repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
leafclick/intellij-community | platform/platform-impl/src/com/intellij/ui/ColorChooserServiceImpl.java | 1894 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.util.List;
/**
* @author Konstantin Bulenkov
*/
public class ColorChooserServiceImpl extends ColorChooserService {
@Nullable
@Override
public Color showDialog(Component parent,
String caption,
Color preselectedColor,
boolean enableOpacity,
List<? extends ColorPickerListener> listeners,
boolean opacityInPercent) {
return ColorPicker.showDialog(parent, caption, preselectedColor, enableOpacity, listeners, opacityInPercent);
}
@Nullable
@Override
public Color showDialog(Project project,
Component parent,
@Nls(capitalization = Nls.Capitalization.Title) String caption,
Color preselectedColor,
boolean enableOpacity,
List<? extends ColorPickerListener> listeners,
boolean opacityInPercent) {
return showDialog(parent, caption, preselectedColor, enableOpacity, listeners, opacityInPercent);
}
}
| apache-2.0 |
HomHomLin/weex | android/sdk/src/main/java/com/taobao/weex/ui/view/listview/loadmore/DefaultLoadMoreView.java | 15239 | /**
*
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "[]"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright 2016 Alibaba Group
*
* 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.taobao.weex.ui.view.listview.loadmore;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by Linhh on 15/11/15.
*/
public class DefaultLoadMoreView extends BaseLoadMoreView {
private Paint paint;
private RectF oval;
private int mCircleSize = 25;
private int mProgress = 30;//圆圈比例
private int mCircleOffset = 70;
private boolean mLoading = true;
public DefaultLoadMoreView(Context context, RecyclerView recyclerView) {
super(context, recyclerView);
paint = new Paint();
oval = new RectF();
setLoadmoreString("加载中...");
// mLoadMoreString = context.getString(R.string.loading);
}
public void setLoading(boolean loading){
mLoading = loading;
}
public void updateProgress(){
mProgress = mProgress + 5;
if(mProgress == 100){
mProgress = 0;
}
}
@Override
public void onDrawLoadMore(Canvas c, RecyclerView parent) {
super.onDrawLoadMore(c,parent);
final int left = parent.getPaddingLeft() ;
final int right = parent.getMeasuredWidth() - parent.getPaddingRight() ;
final int childSize = parent.getChildCount() ;
final View child = parent.getChildAt( childSize - 1 ) ;
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
final int top = child.getBottom() + layoutParams.bottomMargin ;
final int bottom = top + getLoadMorePadding()/2 ;
if(mLoading) {
paint.setAntiAlias(true);// 抗锯齿
paint.setFlags(Paint.ANTI_ALIAS_FLAG);// 增强消除锯齿
paint.setColor(Color.GRAY);// 画笔为灰色
paint.setStrokeWidth(10);// 画笔宽度
paint.setStyle(Paint.Style.STROKE);// 中空
c.drawCircle((right - left) / 2 - mCircleOffset, bottom, mCircleSize, paint);//在中心为((right - left)/2,bottom)的地方画个半径为mCircleSize的圆,
paint.setColor(Color.GREEN);// 设置画笔为绿色
oval.set((right - left) / 2 - mCircleOffset - mCircleSize, bottom - mCircleSize, (right - left) / 2 - mCircleOffset + mCircleSize, bottom + mCircleSize);// 在Circle小于圈圈大小的地方画圆,这样也就保证了半径为mCircleSize
c.drawArc(oval, -90, ((float) mProgress / 100) * 360, false, paint);// 圆弧,第二个参数为:起始角度,第三个为跨的角度,第四个为true的时候是实心,false的时候为空心
}
paint.reset();// 将画笔重置
paint.setAntiAlias(true);// 抗锯齿
paint.setFlags(Paint.ANTI_ALIAS_FLAG);// 增强消除锯齿
paint.setStrokeWidth(3);// 再次设置画笔的宽度
paint.setTextSize(40);// 设置文字的大小
paint.setColor(Color.BLACK);// 设置画笔颜色
if(mLoading) {
c.drawText(getLoadmoreString(), (right - left) / 2, bottom + 10, paint);
}else{
c.drawText(getLoadmoreString(), (right - left) / 2 - mCircleOffset, bottom + 10, paint);
}
}
}
| apache-2.0 |
kusid/herd | herd-code/herd-tools/herd-uploader/src/test/java/org/finra/herd/tools/uploader/UploaderWebClientTest.java | 10712 | /*
* Copyright 2015 herd 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.finra.herd.tools.uploader;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.JAXBException;
import org.junit.Assert;
import org.junit.Test;
import org.finra.herd.dao.impl.MockHttpClientOperationsImpl;
import org.finra.herd.model.api.xml.AwsCredential;
import org.finra.herd.model.api.xml.BusinessObjectDataKey;
import org.finra.herd.model.api.xml.BusinessObjectDataUploadCredential;
import org.finra.herd.model.api.xml.BusinessObjectDataVersions;
import org.finra.herd.model.dto.DataBridgeBaseManifestDto;
import org.finra.herd.model.dto.RegServerAccessParamsDto;
/**
* Unit tests for UploaderWebClient class.
*/
public class UploaderWebClientTest extends AbstractUploaderTest
{
@Test
public void testGetBusinessObjectDataUploadCredential1() throws Exception
{
DataBridgeBaseManifestDto manifest = new DataBridgeBaseManifestDto();
manifest.setNamespace("test1");
manifest.setBusinessObjectDefinitionName("test2");
manifest.setBusinessObjectFormatUsage("test3");
manifest.setBusinessObjectFormatFileType("test4");
manifest.setBusinessObjectFormatVersion("test5");
manifest.setPartitionValue("test6");
manifest.setSubPartitionValues(Arrays.asList("test7", "test8"));
String storageName = "test8";
Integer businessObjectDataVersion = 1234;
Boolean createNewVersion = false;
uploaderWebClient.getRegServerAccessParamsDto().setUseSsl(false);
BusinessObjectDataUploadCredential businessObjectDataUploadCredential =
uploaderWebClient.getBusinessObjectDataUploadCredential(manifest, storageName, businessObjectDataVersion, createNewVersion);
Assert.assertNotNull(businessObjectDataUploadCredential);
AwsCredential awsCredential = businessObjectDataUploadCredential.getAwsCredential();
Assert.assertNotNull(awsCredential);
Assert.assertEquals("http://testWebServiceHostname:1234/herd-app/rest/businessObjectData/upload/credential/namespaces/test1" +
"/businessObjectDefinitionNames/test2/businessObjectFormatUsages/test3/businessObjectFormatFileTypes/test4/businessObjectFormatVersions/test5" +
"/partitionValues/test6?storageName=test8&subPartitionValues=test7%7Ctest8&businessObjectDataVersion=1234&createNewVersion=false",
awsCredential.getAwsAccessKey());
}
@Test
public void testGetBusinessObjectDataUploadCredential2() throws Exception
{
DataBridgeBaseManifestDto manifest = new DataBridgeBaseManifestDto();
manifest.setNamespace("test1");
manifest.setBusinessObjectDefinitionName("test2");
manifest.setBusinessObjectFormatUsage("test3");
manifest.setBusinessObjectFormatFileType("test4");
manifest.setBusinessObjectFormatVersion("test5");
manifest.setPartitionValue("test6");
String storageName = "test8";
Integer businessObjectDataVersion = 1234;
Boolean createNewVersion = null;
uploaderWebClient.getRegServerAccessParamsDto().setUseSsl(true);
BusinessObjectDataUploadCredential businessObjectDataUploadCredential =
uploaderWebClient.getBusinessObjectDataUploadCredential(manifest, storageName, businessObjectDataVersion, createNewVersion);
Assert.assertNotNull(businessObjectDataUploadCredential);
AwsCredential awsCredential = businessObjectDataUploadCredential.getAwsCredential();
Assert.assertNotNull(awsCredential);
Assert.assertEquals("https://testWebServiceHostname:1234/herd-app/rest/businessObjectData/upload/credential/namespaces/test1" +
"/businessObjectDefinitionNames/test2/businessObjectFormatUsages/test3/businessObjectFormatFileTypes/test4/businessObjectFormatVersions/test5" +
"/partitionValues/test6?storageName=test8&businessObjectDataVersion=1234", awsCredential.getAwsAccessKey());
}
@Test
public void testGetBusinessObjectDataUploadCredential3() throws Exception
{
DataBridgeBaseManifestDto manifest = new DataBridgeBaseManifestDto();
manifest.setNamespace("test1");
manifest.setBusinessObjectDefinitionName("test2");
manifest.setBusinessObjectFormatUsage("test3");
manifest.setBusinessObjectFormatFileType("test4");
manifest.setBusinessObjectFormatVersion("test5");
manifest.setPartitionValue("test6");
manifest.setSubPartitionValues(Arrays.asList("test7", "test8"));
String storageName = "test8";
Integer businessObjectDataVersion = null;
Boolean createNewVersion = true;
uploaderWebClient.getRegServerAccessParamsDto().setUseSsl(true);
BusinessObjectDataUploadCredential businessObjectDataUploadCredential =
uploaderWebClient.getBusinessObjectDataUploadCredential(manifest, storageName, businessObjectDataVersion, createNewVersion);
Assert.assertNotNull(businessObjectDataUploadCredential);
AwsCredential awsCredential = businessObjectDataUploadCredential.getAwsCredential();
Assert.assertNotNull(awsCredential);
Assert.assertEquals("https://testWebServiceHostname:1234/herd-app/rest/businessObjectData/upload/credential/namespaces/test1" +
"/businessObjectDefinitionNames/test2/businessObjectFormatUsages/test3/businessObjectFormatFileTypes/test4/businessObjectFormatVersions/test5" +
"/partitionValues/test6?storageName=test8&subPartitionValues=test7%7Ctest8&createNewVersion=true", awsCredential.getAwsAccessKey());
}
@Test
public void testGetBusinessObjectDataVersions() throws Exception
{
testGetBusinessObjectDataVersions(null, null, null, false);
}
@Test
public void testGetBusinessObjectDataVersionsUseSsl() throws Exception
{
testGetBusinessObjectDataVersions(null, null, null, true);
}
@Test
public void testGetBusinessObjectDataVersionsWithBusinessObjectDataVersion() throws Exception
{
testGetBusinessObjectDataVersions(null, null, 5678, true);
}
@Test
public void testGetBusinessObjectDataVersionsWithBusinessObjectFormatVersion() throws Exception
{
testGetBusinessObjectDataVersions(null, 1234, null, true);
}
@Test
public void testGetBusinessObjectDataVersionsWithSubPartitions() throws Exception
{
testGetBusinessObjectDataVersions(Arrays.asList("testSubPartitionValue1", "testSubPartitionValue2", "testSubPartitionValue3", "testSubPartitionValue4"),
null, null, true);
}
@Test
public void testUpdateBusinessObjectDataStatusIgnoreException() throws Exception
{
uploaderWebClient.getRegServerAccessParamsDto().setRegServerHost(MockHttpClientOperationsImpl.HOSTNAME_THROW_IO_EXCEPTION_DURING_UPDATE_BDATA_STATUS);
BusinessObjectDataKey businessObjectDataKey = new BusinessObjectDataKey();
String businessObjectDataStatus = "testBusinessObjectDataStatus";
executeWithoutLogging(UploaderWebClient.class, () -> {
uploaderWebClient.updateBusinessObjectDataStatusIgnoreException(businessObjectDataKey, businessObjectDataStatus);
});
}
@Test
public void testWebClientRegServerAccessParamsDtoSetterAndGetter()
{
// Create and initialize an instance of RegServerAccessParamsDto.
RegServerAccessParamsDto regServerAccessParamsDto = new RegServerAccessParamsDto();
regServerAccessParamsDto.setRegServerHost(WEB_SERVICE_HOSTNAME);
regServerAccessParamsDto.setRegServerPort(WEB_SERVICE_HTTPS_PORT);
regServerAccessParamsDto.setUseSsl(true);
regServerAccessParamsDto.setUsername(WEB_SERVICE_HTTPS_USERNAME);
regServerAccessParamsDto.setPassword(WEB_SERVICE_HTTPS_PASSWORD);
// Set the DTO.
uploaderWebClient.setRegServerAccessParamsDto(regServerAccessParamsDto);
// Retrieve the DTO and validate the results.
RegServerAccessParamsDto resultRegServerAccessParamsDto = uploaderWebClient.getRegServerAccessParamsDto();
// validate the results.
assertEquals(WEB_SERVICE_HOSTNAME, resultRegServerAccessParamsDto.getRegServerHost());
assertEquals(WEB_SERVICE_HTTPS_PORT, resultRegServerAccessParamsDto.getRegServerPort());
assertTrue(resultRegServerAccessParamsDto.isUseSsl());
assertEquals(WEB_SERVICE_HTTPS_USERNAME, resultRegServerAccessParamsDto.getUsername());
assertEquals(WEB_SERVICE_HTTPS_PASSWORD, resultRegServerAccessParamsDto.getPassword());
}
/**
* Calls getBusinessObjectDataVersions() method and makes assertions.
*
* @param subPartitionValues the list of sub-partition values
* @param businessObjectFormatVersion the business object format version
* @param businessObjectDataVersion the business object data version
* @param useSsl specifies whether to use SSL or not
*
* @throws java.io.IOException
* @throws javax.xml.bind.JAXBException
* @throws java.net.URISyntaxException
*/
private void testGetBusinessObjectDataVersions(List<String> subPartitionValues, Integer businessObjectFormatVersion, Integer businessObjectDataVersion,
boolean useSsl) throws IOException, JAXBException, URISyntaxException
{
uploaderWebClient.getRegServerAccessParamsDto().setUseSsl(useSsl);
BusinessObjectDataKey businessObjectDataKey = new BusinessObjectDataKey();
businessObjectDataKey.setBusinessObjectFormatVersion(businessObjectFormatVersion);
businessObjectDataKey.setSubPartitionValues(subPartitionValues);
businessObjectDataKey.setBusinessObjectDataVersion(businessObjectDataVersion);
BusinessObjectDataVersions businessObjectDataVersions = uploaderWebClient.getBusinessObjectDataVersions(businessObjectDataKey);
assertNotNull("businessObjectDataVersions", businessObjectDataVersions);
}
}
| apache-2.0 |
paplorinc/intellij-community | platform/util/src/com/intellij/openapi/util/DefaultJDOMExternalizer.java | 10740 | /*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.openapi.util;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.BitUtil;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.xmlb.annotations.Transient;
import org.jdom.Element;
import org.jdom.Verifier;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
/**
* @deprecated {@link com.intellij.util.xmlb.XmlSerializer} should be used instead
* @author mike
*/
@Deprecated
@SuppressWarnings("HardCodedStringLiteral")
public class DefaultJDOMExternalizer {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.DefaultJDOMExternalizer");
private DefaultJDOMExternalizer() {
}
public interface JDOMFilter{
boolean isAccept(@NotNull Field field);
}
public static void writeExternal(@NotNull Object data, @NotNull Element parentNode) throws WriteExternalException {
writeExternal(data, parentNode, null);
}
public static void writeExternal(@NotNull Object data,
@NotNull Element parentNode,
@Nullable("null means all elements accepted") JDOMFilter filter) throws WriteExternalException {
Field[] fields = data.getClass().getFields();
for (Field field : fields) {
if (field.getName().indexOf('$') >= 0) continue;
int modifiers = field.getModifiers();
if (!(Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) &&
/*!Modifier.isFinal(modifiers) &&*/ !Modifier.isTransient(modifiers) &&
field.getAnnotation(Transient.class) == null)) continue;
field.setAccessible(true); // class might be non-public
Class type = field.getType();
if (filter != null && !filter.isAccept(field) || field.getDeclaringClass().getAnnotation(Transient.class) != null) {
continue;
}
String value = null;
try {
if (type.isPrimitive()) {
if (type.equals(byte.class)) {
value = Byte.toString(field.getByte(data));
}
else if (type.equals(short.class)) {
value = Short.toString(field.getShort(data));
}
else if (type.equals(int.class)) {
value = Integer.toString(field.getInt(data));
}
else if (type.equals(long.class)) {
value = Long.toString(field.getLong(data));
}
else if (type.equals(float.class)) {
value = Float.toString(field.getFloat(data));
}
else if (type.equals(double.class)) {
value = Double.toString(field.getDouble(data));
}
else if (type.equals(char.class)) {
value = String.valueOf(field.getChar(data));
}
else if (type.equals(boolean.class)) {
value = Boolean.toString(field.getBoolean(data));
}
else {
continue;
}
}
else if (type.equals(String.class)) {
value = filterXMLCharacters((String)field.get(data));
}
else if (type.isEnum()) {
value = field.get(data).toString();
}
else if (type.equals(Color.class)) {
Color color = (Color)field.get(data);
if (color != null) {
value = Integer.toString(color.getRGB() & 0xFFFFFF, 16);
}
}
else if (ReflectionUtil.isAssignable(JDOMExternalizable.class, type)) {
Element element = new Element("option");
parentNode.addContent(element);
element.setAttribute("name", field.getName());
JDOMExternalizable domValue = (JDOMExternalizable)field.get(data);
if (domValue != null) {
Element valueElement = new Element("value");
element.addContent(valueElement);
domValue.writeExternal(valueElement);
}
continue;
}
else {
LOG.debug("Wrong field type: " + type);
continue;
}
}
catch (IllegalAccessException e) {
continue;
}
Element element = new Element("option");
parentNode.addContent(element);
element.setAttribute("name", field.getName());
if (value != null) {
element.setAttribute("value", value);
}
}
}
@Nullable
static String filterXMLCharacters(@Nullable String value) {
if (value == null) {
return null;
}
StringBuilder builder = null;
for (int i=0; i<value.length();i++) {
char c = value.charAt(i);
if (Verifier.isXMLCharacter(c)) {
if (builder != null) {
builder.append(c);
}
}
else {
if (builder == null) {
builder = new StringBuilder(value.length()+5);
builder.append(value, 0, i);
}
}
}
if (builder != null) {
value = builder.toString();
}
return value;
}
public static void readExternal(@NotNull Object data, Element parentNode) throws InvalidDataException{
if (parentNode == null) return;
for (Element e : parentNode.getChildren("option")) {
String fieldName = e.getAttributeValue("name");
if (fieldName == null) {
throw new InvalidDataException();
}
try {
Field field = data.getClass().getField(fieldName);
Class type = field.getType();
int modifiers = field.getModifiers();
if (!BitUtil.isSet(modifiers, Modifier.PUBLIC) || BitUtil.isSet(modifiers, Modifier.STATIC)) continue;
field.setAccessible(true); // class might be non-public
if (BitUtil.isSet(modifiers, Modifier.FINAL)) {
// read external contents of final field
Object value = field.get(data);
if (value instanceof JDOMExternalizable) {
final List children = e.getChildren("value");
for (Object child : children) {
Element valueTag = (Element)child;
((JDOMExternalizable)value).readExternal(valueTag);
}
}
continue;
}
String value = e.getAttributeValue("value");
if (type.isPrimitive()) {
if (value != null) {
if (type.equals(byte.class)) {
try {
field.setByte(data, Byte.parseByte(value));
}
catch (NumberFormatException ex) {
throw new InvalidDataException();
}
}
else if (type.equals(short.class)) {
try {
field.setShort(data, Short.parseShort(value));
}
catch (NumberFormatException ex) {
throw new InvalidDataException();
}
}
else if (type.equals(int.class)) {
int i = toInt(value);
field.setInt(data, i);
}
else if (type.equals(long.class)) {
try {
field.setLong(data, Long.parseLong(value));
}
catch (NumberFormatException ex) {
throw new InvalidDataException();
}
}
else if (type.equals(float.class)) {
try {
field.setFloat(data, Float.parseFloat(value));
}
catch (NumberFormatException ex) {
throw new InvalidDataException();
}
}
else if (type.equals(double.class)) {
try {
field.setDouble(data, Double.parseDouble(value));
}
catch (NumberFormatException ex) {
throw new InvalidDataException();
}
}
else if (type.equals(char.class)) {
if (value.length() != 1) {
throw new InvalidDataException();
}
field.setChar(data, value.charAt(0));
}
else if (type.equals(boolean.class)) {
if (value.equals("true")) {
field.setBoolean(data, true);
}
else if (value.equals("false")) {
field.setBoolean(data, false);
}
else {
throw new InvalidDataException();
}
}
else {
throw new InvalidDataException();
}
}
}
else if (type.isEnum()) {
for (Object enumValue : type.getEnumConstants()) {
if (enumValue.toString().equals(value)) {
field.set(data, enumValue);
break;
}
}
}
else if (type.equals(String.class)) {
field.set(data, value);
}
else if (type.equals(Color.class)) {
Color color = toColor(value);
field.set(data, color);
}
else if (ReflectionUtil.isAssignable(JDOMExternalizable.class, type)) {
final List<Element> children = e.getChildren("value");
if (!children.isEmpty()) {
// compatibility with Selena's serialization which writes an empty tag for a bean which has a default value
JDOMExternalizable object = null;
for (Element element : children) {
object = (JDOMExternalizable)type.newInstance();
object.readExternal(element);
}
field.set(data, object);
}
}
else {
throw new InvalidDataException("wrong type: " + type);
}
}
catch (NoSuchFieldException ignore) {
}
catch (SecurityException | InstantiationException ex) {
throw new InvalidDataException();
}
catch (IllegalAccessException ex) {
throw new InvalidDataException(ex);
}
}
}
public static int toInt(@NotNull String value) throws InvalidDataException {
int i;
try {
i = Integer.parseInt(value);
}
catch (NumberFormatException ex) {
throw new InvalidDataException(value, ex);
}
return i;
}
public static Color toColor(@Nullable String value) throws InvalidDataException {
Color color;
if (value == null) {
color = null;
}
else {
try {
int rgb = Integer.parseInt(value, 16);
color = new Color(rgb);
}
catch (NumberFormatException ex) {
LOG.debug("Wrong color value: " + value, ex);
throw new InvalidDataException("Wrong color value: " + value, ex);
}
}
return color;
}
}
| apache-2.0 |
YoungDigitalPlanet/empiria.player | src/main/java/eu/ydp/empiria/player/client/controller/session/SessionDataCarrier.java | 2166 | /*
* Copyright 2017 Young Digital Planet S.A.
*
* 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 eu.ydp.empiria.player.client.controller.session;
import com.google.gwt.core.client.JavaScriptObject;
public class SessionDataCarrier {
public SessionDataCarrier() {
}
public int[] dones;
public int[] todos;
public int[] times;
public int[] checks;
public int[] mistakes;
public boolean[] visiteds;
public int doneTotal;
public int todoTotal;
public int timeTotal;
public int visitedCount;
public JavaScriptObject toJsObject() {
return createJsObject();
}
private native JavaScriptObject createJsObject()/*-{
var obj = [];
var instance = this;
obj.getTimeTotal = function () {
return instance.@eu.ydp.empiria.player.client.controller.session.SessionDataCarrier::timeTotal;
}
obj.getVariableTotalValue = function () {
return instance.@eu.ydp.empiria.player.client.controller.session.SessionDataCarrier::timeTotal;
}
obj.getDoneTotal = function () {
return instance.@eu.ydp.empiria.player.client.controller.session.SessionDataCarrier::doneTotal;
}
obj.getTodoTotal = function () {
return instance.@eu.ydp.empiria.player.client.controller.session.SessionDataCarrier::todoTotal;
}
obj.getVisitedCount = function () {
return instance.@eu.ydp.empiria.player.client.controller.session.SessionDataCarrier::visitedCount;
}
return obj;
}-*/;
}
| apache-2.0 |
MoebiusSolutions/mscapi-agent | src/main/java/com/moesol/url/MscapiHookingAgent.java | 1253 | package com.moesol.url;
import java.lang.instrument.Instrumentation;
public class MscapiHookingAgent {
public static boolean DEBUG = false;
public static String CONTEXT = "TLS";
public static void premain(String args, Instrumentation inst) throws Exception {
System.out.println("MSCAPI Agent hooking SSL with args: " + args);
if (args != null) {
processArgs(args);
}
Config config = Config.loadFromUserHome();
maybeSetTrustSystemProperties(config);
SwingSelectorKeyManager.configureSwingKeyManagerAsDefault();
}
private static void maybeSetTrustSystemProperties(Config config) {
if (config.isUseWindowsTrust()) {
System.setProperty("javax.net.ssl.trustStoreType", "Windows-ROOT");
System.setProperty("javax.net.ssl.trustStore", "NONE");
}
}
static void processArgs(String args) {
String[] split = args.split(",\\s*");
for (String s : split) {
if (s.equals("debug")) {
DEBUG = true;
}
if (s.startsWith("context=")) {
CONTEXT = s.replace("context=", "");
}
if (s.equals("help")) {
showHelp();
}
}
}
private static void showHelp() {
System.out.println("Options: debug | context={c} | help");
System.out.println("{c} -- SSL, SSLv2, SSLv3, TLS, TLSv1, TLSv1.1, TLSv1.2");
}
}
| apache-2.0 |
Alphagfx/Kliander | core/src/com/alphagfx/kliander/actors/Obstacle.java | 1957 | // Copyright Kliander Alphagfx
//
// 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.alphagfx.kliander.actors;
import com.alphagfx.kliander.enums.UserDataType;
import com.alphagfx.kliander.utils.WorldUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.World;
public class Obstacle extends GameActor {
public Obstacle(Body body) {
super(body);
setUserDataType(UserDataType.OBSTACLE);
setInvincible(true);
}
@Override
protected void moveTo(Vector2 target) {
}
@Override
protected void turnTo(float angle) {
}
@Override
protected void fire(Vector2 target) {
}
@Override
protected void specialAction(String name, Object... objects) {
}
public static class Factory implements com.alphagfx.kliander.actors.Factory<Obstacle> {
@Override
public Obstacle create(World world, Vector2 position, float angle, Object... objects) {
if (objects.length == 2 && objects[0] instanceof Float && objects[1] instanceof Float) {
return new Obstacle(WorldUtils.createObstacle(world, position, ((float) objects[0]), ((float) objects[1])));
} else {
return new Obstacle(WorldUtils.createObstacle(world, position, 1, 1));
}
}
}
}
| apache-2.0 |
nafae/developer | modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201402/cm/AdGroupCriterionServiceInterface.java | 2029 | /**
* AdGroupCriterionServiceInterface.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.adwords.axis.v201402.cm;
public interface AdGroupCriterionServiceInterface extends java.rmi.Remote {
/**
* Gets adgroup criteria.
*
*
* @param serviceSelector filters the adgroup criteria to be returned.
*
* @return a page (subset) view of the criteria selected
*
* @throws ApiException when there is at least one error with the request
*/
public com.google.api.ads.adwords.axis.v201402.cm.AdGroupCriterionPage get(com.google.api.ads.adwords.axis.v201402.cm.Selector serviceSelector) throws java.rmi.RemoteException, com.google.api.ads.adwords.axis.v201402.cm.ApiException;
/**
* Adds, removes or updates adgroup criteria.
*
*
* @param operations operations to do
* during checks on keywords to be added.
*
* @return added and updated adgroup criteria (without optional parts)
*
* @throws ApiException when there is at least one error with the request
*/
public com.google.api.ads.adwords.axis.v201402.cm.AdGroupCriterionReturnValue mutate(com.google.api.ads.adwords.axis.v201402.cm.AdGroupCriterionOperation[] operations) throws java.rmi.RemoteException, com.google.api.ads.adwords.axis.v201402.cm.ApiException;
/**
* Returns the list of AdGroupCriterion that match the query.
*
*
* @param query The SQL-like AWQL query string
*
* @returns A list of AdGroupCriterion
*
* @throws ApiException when the query is invalid or there are errors
* processing the request.
*/
public com.google.api.ads.adwords.axis.v201402.cm.AdGroupCriterionPage query(java.lang.String query) throws java.rmi.RemoteException, com.google.api.ads.adwords.axis.v201402.cm.ApiException;
}
| apache-2.0 |
CamelCookbook/camel-cookbook-examples | 10-runtimes/runtime-wildfly-swarm/src/main/java/org/camelcookbook/runtimes/swarm/CamelRoutes.java | 1881 | /*
* Copyright (C) Scott Cranton, Jakub Korab, and Christian Posta
* https://github.com/CamelCookbook
*
* 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.camelcookbook.runtimes.swarm;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.cdi.ContextName;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.model.rest.RestBindingMode;
import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.container.runtime.cdi.ConfigViewProducingExtension;
import org.wildfly.swarm.container.runtime.cdi.ConfigurationValueProducer;
import org.wildfly.swarm.spi.runtime.annotations.ConfigurationValue;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;
@ApplicationScoped
@ContextName("cdi-context")
public class CamelRoutes extends RouteBuilder {
@Inject
@ConfigurationValue("swarm.camel.foo.name")
private String name;
@Override
public void configure() throws Exception {
restConfiguration().component("undertow")
.contextPath("/rest").bindingMode(RestBindingMode.auto);
rest()
.get("/greetings/{name}").produces("text/plain")
.route().transform(simple("Hello ${header.name} from " + name));
}
}
| apache-2.0 |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/generation/surroundWith/SurroundWithHandler.java | 12152 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.generation.surroundWith;
import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.template.TemplateManager;
import com.intellij.codeInsight.template.impl.SurroundWithLogger;
import com.intellij.codeInsight.template.impl.SurroundWithTemplateHandler;
import com.intellij.ide.DataManager;
import com.intellij.ide.IdeBundle;
import com.intellij.idea.ActionsBundle;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageSurrounders;
import com.intellij.lang.folding.CustomFoldingSurroundDescriptor;
import com.intellij.lang.surroundWith.SurroundDescriptor;
import com.intellij.lang.surroundWith.Surrounder;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiCompiledElement;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.refactoring.rename.inplace.InplaceRefactoring;
import com.intellij.util.DocumentUtil;
import com.intellij.util.text.CharArrayUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class SurroundWithHandler implements CodeInsightActionHandler {
public static final TextRange CARET_IS_OK = new TextRange(0, 0);
@Override
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull PsiFile file) {
invoke(project, editor, file, null);
}
@Override
public boolean startInWriteAction() {
return false;
}
public static void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file, Surrounder surrounder) {
if (!EditorModificationUtil.checkModificationAllowed(editor)) return;
if (file instanceof PsiCompiledElement) {
HintManager.getInstance().showErrorHint(editor, "Can't modify decompiled code");
return;
}
List<AnAction> applicable = buildSurroundActions(project, editor, file, surrounder);
if (applicable != null) {
showPopup(editor, applicable);
}
else if (!ApplicationManager.getApplication().isUnitTestMode()) {
HintManager.getInstance().showErrorHint(editor, "Couldn't find Surround With variants applicable to the current context");
}
}
@Nullable
public static List<AnAction> buildSurroundActions(final Project project, final Editor editor, PsiFile file, @Nullable Surrounder surrounder){
SelectionModel selectionModel = editor.getSelectionModel();
boolean hasSelection = selectionModel.hasSelection();
if (!hasSelection) {
selectLogicalLineContentsAtCaret(editor);
}
int startOffset = selectionModel.getSelectionStart();
int endOffset = selectionModel.getSelectionEnd();
PsiElement element1 = file.findElementAt(startOffset);
PsiElement element2 = file.findElementAt(endOffset - 1);
if (element1 == null || element2 == null) return null;
TextRange textRange = new TextRange(startOffset, endOffset);
for(SurroundWithRangeAdjuster adjuster: SurroundWithRangeAdjuster.EP_NAME.getExtensionList()) {
textRange = adjuster.adjustSurroundWithRange(file, textRange, hasSelection);
if (textRange == null) return null;
}
startOffset = textRange.getStartOffset();
endOffset = textRange.getEndOffset();
element1 = file.findElementAt(startOffset);
final Language baseLanguage = file.getViewProvider().getBaseLanguage();
assert element1 != null;
final Language l = element1.getParent().getLanguage();
List<SurroundDescriptor> surroundDescriptors = new ArrayList<>(LanguageSurrounders.INSTANCE.allForLanguage(l));
if (l != baseLanguage) surroundDescriptors.addAll(LanguageSurrounders.INSTANCE.allForLanguage(baseLanguage));
surroundDescriptors.add(CustomFoldingSurroundDescriptor.INSTANCE);
int exclusiveCount = 0;
List<SurroundDescriptor> exclusiveSurroundDescriptors = new ArrayList<>();
for (SurroundDescriptor sd : surroundDescriptors) {
if (sd.isExclusive()) {
exclusiveCount++;
exclusiveSurroundDescriptors.add(sd);
}
}
if (exclusiveCount > 0) {
surroundDescriptors = exclusiveSurroundDescriptors;
}
if (surrounder != null) {
invokeSurrounderInTests(project, editor, file, surrounder, startOffset, endOffset, surroundDescriptors);
return null;
}
Map<Surrounder, PsiElement[]> surrounders = new LinkedHashMap<>();
for (SurroundDescriptor descriptor : surroundDescriptors) {
final PsiElement[] elements = descriptor.getElementsToSurround(file, startOffset, endOffset);
if (elements.length > 0) {
for (PsiElement element : elements) {
assert element != null : "descriptor " + descriptor + " returned null element";
assert element.isValid() : descriptor;
}
for (Surrounder s: descriptor.getSurrounders()) {
surrounders.put(s, elements);
}
}
}
return doBuildSurroundActions(project, editor, file, surrounders);
}
public static void selectLogicalLineContentsAtCaret(Editor editor) {
int caretOffset = editor.getCaretModel().getOffset();
Document document = editor.getDocument();
CharSequence text = document.getImmutableCharSequence();
editor.getSelectionModel().setSelection(CharArrayUtil.shiftForward(text, DocumentUtil.getLineStartOffset(caretOffset, document), " \t"),
CharArrayUtil.shiftBackward(text, DocumentUtil.getLineEndOffset(caretOffset, document) - 1, " \t") + 1);
}
private static void invokeSurrounderInTests(Project project,
Editor editor,
PsiFile file,
Surrounder surrounder,
int startOffset,
int endOffset, List<? extends SurroundDescriptor> surroundDescriptors) {
assert ApplicationManager.getApplication().isUnitTestMode();
for (SurroundDescriptor descriptor : surroundDescriptors) {
final PsiElement[] elements = descriptor.getElementsToSurround(file, startOffset, endOffset);
if (elements.length > 0) {
for (Surrounder descriptorSurrounder : descriptor.getSurrounders()) {
if (surrounder.getClass().equals(descriptorSurrounder.getClass())) {
WriteCommandAction.runWriteCommandAction(project, () -> doSurround(project, editor, surrounder, elements));
return;
}
}
}
}
}
private static void showPopup(Editor editor, List<AnAction> applicable) {
DataContext context = DataManager.getInstance().getDataContext(editor.getContentComponent());
JBPopupFactory.ActionSelectionAid mnemonics = JBPopupFactory.ActionSelectionAid.MNEMONICS;
DefaultActionGroup group = new DefaultActionGroup(applicable.toArray(AnAction.EMPTY_ARRAY));
JBPopupFactory.getInstance().createActionGroupPopup(CodeInsightBundle.message("surround.with.chooser.title"), group, context, mnemonics, true).showInBestPositionFor(editor);
}
static void doSurround(final Project project, final Editor editor, final Surrounder surrounder, final PsiElement[] elements) {
PsiDocumentManager.getInstance(project).commitAllDocuments();
int col = editor.getCaretModel().getLogicalPosition().column;
int line = editor.getCaretModel().getLogicalPosition().line;
if (!editor.getCaretModel().supportsMultipleCarets()) {
LogicalPosition pos = new LogicalPosition(0, 0);
editor.getCaretModel().moveToLogicalPosition(pos);
}
TextRange range = surrounder.surroundElements(project, editor, elements);
if (range != CARET_IS_OK) {
if (TemplateManager.getInstance(project).getActiveTemplate(editor) == null &&
InplaceRefactoring.getActiveInplaceRenamer(editor) == null) {
LogicalPosition pos1 = new LogicalPosition(line, col);
editor.getCaretModel().moveToLogicalPosition(pos1);
}
if (range != null) {
int offset = range.getStartOffset();
editor.getCaretModel().removeSecondaryCarets();
editor.getCaretModel().moveToOffset(offset);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset());
}
}
}
@Nullable
private static List<AnAction> doBuildSurroundActions(Project project,
Editor editor,
PsiFile file,
Map<Surrounder, PsiElement[]> surrounders) {
List<AnAction> applicable = new ArrayList<>();
Set<Character> usedMnemonicsSet = new HashSet<>();
int index = 0;
for (Map.Entry<Surrounder, PsiElement[]> entry : surrounders.entrySet()) {
Surrounder surrounder = entry.getKey();
PsiElement[] elements = entry.getValue();
if (surrounder.isApplicable(elements)) {
char mnemonic;
if (index < 9) {
mnemonic = (char)('0' + index + 1);
}
else if (index == 9) {
mnemonic = '0';
}
else {
mnemonic = (char)('A' + index - 10);
}
index++;
usedMnemonicsSet.add(Character.toUpperCase(mnemonic));
applicable.add(new InvokeSurrounderAction(surrounder, project, editor, elements, mnemonic));
}
}
List<AnAction> templateGroup = SurroundWithTemplateHandler.createActionGroup(editor, file, usedMnemonicsSet);
if (!templateGroup.isEmpty()) {
applicable.add(new Separator(IdeBundle.lazyMessage("action.Anonymous.text.live.templates")));
applicable.addAll(templateGroup);
applicable.add(Separator.getInstance());
applicable.add(new ConfigureTemplatesAction());
}
return applicable.isEmpty() ? null : applicable;
}
private static class InvokeSurrounderAction extends AnAction {
private final Surrounder mySurrounder;
private final Project myProject;
private final Editor myEditor;
private final PsiElement[] myElements;
InvokeSurrounderAction(Surrounder surrounder, Project project, Editor editor, PsiElement[] elements, char mnemonic) {
super(UIUtil.MNEMONIC + String.valueOf(mnemonic) + ". " + surrounder.getTemplateDescription());
mySurrounder = surrounder;
myProject = project;
myEditor = editor;
myElements = elements;
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
if (!FileDocumentManager.getInstance().requestWriting(myEditor.getDocument(), myProject)) {
return;
}
Language language = Language.ANY;
if (myElements != null && myElements.length != 0) {
language = myElements[0].getLanguage();
}
WriteCommandAction.runWriteCommandAction(myProject, () -> doSurround(myProject, myEditor, mySurrounder, myElements));
SurroundWithLogger.logSurrounder(mySurrounder, language, myProject);
}
}
private static class ConfigureTemplatesAction extends AnAction {
private ConfigureTemplatesAction() {
super(ActionsBundle.lazyMessage("action.ConfigureTemplatesAction.text"));
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
ShowSettingsUtil.getInstance().showSettingsDialog(e.getData(CommonDataKeys.PROJECT), "Live Templates");
}
}
}
| apache-2.0 |
webfirmframework/wff | wffweb/src/test/java/com/webfirmframework/wffweb/css/css3/MsFlexTest.java | 11494 | /*
* Copyright 2014-2021 Web Firm Framework
*
* 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.webfirmframework.wffweb.css.css3;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.webfirmframework.wffweb.InvalidValueException;
import com.webfirmframework.wffweb.css.CssLengthUnit;
import com.webfirmframework.wffweb.css.CssNameConstants;
/**
* @author WFF
* @since 1.0.0
* @version 1.0.0
* <pre>
* The undefined value for flex-grow, flex-shrink and flex-basis in flex property is 1, 1 and 0% respectively.
* </pre>
*/
public class MsFlexTest {
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#MsFlex()}.
*/
@Test
public void testMsFlex() {
final MsFlex flex = new MsFlex();
assertEquals("0.0 1.0 auto", flex.getCssValue());
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#MsFlex(java.lang.String)}.
*/
@Test
public void testMsFlexString() {
final MsFlex flex = new MsFlex("2 5 25px");
assertEquals("2.0 5.0 25px", flex.getCssValue());
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#MsFlex(com.webfirmframework.wffweb.css.css3.MsFlex)}.
*/
@Test
public void testMsFlexMsFlex() {
final MsFlex flex = new MsFlex(new MsFlex("2 5 25px"));
assertEquals("2.0 5.0 25px", flex.getCssValue());
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#getCssName()}.
*/
@Test
public void testGetCssName() {
final MsFlex flex = new MsFlex();
assertEquals(CssNameConstants.MS_FLEX, flex.getCssName());
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#getCssValue()}.
*/
@Test
public void testGetCssValue() {
final MsFlex flex = new MsFlex(new MsFlex("2 5 25px"));
assertEquals("2.0 5.0 25px", flex.getCssValue());
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#toString()}.
*/
@Test
public void testToString() {
final MsFlex flex = new MsFlex("2 5 25px");
assertEquals(CssNameConstants.MS_FLEX+": "+flex.getCssValue(),
flex.getCssName() + ": " + flex.getCssValue());
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#setCssValue(java.lang.String)}.
*/
@Test
public void testSetCssValueString() {
final MsFlex flex = new MsFlex();
flex.setCssValue("2 5 25px");
assertEquals(CssNameConstants.MS_FLEX+": "+flex.getCssValue(),
flex.getCssName() + ": " + flex.getCssValue());
assertEquals("2.0 5.0 25px", flex.getCssValue());
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#setCssValue(java.lang.String)}.
*/
@Test(expected = InvalidValueException.class)
public void testSetCssValueStringInvalid() {
final MsFlex flex = new MsFlex();
try {
flex.setCssValue("2 5 25");
} catch (InvalidValueException e) {
try {
flex.setCssValue("fddf");
} catch (InvalidValueException e1) {
throw e1;
}
}
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#isValid(java.lang.String)}.
*/
@Test
public void testIsValid() {
assertTrue(MsFlex.isValid("1"));
assertTrue(MsFlex.isValid("1px"));
assertTrue(MsFlex.isValid("1 1"));
assertTrue(MsFlex.isValid("1 2 3px"));
assertFalse(MsFlex.isValid("1 2 3"));
assertFalse(MsFlex.isValid("1 df"));
assertFalse(MsFlex.isValid("kdfidk"));
assertFalse(MsFlex.isValid("1 2 2 2"));
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#setAsInitial()}.
*/
@Test
public void testSetAsInitial() {
final MsFlex flex = new MsFlex("2 5 25px");
final FlexGrow flexGrow = flex.getFlexGrow();
assertNotNull(flexGrow);
assertTrue(flexGrow.isAlreadyInUse());
final FlexShrink flexShrink = flex.getFlexShrink();
assertNotNull(flexShrink);
assertTrue(flexShrink.isAlreadyInUse());
final FlexBasis flexBasis = flex.getFlexBasis();
assertNotNull(flexBasis);
assertTrue(flexBasis.isAlreadyInUse());
flex.setAsInherit();
assertNull(flex.getFlexGrow());
assertNull(flex.getFlexShrink());
assertNull(flex.getFlexBasis());
assertFalse(flexGrow.isAlreadyInUse());
assertFalse(flexShrink.isAlreadyInUse());
assertFalse(flexBasis.isAlreadyInUse());
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#setAsInherit()}.
*/
@Test
public void testSetAsInherit() {
final MsFlex flex = new MsFlex("2 5 25px");
final FlexGrow flexGrow = flex.getFlexGrow();
assertNotNull(flexGrow);
assertTrue(flexGrow.isAlreadyInUse());
final FlexShrink flexShrink = flex.getFlexShrink();
assertNotNull(flexShrink);
assertTrue(flexShrink.isAlreadyInUse());
final FlexBasis flexBasis = flex.getFlexBasis();
assertNotNull(flexBasis);
assertTrue(flexBasis.isAlreadyInUse());
flex.setAsInherit();
assertNull(flex.getFlexGrow());
assertNull(flex.getFlexShrink());
assertNull(flex.getFlexBasis());
assertFalse(flexGrow.isAlreadyInUse());
assertFalse(flexShrink.isAlreadyInUse());
assertFalse(flexBasis.isAlreadyInUse());
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#getFlexBasis()}.
*/
@Test
public void testGetFlexBasis() {
final MsFlex flex = new MsFlex("2 5 25px");
assertEquals("2.0 5.0 25px", flex.getCssValue());
assertNotNull(flex.getFlexBasis());
assertEquals("25px", flex.getFlexBasis().getCssValue());
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#getFlexShrink()}.
*/
@Test
public void testGetFlexShrink() {
final MsFlex flex = new MsFlex("2 5 25px");
assertEquals("2.0 5.0 25px", flex.getCssValue());
assertNotNull(flex.getFlexShrink());
assertEquals("5.0", flex.getFlexShrink().getCssValue());
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#getFlexGrow()}.
*/
@Test
public void testGetFlexGrow() {
final MsFlex flex = new MsFlex("2 5 25px");
assertEquals("2.0 5.0 25px", flex.getCssValue());
assertNotNull(flex.getFlexGrow());
assertEquals("2.0", flex.getFlexGrow().getCssValue());
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#setFlexGrow(com.webfirmframework.wffweb.css.css3.FlexGrow)}.
*/
@Test
public void testSetFlexGrow() {
final MsFlex flex = new MsFlex("6 5 25px");
final FlexGrow flexGrow1 = flex.getFlexGrow();
final FlexGrow flexGrow2 = new FlexGrow(2);
flex.setFlexGrow(flexGrow2);// here it will show a warning in the console
assertEquals("2.0 5.0 25px", flex.getCssValue());
assertNotNull(flex.getFlexGrow());
assertEquals("2.0", flex.getFlexGrow().getCssValue());
assertNotNull(flex.getFlexShrink());
assertEquals("5.0", flex.getFlexShrink().getCssValue());
assertNotNull(flex.getFlexBasis());
assertEquals("25px", flex.getFlexBasis().getCssValue());
assertNotEquals(flexGrow1, flexGrow2);
assertNotEquals(flexGrow2, flex.getFlexGrow());
assertEquals(flexGrow1, flex.getFlexGrow());
flex.setFlexGrow(flexGrow1);
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#setFlexShrink(com.webfirmframework.wffweb.css.css3.FlexShrink)}.
*/
@Test
public void testSetFlexShrink() {
final MsFlex flex = new MsFlex("6 5 25px");
final FlexShrink flexShrink1 = flex.getFlexShrink();
final FlexShrink flexShrink2 = new FlexShrink(2);
flex.setFlexShrink(flexShrink2);// here it will show a warning in the console
assertEquals("6.0 2.0 25px", flex.getCssValue());
assertNotNull(flex.getFlexGrow());
assertEquals("6.0", flex.getFlexGrow().getCssValue());
assertNotNull(flex.getFlexShrink());
assertEquals("2.0", flex.getFlexShrink().getCssValue());
assertNotNull(flex.getFlexBasis());
assertEquals("25px", flex.getFlexBasis().getCssValue());
assertNotEquals(flexShrink1, flexShrink2);
assertNotEquals(flexShrink2, flex.getFlexShrink());
assertEquals(flexShrink1, flex.getFlexShrink());
flex.setFlexShrink(flexShrink1);
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#setFlexBasis(com.webfirmframework.wffweb.css.css3.FlexBasis)}.
*/
@Test
public void testSetFlexBasis() {
final MsFlex flex = new MsFlex("6 5 25px");
final FlexBasis flexBasis1 = flex.getFlexBasis();
final FlexBasis flexBasis2 = new FlexBasis(2, CssLengthUnit.PX);
flex.setFlexBasis(flexBasis2);// here it will show a warning in the console
assertEquals("6.0 5.0 2.0px", flex.getCssValue());
assertNotNull(flex.getFlexGrow());
assertEquals("6.0", flex.getFlexGrow().getCssValue());
assertNotNull(flex.getFlexShrink());
assertEquals("5.0", flex.getFlexShrink().getCssValue());
assertNotNull(flex.getFlexBasis());
assertEquals("2.0px", flex.getFlexBasis().getCssValue());
assertNotEquals(flexBasis1, flexBasis2);
assertNotEquals(flexBasis2, flex.getFlexBasis());
assertEquals(flexBasis1, flex.getFlexBasis());
flex.setFlexBasis(flexBasis1);
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#stateChanged(com.webfirmframework.wffweb.css.core.CssProperty)}.
*/
@Test
public void testStateChanged() {
//NOP
}
/**
* Test method for {@link com.webfirmframework.wffweb.css.css3.MsFlex#addPredefinedConstant(java.lang.String)}.
*/
@Test
public void testAddPredefinedConstant() {
//TODO not implemented
}
}
| apache-2.0 |
mllweb/Some | app/src/main/java/com/mllweb/some/adapter/MainTabPagerAdapter.java | 768 | package com.mllweb.some.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Android on 2016/7/13.
*/
public class MainTabPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
public MainTabPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
if (fragments != null) {
mFragments = fragments;
}
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
}
| artistic-2.0 |
cmsd2/toyapp | src/com/advancedtelematic/toyapp/MyToyApp.java | 859 | package com.advancedtelematic.toyapp;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Game;
public class MyToyApp extends Game {
private MainScreen mainScreen;
private AboutScreen aboutScreen;
private GameScreen gameScreen;
@Override
public void create() {
setScreen(getMainScreen());
}
public MainScreen getMainScreen() {
if(mainScreen == null) {
this.mainScreen = new MainScreen(this);
}
return mainScreen;
}
public AboutScreen getAboutScreen() {
if(aboutScreen == null) {
this.aboutScreen = new AboutScreen(this);
}
return aboutScreen;
}
public GameScreen getGameScreen() {
if(gameScreen == null) {
this.gameScreen = new GameScreen(this);
}
return gameScreen;
}
}
| bsd-2-clause |
scifio/scifio | src/main/java/io/scif/img/AbstractImgIOComponent.java | 2375 | /*
* #%L
* SCIFIO library for reading and converting scientific file formats.
* %%
* Copyright (C) 2011 - 2021 SCIFIO developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package io.scif.img;
import io.scif.AbstractSCIFIOPlugin;
import io.scif.SCIFIOService;
import org.scijava.Context;
import org.scijava.plugin.Parameter;
import org.scijava.service.SciJavaService;
/**
* Abstract superclass for ImgIOComponents (such as {@link ImgOpener} or
* {@link ImgSaver}). Provides constructors ensuring proper Services are
* available, and an accessor for the {@link ImgUtilityService}.
*
* @author Mark Hiner hinerm@gmail.com
*/
public abstract class AbstractImgIOComponent extends AbstractSCIFIOPlugin {
// -- Fields --
@Parameter
private ImgUtilityService imgUtils;
// -- Constructors --
public AbstractImgIOComponent() {
this(new Context(SCIFIOService.class, SciJavaService.class));
}
public AbstractImgIOComponent(final Context context) {
setContext(context);
}
// -- AbstractImgIOComponent methods --
public ImgUtilityService utils() {
return imgUtils;
}
}
| bsd-2-clause |
zhangjunfang/eclipse-dir | eCardCity2.0/0.card/src/cn/com/newcapec/citycard/account/service/impl/AccountService.java | 4772 | package cn.com.newcapec.citycard.account.service.impl;
import java.util.List;
import cn.com.newcapec.common.domain.Node;
import cn.com.newcapec.common.exception.BusinessException;
import cn.com.newcapec.common.service.impl.BaseService;
import cn.com.newcapec.common.util.StringHelper;
import cn.com.newcapec.citycard.account.dao.IAccountDao;
import cn.com.newcapec.citycard.account.service.IAccountService;
import cn.com.newcapec.citycard.common.po.TOrgUser;
/**
* <pre>
* 功能描述:帐号管理服务接口实现
*
* Author : Wangjian
* Date : 2008-05-05
* Time : 09:52:05
* Version: 1.0
* </pre>
*/
public class AccountService extends BaseService implements IAccountService{
private IAccountDao accountDao;//帐号管理DAO接口
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
/**
* @return the accountDao
*/
public IAccountDao getAccountDao() {
return accountDao;
}
/**
* 功能描述:校验用户帐号
*
* @param username 帐号
* @param password 密码
*
* @return User 用户
*
* @throws BusinessException 业务异常
* */
public TOrgUser validateAccount(String username, String password)
throws BusinessException {
if (username == null || username.length() == 0) {
throw new BusinessException("用户名不能为空!");
}
if (password == null || password.length() == 0) {
throw new BusinessException("密码不能为空!");
}
TOrgUser euser = accountDao.getUserByUsername(username);
if (euser == null) {
throw new BusinessException("该帐号不存在!");
}
/**
* 对密码进行MD5加密后进行与数据库中存储密码的比较
*/
String spassword = null;
try {
spassword = StringHelper.convertToMd5(password);
} catch (Exception e) {
throw new BusinessException("密码格式转换失败!");
}
if (!spassword.equals(euser.getPassword())) {
throw new BusinessException("密码不正确!");
}
if (euser.getValid() != null && euser.getValid().equals("0")) {
throw new BusinessException("该帐号已被禁用,请与系统管理员联系!");
}
if (getRoleCountByUserId(euser.getId()) == 0) {
throw new BusinessException("该帐号没有分配角色,请与系统管理员联系!");
}
if (!getValidByUserId(euser.getId())) {
throw new BusinessException("该账号所在组织机构已被禁止登录,或超过有效期限!");
}
if (!getIPByUserId(euser.getId())) {
throw new BusinessException("该账号登录IP不在组织机构许可IP地址范围内!");
}
return euser;
}
/**
* 根据用户ID得到他是否在系统中已分配角色信息
* @param userId
* @return
* @throws BusinessException
*/
public Integer getRoleCountByUserId(Integer userId)
throws BusinessException {
return accountDao.getRoleCountByUserId(userId);
}
/**
* 根据用户ID得到所在部门(包括父级节点)的状态
* @param userId
* @return
* @throws BusinessException
*/
public Boolean getValidByUserId(Integer userId)
throws BusinessException {
return accountDao.getDepValid(userId);
}
/**
* 根据用户ID得到所在部门(包括父级节点)的IP登录信息
* @param userId
* @return
* @throws BusinessException
*/
public Boolean getIPByUserId(Integer userId)
throws BusinessException {
return accountDao.getIPAuth(userId);
}
/**
* 功能描述:得到用户可操作的模块
*
* @param userId 用户ID号
*
* @return NodeList 用户可操作的功能菜单结点列表
*
* @throws BusinessException 业务异常
* */
public List<Node> getNodeListByUserId(Integer userId)
throws BusinessException {
assert userId != null;
return accountDao.getNodeListByUserId(userId);
}
/* (non-Javadoc)
* @see cn.com.newcapec.citycard.account.service.impl.AccountService#getUserByPk(java.lang.Integer)
*/
public TOrgUser getUserByPk(Integer userId) throws BusinessException{
assert userId != null;
return (TOrgUser)baseDao.get(TOrgUser.class, userId);
}
/**
* 功能描述:获取用户信息
* @param userId 用户ID
* @return TOrgUser
* @throws Exception
*
*/
public void updateUser(TOrgUser user) throws Exception{
assert user != null;
if(!getUserByPk(user.getId()).getPassword().equals(user.getPassword())){
user.setPassword(StringHelper.convertToMd5(user.getPassword()));
}
baseDao.merge(user);
}
/**
* 功能描述:监测输入的旧密码是否正确
*
* @param pwdInput 输入的,未经加密的
* @param pwdDB 数据库的,已经加密的
* @return Boolean
* @throws BusinessException
*/
public boolean checkPasswordSame(String pwdInput,String pwdDB) throws Exception{
return StringHelper.convertToMd5(pwdInput).equals(pwdDB);
}
}
| bsd-2-clause |
Tacohen/Werewolf-Server-Java | src/main/java/edu/wm/something/domain/Kill.java | 1006 | package edu.wm.something.domain;
import java.util.Date;
public class Kill {
private String killerID;
private String victimID;
private Date timestamp;
private float lat;
private float lng;
public String getKillerID() {
return killerID;
}
public void setKillerID(String killerID) {
this.killerID = killerID;
}
public String getVictimID() {
return victimID;
}
public void setVictimID(String victimID) {
this.victimID = victimID;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public float getLat() {
return lat;
}
public void setLat(float lat) {
this.lat = lat;
}
public float getLng() {
return lng;
}
public void setLng(float lng) {
this.lng = lng;
}
public Kill(String killerID, String victimID, Date timestamp, float lat,
float lng) {
super();
this.killerID = killerID;
this.victimID = victimID;
this.timestamp = timestamp;
this.lat = lat;
this.lng = lng;
}
}
| bsd-2-clause |
jupsal/schmies-jTEM | src/de/jtem/riemann/analyticContinuation/AnalyticContinuousIntegratorODE.java | 2562 | /**
This file is part of a jTEM project.
All jTEM projects are licensed under the FreeBSD license
or 2-clause BSD license (see http://www.opensource.org/licenses/bsd-license.php).
Copyright (c) 2002-2009, Technische Universität Berlin, jTEM
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 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 de.jtem.riemann.analyticContinuation;
import de.jtem.blas.ComplexVector;
import de.jtem.numericalMethods.calculus.odeSolving.ODE;
class AnalyticContinuousIntegratorODE extends AnalyticContinuationODE implements ODE {
FunctionSetOnAlgebraicCurve functions;
int numberOfFunctions;
ComplexVector values = new ComplexVector();
public AnalyticContinuousIntegratorODE( AlgebraicCurve curve ) {
super( curve );
}
void setFunctions( FunctionSetOnAlgebraicCurve functions ) {
this.functions = functions;
numberOfFunctions = functions.getNumberOfFunctions();
values.setSize( numberOfFunctions );
}
public int getNumberOfEquations() {
return 4 + numberOfFunctions * 2;
}
public void eval(
double t,
double[] x,
double[] y) {
super.eval( t, x, y );
functions.evaluateFunctions(lambda, mu, Q, dQdLambda, dQdMu, values);
values.assignTimes( direction );
for (int i = 0, j = 4; i < numberOfFunctions; i++, j+=2 ) {
y[j ] = values.re[i];
y[j+1 ] = values.im[i];
}
}
}
| bsd-2-clause |
andysan/jotify | src/de/felixbruns/jotify/api/media/PlaylistContainer.java | 1547 | package de.felixbruns.jotify.api.media;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class PlaylistContainer implements Iterable<Playlist> {
public static final PlaylistContainer EMPTY = new PlaylistContainer();
private String author;
private List<Playlist> playlists;
private long revision;
private long checksum;
public PlaylistContainer(){
this.author = null;
this.playlists = new ArrayList<Playlist>();
this.revision = -1;
this.checksum = -1;
}
public String getAuthor(){
return this.author;
}
public void setAuthor(String author){
this.author = author;
}
public List<Playlist> getPlaylists(){
return this.playlists;
}
public void setPlaylists(List<Playlist> playlists){
this.playlists = playlists;
}
public long getRevision(){
return this.revision;
}
public void setRevision(long revision){
this.revision = revision;
}
/**
* Get and update the checksum of this playlist container.
*
* @return The current checksum.
*/
public long getChecksum(){
Checksum checksum = new Checksum();
for(Playlist playlist : this.playlists){
checksum.update(playlist);
}
this.checksum = checksum.getValue();
return this.checksum;
}
/**
* Set the current checksum of this playlist container.
*
* @param checksum The checksum.
*/
public void setChecksum(long checksum){
this.checksum = checksum;
}
public Iterator<Playlist> iterator(){
return this.playlists.iterator();
}
}
| bsd-2-clause |
Team254/FRC-2013 | src/com/team254/frc2013/subsystems/Intake.java | 2399 | package com.team254.frc2013.subsystems;
import com.team254.frc2013.Constants;
import com.team254.frc2013.WristGains;
import com.team254.frc2013.subsystems.controllers.WristController;
import com.team254.lib.control.ControlOutput;
import com.team254.lib.control.ControlSource;
import com.team254.lib.util.Util;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
* Class designed to control the intake mechanism.
*
* @author art.kalb96@gmail.com (Arthur Kalb)
* @author maskoken@gmail.com (Matthew Koken)
*/
public class Intake extends Subsystem {
private Talon intakeMotor = new Talon(Constants.intakePort.getInt());
private Talon intakePivotMotor = new Talon(Constants.intakePivotPort.getInt());
private Encoder encoder = new Encoder(Constants.intakeEncoderPortA.getInt(),
Constants.intakeEncoderPortB.getInt());
private DigitalInput zeroSensor = new DigitalInput(Constants.intakeZeroSensorPort.getInt());
public Intake() {
encoder.start();
controller.setGoal(0);
}
class WristSource implements ControlSource {
public double get() {
double v = -encoder.get() * (2 * Math.PI / 921.6);
return v;
}
public void updateFilter() {
}
public boolean getLowerLimit() {
return !zeroSensor.get();
}
public boolean getUpperLimit() {
return false;
}
}
class WristOutput implements ControlOutput {
public void set(double value) {
intakePivotMotor.set(-value);
}
}
public WristController controller = new WristController("wrist", new WristOutput(), new WristSource(), WristGains.getGains()[0], 1.0 / 100.0);
protected void initDefaultCommand() {
}
public void setIntakePower(double power) {
double output = Util.limit(power, 1.0);
intakeMotor.set(output);
}
public void setRawPivot(double power) {
}
public void setAngle(double angle) {
controller.setGoal(angle);
}
public double getAngle() {
return controller.getGoal();
}
public boolean getZeroSensor() {
return !zeroSensor.get();
}
public double getEncoder() {
return -encoder.get() * (2 * Math.PI / 921.6);
}
public void rezero() {
controller.reset();
}
public boolean ready() {
return controller.getState() == WristController.READY;
}
}
| bsd-2-clause |
jayfans3/example | liupeng/src/main/java/liupeng/Ch12_MapReduceBLAST/edu/nju/cs/mapreduceblast/automaton/Hit.java | 490 | /**
* @author Liu Yu-long
* @date June, 2011
*/
package edu.nju.cs.mapreduceblast.automaton;
/**
* @author Administrator
*
*/
public class Hit {
private int indexInDB_Sequence;
private int[] indexInQuery;
public Hit(int indexInDB_Sequence,int[] indexInQuery){
this.indexInDB_Sequence=indexInDB_Sequence;
this.indexInQuery=indexInQuery;
}
public int getIndexInDB_Sequence(){
return indexInDB_Sequence;
}
public int[] getIndexInQuery(){
return indexInQuery;
}
}
| bsd-2-clause |
yaoqi/chat | src/main/java/com/mercury/chat/user/entity/QuickReplyTemplate.java | 9280 | package com.mercury.chat.user.entity;
import java.util.ArrayList;
import java.util.List;
public class QuickReplyTemplate {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public QuickReplyTemplate() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andUuidIsNull() {
addCriterion("UUID is null");
return (Criteria) this;
}
public Criteria andUuidIsNotNull() {
addCriterion("UUID is not null");
return (Criteria) this;
}
public Criteria andUuidEqualTo(Long value) {
addCriterion("UUID =", value, "uuid");
return (Criteria) this;
}
public Criteria andUuidNotEqualTo(Long value) {
addCriterion("UUID <>", value, "uuid");
return (Criteria) this;
}
public Criteria andUuidGreaterThan(Long value) {
addCriterion("UUID >", value, "uuid");
return (Criteria) this;
}
public Criteria andUuidGreaterThanOrEqualTo(Long value) {
addCriterion("UUID >=", value, "uuid");
return (Criteria) this;
}
public Criteria andUuidLessThan(Long value) {
addCriterion("UUID <", value, "uuid");
return (Criteria) this;
}
public Criteria andUuidLessThanOrEqualTo(Long value) {
addCriterion("UUID <=", value, "uuid");
return (Criteria) this;
}
public Criteria andUuidIn(List<Long> values) {
addCriterion("UUID in", values, "uuid");
return (Criteria) this;
}
public Criteria andUuidNotIn(List<Long> values) {
addCriterion("UUID not in", values, "uuid");
return (Criteria) this;
}
public Criteria andUuidBetween(Long value1, Long value2) {
addCriterion("UUID between", value1, value2, "uuid");
return (Criteria) this;
}
public Criteria andUuidNotBetween(Long value1, Long value2) {
addCriterion("UUID not between", value1, value2, "uuid");
return (Criteria) this;
}
public Criteria andSaleidIsNull() {
addCriterion("SALEID is null");
return (Criteria) this;
}
public Criteria andSaleidIsNotNull() {
addCriterion("SALEID is not null");
return (Criteria) this;
}
public Criteria andSaleidEqualTo(Long value) {
addCriterion("SALEID =", value, "saleid");
return (Criteria) this;
}
public Criteria andSaleidNotEqualTo(Long value) {
addCriterion("SALEID <>", value, "saleid");
return (Criteria) this;
}
public Criteria andSaleidGreaterThan(Long value) {
addCriterion("SALEID >", value, "saleid");
return (Criteria) this;
}
public Criteria andSaleidGreaterThanOrEqualTo(Long value) {
addCriterion("SALEID >=", value, "saleid");
return (Criteria) this;
}
public Criteria andSaleidLessThan(Long value) {
addCriterion("SALEID <", value, "saleid");
return (Criteria) this;
}
public Criteria andSaleidLessThanOrEqualTo(Long value) {
addCriterion("SALEID <=", value, "saleid");
return (Criteria) this;
}
public Criteria andSaleidIn(List<Long> values) {
addCriterion("SALEID in", values, "saleid");
return (Criteria) this;
}
public Criteria andSaleidNotIn(List<Long> values) {
addCriterion("SALEID not in", values, "saleid");
return (Criteria) this;
}
public Criteria andSaleidBetween(Long value1, Long value2) {
addCriterion("SALEID between", value1, value2, "saleid");
return (Criteria) this;
}
public Criteria andSaleidNotBetween(Long value1, Long value2) {
addCriterion("SALEID not between", value1, value2, "saleid");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | bsd-2-clause |
TomorrowOnceMore/SummerMVC | summer-manager/summer-manager-pojo/src/main/java/com/summer/pojo/TbOrderItem.java | 6695 | package com.summer.pojo;
public class TbOrderItem {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tb_order_item.id
*
* @mbggenerated
*/
private String id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tb_order_item.item_id
*
* @mbggenerated
*/
private String itemId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tb_order_item.order_id
*
* @mbggenerated
*/
private String orderId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tb_order_item.num
*
* @mbggenerated
*/
private Integer num;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tb_order_item.title
*
* @mbggenerated
*/
private String title;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tb_order_item.price
*
* @mbggenerated
*/
private Long price;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tb_order_item.total_fee
*
* @mbggenerated
*/
private Long totalFee;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tb_order_item.pic_path
*
* @mbggenerated
*/
private String picPath;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tb_order_item.id
*
* @return the value of tb_order_item.id
*
* @mbggenerated
*/
public String getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tb_order_item.id
*
* @param id the value for tb_order_item.id
*
* @mbggenerated
*/
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tb_order_item.item_id
*
* @return the value of tb_order_item.item_id
*
* @mbggenerated
*/
public String getItemId() {
return itemId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tb_order_item.item_id
*
* @param itemId the value for tb_order_item.item_id
*
* @mbggenerated
*/
public void setItemId(String itemId) {
this.itemId = itemId == null ? null : itemId.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tb_order_item.order_id
*
* @return the value of tb_order_item.order_id
*
* @mbggenerated
*/
public String getOrderId() {
return orderId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tb_order_item.order_id
*
* @param orderId the value for tb_order_item.order_id
*
* @mbggenerated
*/
public void setOrderId(String orderId) {
this.orderId = orderId == null ? null : orderId.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tb_order_item.num
*
* @return the value of tb_order_item.num
*
* @mbggenerated
*/
public Integer getNum() {
return num;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tb_order_item.num
*
* @param num the value for tb_order_item.num
*
* @mbggenerated
*/
public void setNum(Integer num) {
this.num = num;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tb_order_item.title
*
* @return the value of tb_order_item.title
*
* @mbggenerated
*/
public String getTitle() {
return title;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tb_order_item.title
*
* @param title the value for tb_order_item.title
*
* @mbggenerated
*/
public void setTitle(String title) {
this.title = title == null ? null : title.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tb_order_item.price
*
* @return the value of tb_order_item.price
*
* @mbggenerated
*/
public Long getPrice() {
return price;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tb_order_item.price
*
* @param price the value for tb_order_item.price
*
* @mbggenerated
*/
public void setPrice(Long price) {
this.price = price;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tb_order_item.total_fee
*
* @return the value of tb_order_item.total_fee
*
* @mbggenerated
*/
public Long getTotalFee() {
return totalFee;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tb_order_item.total_fee
*
* @param totalFee the value for tb_order_item.total_fee
*
* @mbggenerated
*/
public void setTotalFee(Long totalFee) {
this.totalFee = totalFee;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tb_order_item.pic_path
*
* @return the value of tb_order_item.pic_path
*
* @mbggenerated
*/
public String getPicPath() {
return picPath;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tb_order_item.pic_path
*
* @param picPath the value for tb_order_item.pic_path
*
* @mbggenerated
*/
public void setPicPath(String picPath) {
this.picPath = picPath == null ? null : picPath.trim();
}
} | bsd-2-clause |
robertocapuano/jink | jink/src/main/java/debug/test/JDITest.java | 3091 | /*
* Copyright (c) 2014, Roberto Capuano <roberto@2think.it>
* 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 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 debug.test;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
import com.sun.jdi.request.*;
import tools.*;
import debug.event.*;
import java.util.*;
public class JDITest implements JDIListener, DebugOff
{
public JDITest()
{
}
// JDIListener
public boolean accessWatchpoint(AccessWatchpointEventSet e)
{
return false;
}
public boolean classPrepare(ClassPrepareEventSet e)
{
return false;
}
public boolean classUnload(ClassUnloadEventSet e)
{
return false;
}
public boolean exception(ExceptionEventSet e)
{
return false;
}
/**
** Applicare attenzione al caso di thread avviati senza oggetto this.
** Di interesse sono MethodEntryEvent, MethodExitEvent, StepEvent
*/
public boolean locationTrigger( final LocationTriggerEventSet e)
{ return false;
}
public boolean modificationWatchpoint(ModificationWatchpointEventSet e)
{
return false;
}
public boolean threadStart( ThreadStartEventSet e)
{ return false;
}
public boolean threadDeath(ThreadDeathEventSet e)
{
/* try
{
ThreadReference threadReference = e.getThread();
log.log( DEBUG, "" + threadReference );
// Inspector.inspect( e );
if ( threadReference.name().equals("DestroyJavaVM") )
return;
model.kill( threadReference );
}
catch (VMDisconnectedException vmde)
{
log.log( DEBUG, ""+vmde );
}
*/
return false;
}
public boolean vmDeath(VMDeathEventSet e)
{
return false;
}
public boolean vmDisconnect(VMDisconnectEventSet e)
{
// log.log( DEBUG, "" );
// com.mdcs.joi.Inspector.inspect( e );
return false;
}
public boolean vmStart(VMStartEventSet e)
{
return false;
}
} | bsd-2-clause |
mrduongnv/jcodec | src/main/java/net/sourceforge/jaad/aac/error/BitsBuffer.java | 1955 | package net.sourceforge.jaad.aac.error;
import net.sourceforge.jaad.aac.AACException;
import net.sourceforge.jaad.aac.syntax.IBitStream;
public class BitsBuffer {
int bufa, bufb, len;
public BitsBuffer() {
len = 0;
}
public int getLength() {
return len;
}
public int showBits(int bits) {
if(bits==0) return 0;
if(len<=32) {
//huffman_spectral_data_2 needs to read more than may be available,
//bits maybe > len, deliver 0 than
if(len>=bits) return ((bufa>>(len-bits))&(0xFFFFFFFF>>(32-bits)));
else return ((bufa<<(bits-len))&(0xFFFFFFFF>>(32-bits)));
}
else {
if((len-bits)<32) return ((bufb&(0xFFFFFFFF>>(64-len)))<<(bits-len+32))|(bufa>>(len-bits));
else return ((bufb>>(len-bits-32))&(0xFFFFFFFF>>(32-bits)));
}
}
public boolean flushBits(int bits) {
len -= bits;
boolean b;
if(len<0) {
len = 0;
b = false;
}
else b = true;
return b;
}
public int getBits(int n) {
int i = showBits(n);
if(!flushBits(n)) i = -1;
return i;
}
public int getBit() {
int i = showBits(1);
if(!flushBits(1)) i = -1;
return i;
}
public void rewindReverse() {
if(len==0) return;
final int[] i = HCR.rewindReverse64(bufb, bufa, len);
bufb = i[0];
bufa = i[1];
}
//merge bits of a to b
public void concatBits(BitsBuffer a) {
if(a.len==0) return;
int al = a.bufa;
int ah = a.bufb;
int bl, bh;
if(len>32) {
//mask off superfluous high b bits
bl = bufa;
bh = bufb&((1<<(len-32))-1);
//left shift a len bits
ah = al<<(len-32);
al = 0;
}
else {
bl = bufa&((1<<(len))-1);
bh = 0;
ah = (ah<<(len))|(al>>(32-len));
al = al<<len;
}
//merge
bufa = bl|al;
bufb = bh|ah;
len += a.len;
}
public void readSegment(int segwidth, IBitStream in) throws AACException {
len = segwidth;
if(segwidth>32) {
bufb = in.readBits(segwidth-32);
bufa = in.readBits(32);
}
else {
bufa = in.readBits(segwidth);
bufb = 0;
}
}
}
| bsd-2-clause |
NCIP/cagrid2 | cagrid-trust/cagrid-trust-service/src/main/java/org/cagrid/trust/service/core/Driver.java | 557 | package org.cagrid.trust.service.core;
import java.io.File;
import org.cagrid.core.xml.XMLUtils;
import org.cagrid.trust.model.SyncDescription;
public class Driver {
public static void main(String[] args) {
try {
SpringUtils utils = new SpringUtils();
Synchronizer gts = utils.getSynchronizer();
SyncDescription des = (SyncDescription) XMLUtils.fromXMLFile(SyncDescription.class, new File("/Users/langella/ext/smx-trust/etc/cagrid-trust/sync-description.xml"));
gts.sync(des);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| bsd-3-clause |
Caleydo/caleydo | org.caleydo.view.selectionbrowser/src/org/caleydo/view/selectionbrowser/RcpSelectionBrowserView.java | 2492 | /*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
******************************************************************************/
package org.caleydo.view.selectionbrowser;
import org.caleydo.core.data.datadomain.DataDomainManager;
import org.caleydo.core.data.datadomain.IDataDomain;
import org.caleydo.core.serialize.ASerializedSingleTablePerspectiveBasedView;
import org.caleydo.core.view.CaleydoRCPViewPart;
import org.caleydo.core.view.IDataDomainBasedView;
import org.caleydo.core.view.swt.ASWTView;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
/**
* View showing selections.
*
* @author Marc Streit
*/
public class RcpSelectionBrowserView extends CaleydoRCPViewPart {
public static String VIEW_TYPE = "org.caleydo.view.selectionbrowser";
public RcpSelectionBrowserView() {
super(SerializedSelectionBrowserView.class);
}
@Override
public void createPartControl(Composite parent) {
final Composite parentComposite = new Composite(parent, SWT.NULL);
parentComposite.setLayout(new GridLayout(1, false));
this.parentComposite = parentComposite;
Composite infoComposite = new Composite(this.parentComposite, SWT.NULL);
infoComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridLayout layout;
layout = new GridLayout(1, false);
layout.marginBottom = layout.marginTop = layout.marginLeft = layout.marginRight = layout.horizontalSpacing = layout.verticalSpacing = 0;
layout.marginHeight = layout.marginWidth = 0;
infoComposite.setLayout(layout);
view = new SelectionBrowserView(infoComposite);
if (view instanceof IDataDomainBasedView<?>) {
((IDataDomainBasedView<IDataDomain>) view).setDataDomain(DataDomainManager
.get().getDataDomainByID(
((ASerializedSingleTablePerspectiveBasedView) serializedView)
.getDataDomainID()));
}
((ASWTView) view).draw();
}
@Override
public void setFocus() {
}
@Override
public void dispose() {
super.dispose();
// selectionBrowser.dispose();
}
@Override
public void createDefaultSerializedView() {
serializedView = new SerializedSelectionBrowserView();
determineDataConfiguration(serializedView);
}
}
| bsd-3-clause |
Caleydo/org.caleydo.view.contour | src/main/java/org/caleydo/view/relationshipexplorer/ui/dialog/columnconfig/widget/IdentifierConfigWidget.java | 5336 | /*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
*******************************************************************************/
package org.caleydo.view.relationshipexplorer.ui.dialog.columnconfig.widget;
import org.caleydo.core.id.IDCategory;
import org.caleydo.core.id.IDType;
import org.caleydo.core.util.base.ICallback;
import org.caleydo.view.relationshipexplorer.ui.ConTourElement;
import org.caleydo.view.relationshipexplorer.ui.collection.AEntityCollection;
import org.caleydo.view.relationshipexplorer.ui.collection.IDCollection;
import org.caleydo.view.relationshipexplorer.ui.column.factory.ColumnFactories.IDColumnFactory;
import org.caleydo.view.relationshipexplorer.ui.column.item.factory.impl.MappingSummaryConfigurationAddon.MappingSummaryItemFactoryCreator;
import org.caleydo.view.relationshipexplorer.ui.column.item.factory.impl.TextConfigurationAddon.TextItemFactoryCreator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
/**
* @author Christian
*
*/
public class IdentifierConfigWidget extends ADataConfigWidget {
private Combo idCategoryCombo;
private Combo idTypeCombo;
// private Combo displayedIDTypeCombo;
/**
* @param parent
* @param style
*/
public IdentifierConfigWidget(Composite parent, final ICallback<ADataConfigWidget> callback) {
super(parent, callback);
setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
setLayout(new GridLayout(2, false));
Label idCategoryLabel = new Label(this, SWT.NONE);
idCategoryLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
idCategoryLabel.setText("Type");
idCategoryCombo = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
idCategoryCombo.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
idCategoryCombo.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
idTypeCombo.setEnabled(true);
idTypeCombo.clearSelection();
idTypeCombo.removeAll();
// displayedIDTypeCombo.setEnabled(true);
// displayedIDTypeCombo.clearSelection();
// displayedIDTypeCombo.removeAll();
for (IDType idType : IDCategory.getIDCategory(idCategoryCombo.getText()).getIdTypes()) {
if (!idType.isInternalType()) {
idTypeCombo.add(idType.getTypeName());
// displayedIDTypeCombo.add(idType.getTypeName());
}
}
callback.on(IdentifierConfigWidget.this);
}
});
for (IDCategory idCategory : IDCategory.getAllRegisteredIDCategories()) {
if (!idCategory.isInternaltCategory()) {
idCategoryCombo.add(idCategory.getCategoryName());
}
}
Label idTypeLabel = new Label(this, SWT.NONE);
idTypeLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
idTypeLabel.setText("Identifier");
idTypeCombo = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
idTypeCombo.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
idTypeCombo.setEnabled(false);
idTypeCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// if (displayedIDTypeCombo.getSelectionIndex() == -1) {
// displayedIDTypeCombo.select(idTypeCombo.getSelectionIndex());
// }
callback.on(IdentifierConfigWidget.this);
}
});
// idTypeLabel = new Label(this, SWT.NONE);
// idTypeLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
// idTypeLabel.setText("Displayed Identifier");
// displayedIDTypeCombo = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
// displayedIDTypeCombo.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
// displayedIDTypeCombo.setEnabled(false);
// displayedIDTypeCombo.addSelectionListener(new SelectionAdapter() {
// @Override
// public void widgetSelected(SelectionEvent e) {
// callback.on(IdentifierConfigWidget.this);
// }
// });
}
public IDType getSelectedIDType() {
if (idTypeCombo.getSelectionIndex() == -1)
return null;
return IDType.getIDType(idTypeCombo.getText());
}
// public IDType getSelectedDisplayIDType() {
// if (displayedIDTypeCombo.getSelectionIndex() == -1)
// return null;
// return IDType.getIDType(displayedIDTypeCombo.getText());
// }
@Override
public boolean isConfigValid() {
return getSelectedIDType() != null; // && getSelectedDisplayIDType() != null;
}
@Override
public AEntityCollection getCollection(ConTourElement contour) {
IDCollection collection = new IDCollection(getSelectedIDType(), getSelectedIDType(), null, contour);
IDColumnFactory factory = new IDColumnFactory();
factory.addItemFactoryCreator(new TextItemFactoryCreator(), true);
factory.addSummaryItemFactoryCreator(new MappingSummaryItemFactoryCreator(), true);
collection.setColumnFactory(factory);
return collection;
}
}
| bsd-3-clause |
ktisha/snuggletex | snuggletex-core/src/main/java/uk/ac/ed/ph/snuggletex/internal/util/ArrayListStack.java | 1516 | /* $Id: ArrayListStack.java 742 2012-05-07 13:09:53Z davemckain $
*
* Copyright (c) 2008-2011, The University of Edinburgh.
* All Rights Reserved
*/
package uk.ac.ed.ph.snuggletex.internal.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EmptyStackException;
/**
* Trivial extension of {@link ArrayList} that mixes in the stack-like bits from
* {@link java.util.Stack} whilst still being non-synchronized.
*
* (This is copied from <tt>ph-commons-util</tt>.)
*
* @author David McKain
* @version $Revision: 742 $
*/
public class ArrayListStack<E> extends ArrayList<E> {
private static final long serialVersionUID = -4103564522108783429L;
public ArrayListStack() {
super();
}
public ArrayListStack(Collection<? extends E> c) {
super(c);
}
public ArrayListStack(int initialCapacity) {
super(initialCapacity);
}
//---------------------------------------------------
public E push(E element) {
super.add(element);
return element;
}
public E peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return get(size()-1);
}
public E pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
E result = remove(size()-1);
return result;
}
public int search(Object object) {
int index = indexOf(object);
return index==-1 ? -1 : index+1;
}
}
| bsd-3-clause |
scaladyno/ductilej | src/test/java/org/ductilej/tests/ShadowedFinalArgTest.java | 663 | //
// $Id$
package org.ductilej.tests;
import javax.swing.JLabel;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests handling of shadowed final arguments.
*/
public class ShadowedFinalArgTest
{
public static class MyLabel extends JLabel {
@Override public void setText (final String text) {
super.setText(text);
new Runnable() {
public void run () {
String val = text;
}
}.run();
}
}
@Test public void testShadowedFinal ()
{
// we have nothing to test here, if the above code compiles, then we're fine
}
}
| bsd-3-clause |
nicrioux/JavaPhoenixChannels | src/main/java/org/phoenixframework/channels/Socket.java | 12352 | package org.phoenixframework.channels;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.BaseJsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ws.WebSocket;
import com.squareup.okhttp.ws.WebSocketCall;
import com.squareup.okhttp.ws.WebSocketListener;
import okio.Buffer;
import okio.BufferedSource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Socket {
private static final Logger LOG = Logger.getLogger(Socket.class.getName());
public static final int RECONNECT_INTERVAL_MS = 5000;
private final ObjectMapper objectMapper = new ObjectMapper();
private final OkHttpClient httpClient = new OkHttpClient();
private WebSocket webSocket = null;
private String endpointUri = null;
private final List<Channel> channels = new ArrayList<>();
private Timer timer = null;
private TimerTask reconnectTimerTask = null;
private Set<ISocketOpenCallback> socketOpenCallbacks = Collections.newSetFromMap(new WeakHashMap<ISocketOpenCallback, Boolean>());
private Set<ISocketCloseCallback> socketCloseCallbacks = Collections.newSetFromMap(new WeakHashMap<ISocketCloseCallback, Boolean>());
private Set<IErrorCallback> errorCallbacks = Collections.newSetFromMap(new WeakHashMap<IErrorCallback, Boolean>());
private Set<IMessageCallback> messageCallbacks = Collections.newSetFromMap(new WeakHashMap<IMessageCallback, Boolean>());
private int refNo = 1;
/**
* Annotated WS Endpoint. Private member to prevent confusion with "onConn*" registration methods.
*/
private PhoenixWSListener wsListener = new PhoenixWSListener();
private ConcurrentLinkedDeque<Buffer> sendBuffer = new ConcurrentLinkedDeque<>();
public class PhoenixWSListener implements WebSocketListener {
private PhoenixWSListener() {
}
@Override
public void onOpen(final WebSocket webSocket, final Request request, final Response response) throws IOException {
LOG.log(Level.FINE, "WebSocket onOpen: {0}", webSocket);
Socket.this.webSocket = webSocket;
cancelReconnectTimer();
// TODO - Heartbeat
for (final ISocketOpenCallback callback : socketOpenCallbacks) {
callback.onOpen();
}
Socket.this.flushSendBuffer();
}
@Override
public void onMessage(final BufferedSource payload, final WebSocket.PayloadType type) throws IOException {
LOG.log(Level.FINE, "Envelope received: {0}", payload);
try {
if (type == WebSocket.PayloadType.TEXT) {
final Envelope envelope =
objectMapper.readValue(payload.inputStream(), Envelope.class);
for (final Channel channel : channels) {
if (channel.isMember(envelope.getTopic())) {
channel.trigger(envelope.getEvent(), envelope);
}
}
for (final IMessageCallback callback : messageCallbacks) {
callback.onMessage(envelope);
}
}
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to read message payload", e);
} finally {
payload.close();
}
}
@Override
public void onPong(final Buffer payload) {
LOG.log(Level.INFO, "PONG received: {0}", payload);
}
@Override
public void onClose(final int code, final String reason) {
LOG.log(Level.FINE, "WebSocket onClose {0}/{1}", new Object[]{code, reason});
Socket.this.webSocket = null;
scheduleReconnectTimer();
for (final ISocketCloseCallback callback : socketCloseCallbacks) {
callback.onClose();
}
}
@Override
public void onFailure(final IOException e) {
LOG.log(Level.WARNING, "WebSocket connection error", e);
try {
for (final IErrorCallback callback : errorCallbacks) {
triggerChannelError();
callback.onError(e.toString());
}
}
finally {
// Assume closed on failure
if(Socket.this.webSocket != null) {
try {
Socket.this.webSocket.close(1001 /*CLOSE_GOING_AWAY*/, "EOF received");
} catch (IOException ioe) {
LOG.log(Level.WARNING, "Failed to explicitly close following failure");
} finally {
Socket.this.webSocket = null;
}
}
scheduleReconnectTimer();
}
}
}
/**
* Sets up and schedules a timer task to make repeated reconnect attempts at configured intervals
*/
private void scheduleReconnectTimer() {
cancelReconnectTimer();
// TODO - Clear heartbeat timer
Socket.this.reconnectTimerTask = new TimerTask() {
@Override
public void run() {
LOG.log(Level.FINE, "reconnectTimerTask run");
try {
Socket.this.connect();
} catch (Exception e) {
LOG.log(Level.SEVERE, "Failed to reconnect to " + Socket.this.wsListener, e);
}
}
};
timer.schedule(Socket.this.reconnectTimerTask, RECONNECT_INTERVAL_MS );
}
private void cancelReconnectTimer() {
if (Socket.this.reconnectTimerTask != null) {
Socket.this.reconnectTimerTask.cancel();
}
}
public Socket(final String endpointUri) throws IOException {
LOG.log(Level.FINE, "PhoenixSocket({0})", endpointUri);
this.endpointUri = endpointUri;
this.timer = new Timer("Reconnect Timer for " + endpointUri);
}
public void disconnect() throws IOException {
LOG.log(Level.FINE, "disconnect");
if (webSocket != null) {
webSocket.close(1001 /*CLOSE_GOING_AWAY*/, "Disconnected by client");
}
}
public void connect() throws IOException {
LOG.log(Level.FINE, "connect");
disconnect();
// No support for ws:// or ws:// in okhttp. See https://github.com/square/okhttp/issues/1652
final String httpUrl = this.endpointUri.replaceFirst("^ws:", "http:").replaceFirst("^wss:", "https:");
final Request request = new Request.Builder().url(httpUrl).build();
final WebSocketCall wsCall = WebSocketCall.create(httpClient, request);
wsCall.enqueue(wsListener);
}
/**
* @return true if the socket connection is connected
*/
public boolean isConnected() {
return webSocket != null;
}
/**
* Retrieve a channel instance for the specified topic
*
* @param topic The channel topic
* @param payload The message payload
* @return A Channel instance to be used for sending and receiving events for the topic
*/
public Channel chan(final String topic, final JsonNode payload) {
LOG.log(Level.FINE, "chan: {0}, {1}", new Object[]{topic, payload});
final Channel channel = new Channel(topic, payload, Socket.this);
synchronized (channels) {
channels.add(channel);
}
return channel;
}
/**
* Removes the specified channel if it is known to the socket
*
* @param channel The channel to be removed
*/
public void remove(final Channel channel) {
synchronized (channels) {
for (final Iterator chanIter = channels.iterator(); chanIter.hasNext(); ) {
if (chanIter.next() == channel) {
chanIter.remove();
break;
}
}
}
}
/**
* Sends a message envelope on this socket
*
* @param envelope The message envelope
* @return This socket instance
* @throws IOException Thrown if the message cannot be sent
*/
public Socket push(final Envelope envelope) throws IOException {
LOG.log(Level.FINE, "Pushing envelope: {0}", envelope);
final ObjectNode node = objectMapper.createObjectNode();
node.put("topic", envelope.getTopic());
node.put("event", envelope.getEvent());
node.put("ref", envelope.getRef());
node.set("payload", envelope.getPayload() == null ? objectMapper.createObjectNode() : envelope.getPayload());
final String json = objectMapper.writeValueAsString(node);
LOG.log(Level.FINE, "Sending JSON: {0}", json);
final Buffer payload = new Buffer();
payload.writeUtf8(json);
if (this.isConnected()) {
try {
webSocket.sendMessage(WebSocket.PayloadType.TEXT, payload);
}
catch(IllegalStateException e) {
LOG.log(Level.SEVERE, "Attempted to send push when socket is not open", e);
}
} else {
this.sendBuffer.add(payload);
}
return this;
}
/**
* Register a callback for SocketEvent.OPEN events
*
* @param callback The callback to receive OPEN events
* @return This Socket instance
*/
public Socket onOpen(final ISocketOpenCallback callback) {
cancelReconnectTimer();
this.socketOpenCallbacks.add(callback);
return this;
}
/**
* Register a callback for SocketEvent.ERROR events
*
* @param callback The callback to receive CLOSE events
* @return This Socket instance
*/
public Socket onClose(final ISocketCloseCallback callback) {
this.socketCloseCallbacks.add(callback);
return this;
}
/**
* Register a callback for SocketEvent.ERROR events
*
* @param callback The callback to receive ERROR events
* @return This Socket instance
*/
public Socket onError(final IErrorCallback callback) {
this.errorCallbacks.add(callback);
return this;
}
/**
* Register a callback for SocketEvent.MESSAGE events
*
* @param callback The callback to receive MESSAGE events
* @return This Socket instance
*/
public Socket onMessage(final IMessageCallback callback) {
this.messageCallbacks.add(callback);
return this;
}
@Override
public String toString() {
return "PhoenixSocket{" +
"endpointUri='" + endpointUri + '\'' +
", channels=" + channels +
", refNo=" + refNo +
", webSocket=" + webSocket +
'}';
}
synchronized String makeRef() {
int val = refNo++;
if (refNo == Integer.MAX_VALUE) {
refNo = 0;
}
return Integer.toString(val);
}
private void triggerChannelError() {
for (final Channel channel : channels) {
channel.trigger(ChannelEvent.ERROR.getPhxEvent(), null);
}
}
private void flushSendBuffer() {
while (this.isConnected() && !this.sendBuffer.isEmpty()) {
final Buffer buffer = this.sendBuffer.removeFirst();
try {
this.webSocket.sendMessage(WebSocket.PayloadType.TEXT, buffer);
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to send payload {0}", buffer);
}
}
}
static String replyEventName(final String ref) {
return "chan_reply_" + ref;
}
} | bsd-3-clause |
NCIP/cagrid2 | cagrid-dorian/cagrid-dorian-service/src/main/java/org/cagrid/dorian/service/util/AddressValidator.java | 1850 | package org.cagrid.dorian.service.util;
import gov.nih.nci.cagrid.common.Utils;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
/**
* @author <A href="mailto:langella@bmi.osu.edu">Stephen Langella </A>
* @author <A href="mailto:oster@bmi.osu.edu">Scott Oster </A>
* @author <A href="mailto:hastings@bmi.osu.edu">Shannon Hastings </A>
* @version $Id: ArgumentManagerTable.java,v 1.2 2004/10/15 16:35:16 langella
* Exp $
*/
public class AddressValidator {
public static void validateEmail(String email) throws IllegalArgumentException {
validateField("Email", email);
try {
InternetAddress emailAddr = new InternetAddress(email);
if (!hasNameAndDomain(email)) {
throw new IllegalArgumentException("Invalid email address specified.");
}
} catch (AddressException ex) {
throw new IllegalArgumentException("Invalid email address specified.");
}
}
private static boolean hasNameAndDomain(String aEmailAddress) {
String[] tokens = aEmailAddress.split("@");
if (tokens.length == 2) {
if ((Utils.clean(tokens[0]) != null) && (Utils.clean(tokens[0]) != null)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public static void validateField(String type, String name) throws IllegalArgumentException {
name = Utils.clean(name);
if (name == null) {
throw new IllegalArgumentException("No " + type + " specified.");
}
if (name.length() > 255) {
throw new IllegalArgumentException("The " + type
+ " specified is too long, it must be less than 255 characters.");
}
}
}
| bsd-3-clause |
leriomaggio/code-coherence-evaluation-tool | code_comments_coherence/media/jhotdraw/7.4.1/jhotdraw7zip/extracted/jhotdraw7/src/main/java/org/jhotdraw/draw/action/IncreaseHandleDetailLevelAction.java | 1513 | /*
* @(#)SelectSameAction.java
*
* Copyright (c) 1996-2010 by the original authors of JHotDraw
* and all its contributors.
* All rights reserved.
*
* The copyright of this software is owned by the authors and
* contributors of the JHotDraw project ("the copyright holders").
* You may not use, copy or modify this software, except in
* accordance with the license agreement you entered into with
* the copyright holders. For details see accompanying license terms.
*/
package org.jhotdraw.draw.action;
import org.jhotdraw.draw.*;
/**
* SelectSameAction.
*
* @author Werner Randelshofer
* @version $Id: IncreaseHandleDetailLevelAction.java 604 2010-01-09 12:00:29Z rawcoder $
*/
public class IncreaseHandleDetailLevelAction extends AbstractSelectedAction {
public final static String ID = "view.increaseHandleDetailLevel";
/** Creates a new instance. */
public IncreaseHandleDetailLevelAction(DrawingEditor editor) {
super(editor);
labels.configureAction(this, ID);
//putValue(AbstractAction.NAME, labels.getString("editSelectSame"));
// putValue(AbstractAction.MNEMONIC_KEY, labels.getString("editSelectSameMnem"));
}
public void actionPerformed(java.awt.event.ActionEvent e) {
increaseHandleDetaiLevel();
}
public void increaseHandleDetaiLevel() {
DrawingView view = getView();
if (view != null) {
view.setHandleDetailLevel(view.getHandleDetailLevel() + 1);
}
}
}
| bsd-3-clause |
paksv/vijava | src/com/vmware/vim25/VirtualSerialPortDeviceBackingOption.java | 1860 | /*================================================================================
Copyright (c) 2013 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. 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 com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class VirtualSerialPortDeviceBackingOption extends VirtualDeviceDeviceBackingOption {
} | bsd-3-clause |
asamgir/openspecimen | WEB-INF/src/com/krishagni/catissueplus/core/administrative/events/DistributionProtocolDetail.java | 3136 |
package com.krishagni.catissueplus.core.administrative.events;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.krishagni.catissueplus.core.administrative.domain.DistributionProtocol;
import com.krishagni.catissueplus.core.administrative.domain.User;
import com.krishagni.catissueplus.core.common.events.UserSummary;
public class DistributionProtocolDetail {
private Long id;
private String instituteName;
private UserSummary principalInvestigator;
private String title;
private String shortTitle;
private String irbId;
private Date startDate;
private Date endDate;
private String activityStatus;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getInstituteName() {
return instituteName;
}
public void setInstituteName(String instituteName) {
this.instituteName = instituteName;
}
public UserSummary getPrincipalInvestigator() {
return principalInvestigator;
}
public void setPrincipalInvestigator(UserSummary principalInvestigator) {
this.principalInvestigator = principalInvestigator;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getShortTitle() {
return shortTitle;
}
public void setShortTitle(String shortTitle) {
this.shortTitle = shortTitle;
}
public String getIrbId() {
return irbId;
}
public void setIrbId(String irbId) {
this.irbId = irbId;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getActivityStatus() {
return activityStatus;
}
public void setActivityStatus(String activityStatus) {
this.activityStatus = activityStatus;
}
public static DistributionProtocolDetail from(DistributionProtocol distributionProtocol) {
DistributionProtocolDetail details = new DistributionProtocolDetail();
details.setShortTitle(distributionProtocol.getShortTitle());
details.setId(distributionProtocol.getId());
details.setTitle(distributionProtocol.getTitle());
details.setIrbId(distributionProtocol.getIrbId());
details.setStartDate(distributionProtocol.getStartDate());
details.setEndDate(distributionProtocol.getEndDate());
details.setInstituteName(distributionProtocol.getInstitute().getName());
details.setPrincipalInvestigator(getPrincipleInvestigatorInfo(distributionProtocol.getPrincipalInvestigator()));
details.setActivityStatus(distributionProtocol.getActivityStatus());
return details;
}
private static UserSummary getPrincipleInvestigatorInfo(User principleInvestigator) {
return UserSummary.from(principleInvestigator);
}
public static List<DistributionProtocolDetail> from(List<DistributionProtocol> distributionProtocols) {
List<DistributionProtocolDetail> list = new ArrayList<DistributionProtocolDetail>();
for (DistributionProtocol dp : distributionProtocols) {
list.add(from(dp));
}
return list;
}
}
| bsd-3-clause |
nichoding/daisy-network | daisy-network-proto/src/com/the9/daisy/network/proto/PdlProcessorImpl.java | 1595 | package com.the9.daisy.network.proto;
import org.jboss.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.protobuf.InvalidProtocolBufferException;
import com.the9.daisy.network.msg.Msg;
import com.the9.daisy.network.msg.MsgProcessorAdapter;
import com.the9.daisy.pdl.ISessionManager;
import com.the9.daisy.network.proto.Pdl.LoginGame_C2S_Msg;
import com.the9.daisy.network.proto.Pdl.LoginOut_C2S_Msg;
import com.the9.daisy.network.proto.Pdl.KeepAlive_C2S_Msg;
public class PdlProcessorImpl extends MsgProcessorAdapter implements PdlMsgType {
private static final Logger logger = LoggerFactory
.getLogger(PdlProcessorImpl.class);
private final IPdlHandler pdlHandler;
private final ISessionManager sessionManager;
public PdlProcessorImpl(IPdlHandler pdlHandler,
ISessionManager sessionService) {
super();
this.pdlHandler = pdlHandler;
this.sessionManager = sessionService;
}
@Override
public void process(Channel channel, Msg msg)
throws InvalidProtocolBufferException {
switch (msg.getType()) {
case PDL_LoginGame_C2S_Msg:
pdlHandler.loginGame(LoginGame_C2S_Msg.parseFrom(msg.getContent()),sessionManager.getSession(channel));
break;
case PDL_LoginOut_C2S_Msg:
pdlHandler.loginOut(LoginOut_C2S_Msg.parseFrom(msg.getContent()),sessionManager.getSession(channel));
break;
case PDL_KeepAlive_C2S_Msg:
pdlHandler.keepAlive(KeepAlive_C2S_Msg.parseFrom(msg.getContent()),sessionManager.getSession(channel));
break;
default:
logger.error("unkown msg type:{}", msg.getType());
break;
}
}
}
| bsd-3-clause |
PhilAndrew/choco3gwt | choco-solver/src/main/java/org/chocosolver/solver/search/strategy/decision/fast/FastDecisionSet.java | 3276 | /**
* Copyright (c) 2014,
* Charles Prud'homme (TASC, INRIA Rennes, LINA CNRS UMR 6241),
* Jean-Guillaume Fages (COSLING S.A.S.).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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.chocosolver.solver.search.strategy.decision.fast;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.search.strategy.assignments.DecisionOperator;
import org.chocosolver.solver.search.strategy.decision.Decision;
import org.chocosolver.solver.variables.SetVar;
import org.chocosolver.util.PoolManager;
/**
* @author Jean-Guillaume Fages
* @since Jan. 2013
*/
public class FastDecisionSet extends Decision<SetVar> {
int value;
DecisionOperator<SetVar> operator;
final PoolManager<FastDecisionSet> poolManager;
public FastDecisionSet(PoolManager<FastDecisionSet> poolManager) {
this.poolManager = poolManager;
}
@Override
public Integer getDecisionValue() {
return value;
}
@Override
public void apply() throws ContradictionException {
if (branch == 1) {
operator.apply(var, value, this);
} else if (branch == 2) {
operator.unapply(var, value, this);
}
}
public void set(SetVar v, int value, DecisionOperator<SetVar> operator) {
super.set(v);
this.var = v;
this.value = value;
this.operator = operator;
}
@Override
public void reverse() {
this.operator = operator.opposite();
}
@Override
public void free() {
previous = null;
poolManager.returnE(this);
}
@Override
public String toString() {
return String.format("%s%s %s %s (%d)", (branch < 2 ? "" : "!"), var.getName(), operator.toString(), value, branch);
}
}
| bsd-3-clause |
fresskarma/tinyos-1.x | tools/java/net/tinyos/sf/old/DataSource.java | 1817 | // $Id: DataSource.java,v 1.2 2003/10/07 21:46:03 idgay Exp $
/* tab:4
* "Copyright (c) 2000-2003 The Regents of the University of California.
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose, without fee, and without written agreement is
* hereby granted, provided that the above copyright notice, the following
* two paragraphs and the author appear in all copies of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
* OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
* CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*
* Copyright (c) 2002-2003 Intel Corporation
* All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE
* file. If you do not find these files, copies can be found by writing to
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
* 94704. Attention: Intel License Inquiry.
*/
package net.tinyos.sf.old;
import java.util.*;
public interface DataSource {
public void setSerialForward(SerialForward sf);
public boolean OpenSource ( );
public boolean CloseSource ( );
public byte[] ReadPacket ( );
public boolean WritePacket ( byte[] packet );
}
| bsd-3-clause |
team3042/AerialAssist-master | src/org/team3042/AerialAssist/commands/IntakePistonRetract.java | 1268 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.team3042.AerialAssist.commands;
import edu.wpi.first.wpilibj.Timer;
/**
*
* @author Team 3042
*/
public class IntakePistonRetract extends CommandBase {
private static final double TIME_END = 4.0;
private Timer timer = new Timer();
public IntakePistonRetract() {
requires(intakePiston);
}
/**
* Called just before this Command runs the first time
*/
protected void initialize() {
timer.start();
}
/**
* Called repeatedly when this Command is scheduled to run
*/
protected void execute() {
intakePiston.retract();
}
/**
* Make this return true when this Command no longer needs to run execute()
*/
protected boolean isFinished() {
boolean finished = false;
if (timer.get() >= TIME_END) {
finished = true;
}
return finished;
}
/**
* Called once after isFinished returns true
*/
protected void end() {
}
/**
* Called when another command which requires one or more of the same
* subsystems is scheduled to run
*/
protected void interrupted() {
}
}
| bsd-3-clause |
TheMrMilchmann/lwjgl3 | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/EXTValidationFeatures.java | 8307 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
/**
* This extension provides the {@link VkValidationFeaturesEXT} struct that can be included in the {@code pNext} chain of the {@link VkInstanceCreateInfo} structure passed as the {@code pCreateInfo} parameter of {@link VK10#vkCreateInstance CreateInstance}. The structure contains an array of {@code VkValidationFeatureEnableEXT} enum values that enable specific validation features that are disabled by default. The structure also contains an array of {@code VkValidationFeatureDisableEXT} enum values that disable specific validation layer features that are enabled by default.
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>The {@link EXTValidationFeatures VK_EXT_validation_features} extension subsumes all the functionality provided in the {@link EXTValidationFlags VK_EXT_validation_flags} extension.</p>
* </div>
*
* <h5>VK_EXT_validation_features</h5>
*
* <dl>
* <dt><b>Name String</b></dt>
* <dd>{@code VK_EXT_validation_features}</dd>
* <dt><b>Extension Type</b></dt>
* <dd>Instance extension</dd>
* <dt><b>Registered Extension Number</b></dt>
* <dd>248</dd>
* <dt><b>Revision</b></dt>
* <dd>5</dd>
* <dt><b>Extension and Version Dependencies</b></dt>
* <dd><ul>
* <li>Requires Vulkan 1.0</li>
* </ul></dd>
* <dt><b>Special Use</b></dt>
* <dd><ul>
* <li><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#extendingvulkan-compatibility-specialuse">Debugging tools</a></li>
* </ul></dd>
* <dt><b>Contact</b></dt>
* <dd><ul>
* <li>Karl Schultz <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_validation_features]%20@karl-lunarg%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_validation_features%20extension%3E%3E">karl-lunarg</a></li>
* </ul></dd>
* </dl>
*
* <h5>Other Extension Metadata</h5>
*
* <dl>
* <dt><b>Last Modified Date</b></dt>
* <dd>2018-11-14</dd>
* <dt><b>IP Status</b></dt>
* <dd>No known IP claims.</dd>
* <dt><b>Contributors</b></dt>
* <dd><ul>
* <li>Karl Schultz, LunarG</li>
* <li>Dave Houlton, LunarG</li>
* <li>Mark Lobodzinski, LunarG</li>
* <li>Camden Stocker, LunarG</li>
* <li>Tony Barbour, LunarG</li>
* <li>John Zulauf, LunarG</li>
* </ul></dd>
* </dl>
*/
public final class EXTValidationFeatures {
/** The extension specification version. */
public static final int VK_EXT_VALIDATION_FEATURES_SPEC_VERSION = 5;
/** The extension name. */
public static final String VK_EXT_VALIDATION_FEATURES_EXTENSION_NAME = "VK_EXT_validation_features";
/** Extends {@code VkStructureType}. */
public static final int VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT = 1000247000;
/**
* VkValidationFeatureEnableEXT - Specify validation features to enable
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT} specifies that GPU-assisted validation is enabled. Activating this feature instruments shader programs to generate additional diagnostic data. This feature is disabled by default.</li>
* <li>{@link #VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT} specifies that the validation layers reserve a descriptor set binding slot for their own use. The layer reports a value for {@link VkPhysicalDeviceLimits}{@code ::maxBoundDescriptorSets} that is one less than the value reported by the device. If the device supports the binding of only one descriptor set, the validation layer does not perform GPU-assisted validation. This feature is disabled by default.</li>
* <li>{@link #VK_VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT} specifies that Vulkan best-practices validation is enabled. Activating this feature enables the output of warnings related to common misuse of the API, but which are not explicitly prohibited by the specification. This feature is disabled by default.</li>
* <li>{@link #VK_VALIDATION_FEATURE_ENABLE_DEBUG_PRINTF_EXT VALIDATION_FEATURE_ENABLE_DEBUG_PRINTF_EXT} specifies that the layers will process {@code debugPrintfEXT} operations in shaders and send the resulting output to the debug callback. This feature is disabled by default.</li>
* <li>{@link #VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT} specifies that Vulkan synchronization validation is enabled. This feature reports resource access conflicts due to missing or incorrect synchronization operations between actions (Draw, Copy, Dispatch, Blit) reading or writing the same regions of memory. This feature is disabled by default.</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkValidationFeaturesEXT}</p>
*/
public static final int
VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT = 0,
VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT = 1,
VK_VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT = 2,
VK_VALIDATION_FEATURE_ENABLE_DEBUG_PRINTF_EXT = 3,
VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT = 4;
/**
* VkValidationFeatureDisableEXT - Specify validation features to disable
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_VALIDATION_FEATURE_DISABLE_ALL_EXT VALIDATION_FEATURE_DISABLE_ALL_EXT} specifies that all validation checks are disabled.</li>
* <li>{@link #VK_VALIDATION_FEATURE_DISABLE_SHADERS_EXT VALIDATION_FEATURE_DISABLE_SHADERS_EXT} specifies that shader validation is disabled. This feature is enabled by default.</li>
* <li>{@link #VK_VALIDATION_FEATURE_DISABLE_THREAD_SAFETY_EXT VALIDATION_FEATURE_DISABLE_THREAD_SAFETY_EXT} specifies that thread safety validation is disabled. This feature is enabled by default.</li>
* <li>{@link #VK_VALIDATION_FEATURE_DISABLE_API_PARAMETERS_EXT VALIDATION_FEATURE_DISABLE_API_PARAMETERS_EXT} specifies that stateless parameter validation is disabled. This feature is enabled by default.</li>
* <li>{@link #VK_VALIDATION_FEATURE_DISABLE_OBJECT_LIFETIMES_EXT VALIDATION_FEATURE_DISABLE_OBJECT_LIFETIMES_EXT} specifies that object lifetime validation is disabled. This feature is enabled by default.</li>
* <li>{@link #VK_VALIDATION_FEATURE_DISABLE_CORE_CHECKS_EXT VALIDATION_FEATURE_DISABLE_CORE_CHECKS_EXT} specifies that core validation checks are disabled. This feature is enabled by default. If this feature is disabled, the shader validation and GPU-assisted validation features are also disabled.</li>
* <li>{@link #VK_VALIDATION_FEATURE_DISABLE_UNIQUE_HANDLES_EXT VALIDATION_FEATURE_DISABLE_UNIQUE_HANDLES_EXT} specifies that protection against duplicate non-dispatchable object handles is disabled. This feature is enabled by default.</li>
* <li>{@link #VK_VALIDATION_FEATURE_DISABLE_SHADER_VALIDATION_CACHE_EXT VALIDATION_FEATURE_DISABLE_SHADER_VALIDATION_CACHE_EXT} specifies that there will be no caching of shader validation results and every shader will be validated on every application execution. Shader validation caching is enabled by default.</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkValidationFeaturesEXT}</p>
*/
public static final int
VK_VALIDATION_FEATURE_DISABLE_ALL_EXT = 0,
VK_VALIDATION_FEATURE_DISABLE_SHADERS_EXT = 1,
VK_VALIDATION_FEATURE_DISABLE_THREAD_SAFETY_EXT = 2,
VK_VALIDATION_FEATURE_DISABLE_API_PARAMETERS_EXT = 3,
VK_VALIDATION_FEATURE_DISABLE_OBJECT_LIFETIMES_EXT = 4,
VK_VALIDATION_FEATURE_DISABLE_CORE_CHECKS_EXT = 5,
VK_VALIDATION_FEATURE_DISABLE_UNIQUE_HANDLES_EXT = 6,
VK_VALIDATION_FEATURE_DISABLE_SHADER_VALIDATION_CACHE_EXT = 7;
private EXTValidationFeatures() {}
} | bsd-3-clause |
oracle-adf/PaaS-SaaS_UIAccelerator | OSCProxyClient/src/com/oracle/ptsdemo/oscproxyclient/types/DeleteOpportunity.java | 1599 |
package com.oracle.ptsdemo.oscproxyclient.types;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="opportunity" type="{http://xmlns.oracle.com/apps/sales/opptyMgmt/opportunities/opportunityService/}Opportunity"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"opportunity"
})
@XmlRootElement(name = "deleteOpportunity")
public class DeleteOpportunity {
@XmlElement(required = true)
protected Opportunity opportunity;
/**
* Gets the value of the opportunity property.
*
* @return
* possible object is
* {@link Opportunity }
*
*/
public Opportunity getOpportunity() {
return opportunity;
}
/**
* Sets the value of the opportunity property.
*
* @param value
* allowed object is
* {@link Opportunity }
*
*/
public void setOpportunity(Opportunity value) {
this.opportunity = value;
}
}
| bsd-3-clause |
bdezonia/zorbage | src/test/java/nom/bdezonia/zorbage/algorithm/TestSinc.java | 2980 | /*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (c) 2016-2021 Barry DeZonia All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* Neither the name of the <copyright holder> nor the names of its contributors may
* be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL <COPYRIGHT HOLDER> 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 nom.bdezonia.zorbage.algorithm;
import static org.junit.Assert.assertEquals;
import org.junit.Test; import nom.bdezonia.zorbage.algebra.G;
import nom.bdezonia.zorbage.type.real.float64.Float64Member;
/**
*
* @author Barry DeZonia
*
*/
public class TestSinc {
@Test
public void test() {
Float64Member x = G.DBL.construct("111");
Float64Member result = G.DBL.construct("999");
x.setV(0);
Sinc.compute(G.DBL, x, result);
assertEquals(1, result.v(), 0);
x.setV(Math.PI/4);
Sinc.compute(G.DBL, x, result);
assertEquals(Math.sin(Math.PI/4)/(Math.PI/4), result.v(), 0);
x.setV(Math.PI/2);
Sinc.compute(G.DBL, x, result);
assertEquals(Math.sin(Math.PI/2)/(Math.PI/2), result.v(), 0);
x.setV(3*Math.PI/4);
Sinc.compute(G.DBL, x, result);
assertEquals(Math.sin(3*Math.PI/4)/(3*Math.PI/4), result.v(), 0);
x.setV(Math.PI);
Sinc.compute(G.DBL, x, result);
assertEquals(Math.sin(Math.PI)/(Math.PI), result.v(), 0);
x.setV(5*Math.PI/4);
Sinc.compute(G.DBL, x, result);
assertEquals(Math.sin(5*Math.PI/4)/(5*Math.PI/4), result.v(), 0);
x.setV(3*Math.PI/2);
Sinc.compute(G.DBL, x, result);
assertEquals(Math.sin(3*Math.PI/2)/(3*Math.PI/2), result.v(), 0);
x.setV(7*Math.PI/4);
Sinc.compute(G.DBL, x, result);
assertEquals(Math.sin(7*Math.PI/4)/(7*Math.PI/4), result.v(), 0);
}
}
| bsd-3-clause |
cfmobile/arca-android-samples | CrunchBase/app/src/main/java/com/crunchbase/app/operations/CompanyOperation.java | 1227 | package com.crunchbase.app.operations;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import io.pivotal.arca.dispatcher.ErrorBroadcaster;
import io.pivotal.arca.service.ServiceError;
import io.pivotal.arca.service.SimpleOperation;
public class CompanyOperation extends SimpleOperation {
public CompanyOperation(final Uri uri) {
super(uri);
}
public CompanyOperation(final Parcel in) {
super(in);
}
@Override
public ContentValues[] onExecute(final Context context) throws Exception {
throw new Exception("Override this method to return a json string for a Company.");
}
@Override
public void onFailure(final Context context, final ServiceError error) {
ErrorBroadcaster.broadcast(context, getUri(), error.getCode(), error.getMessage());
}
public static final Parcelable.Creator<CompanyOperation> CREATOR = new Parcelable.Creator<CompanyOperation>() {
@Override
public CompanyOperation createFromParcel(final Parcel in) {
return new CompanyOperation(in);
}
@Override
public CompanyOperation[] newArray(final int size) {
return new CompanyOperation[size];
}
};
}
| bsd-3-clause |
UCDenver-ccp/datasource | datasource-fileparsers/src/main/java/edu/ucdenver/ccp/datasource/identifiers/impl/bio/PDB_sumId.java | 2208 | package edu.ucdenver.ccp.datasource.identifiers.impl.bio;
import edu.ucdenver.ccp.datasource.fileparsers.CcpExtensionOntology;
/*
* #%L
* Colorado Computational Pharmacology's common module
* %%
* Copyright (C) 2012 - 2014 Regents of the University of Colorado
* %%
* 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.
*
* 3. Neither the name of the Regents of the University of Colorado nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT 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.
* #L%
*/
import edu.ucdenver.ccp.datasource.identifiers.DataSource;
import edu.ucdenver.ccp.datasource.identifiers.Identifier;
import edu.ucdenver.ccp.datasource.identifiers.StringDataSourceIdentifier;
@Identifier(ontClass=CcpExtensionOntology.PDB_SUM_IDENTIFIER)
public class PDB_sumId extends StringDataSourceIdentifier {
public PDB_sumId(String id) {
super(id, DataSource.PDB_SUM);
}
}
| bsd-3-clause |
pecko/thindeck | src/test/java/com/thindeck/cockpit/TkIndexTest.java | 2495 | /**
* Copyright (c) 2014-2015, Thindeck.com
* 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. 3) Neither the name of the thindeck.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT 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 com.thindeck.cockpit;
import com.jcabi.matchers.XhtmlMatchers;
import com.thindeck.fakes.FkBase;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.takes.rq.RqFake;
import org.takes.rs.RsPrettyXML;
import org.takes.rs.RsPrint;
/**
* Test case for {@link TkIndex}.
* @author Yegor Bugayenko (yegor@teamed.io)
* @version $Id$
* @since 0.4
*/
public final class TkIndexTest {
/**
* TkIndex can render a page in XML.
* @throws Exception If something goes wrong.
*/
@Test
public void rendersXmlPage() throws Exception {
MatcherAssert.assertThat(
new RsPrint(
new RsPrettyXML(
new TkIndex(new FkBase()).act(new RqFake())
)
).printBody(),
XhtmlMatchers.hasXPaths(
"/page[@date]",
"/page/links/link[@rel='home']"
)
);
}
}
| bsd-3-clause |
pecko/jcabi-heroku-maven-plugin | src/main/java/com/jcabi/heroku/maven/plugin/package-info.java | 2103 | /**
* Copyright (c) 2012-2015, jcabi.com
* 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. 3) Neither the name of the jcabi.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT 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.
*/
/**
* Heroku Maven plugin.
*
* <p>The only dependency you need is (check our latest version available
* at <a href="http://www.jcabi.com">www.jcabi.com</a>):
*
* <pre><depedency>
* <groupId>com.jcabi</groupId>
* <artifactId>jcabi-heroku-maven-plugin</artifactId>
* </dependency></pre>
*
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
* @since 0.4
* @see <a href="http://www.jcabi.com/jcabi-heroku-maven-plugin">project website</a>
*/
package com.jcabi.heroku.maven.plugin;
| bsd-3-clause |
NCIP/catissue-core | software/caTissue/modules/tests/unit/caTissueSuite_Client/src/edu/wustl/catissuecore/api/testcases/OrdersTestCases.java | 5689 | /*L
* Copyright Washington University in St. Louis
* Copyright SemanticBits
* Copyright Persistent Systems
* Copyright Krishagni
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/catissue-core/LICENSE.txt for details.
*/
package edu.wustl.catissuecore.api.testcases;
import edu.wustl.catissuecore.domain.DerivedSpecimenOrderItem;
import edu.wustl.catissuecore.domain.DistributionProtocol;
import edu.wustl.catissuecore.domain.NewSpecimenOrderItem;
import edu.wustl.catissuecore.domain.OrderDetails;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenOrderItem;
import edu.wustl.catissuecore.domain.User;
import gov.nih.nci.system.applicationservice.ApplicationException;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
/**
* @author Ion C. Olaru
* Date: 7/27/11 - 12:03 PM
*/
public class OrdersTestCases extends AbstractCaCoreApiTestCasesWithRegularAuthentication {
public void testNewOrderWithSpecimenOrderItem() throws ApplicationException {
OrderDetails order = new OrderDetails();
Collection items = new HashSet();
SpecimenOrderItem oi = new SpecimenOrderItem();
oi.setDescription("OI Description " + UniqueKeyGeneratorUtil.getUniqueKey());
oi.setRequestedQuantity(2.9);
oi.setOrderDetails(order);
oi.setStatus("New");
items.add(oi);
order.setComment("Order Comments " + UniqueKeyGeneratorUtil.getUniqueKey());
order.setName("Order name " + UniqueKeyGeneratorUtil.getUniqueKey());
order.setOrderItemCollection(items);
order.setStatus("New");
DistributionProtocol dp = getDistributionProtocolById((long)2);
order.setDistributionProtocol(dp);
OrderDetails o = insert(order);
assertTrue(o.getId() > 0);
log.debug(">>> INSERTED ORDER: " + o.getId());
System.out.println(">>> INSERTED ORDER: " + o.getId());
}
public void testNewOrderWithNewSpecimenOrderItem() throws ApplicationException {
OrderDetails order = new OrderDetails();
Collection items = new HashSet();
NewSpecimenOrderItem oi = new NewSpecimenOrderItem();
oi.setDescription("OI Description " + UniqueKeyGeneratorUtil.getUniqueKey());
oi.setRequestedQuantity(2.9);
oi.setOrderDetails(order);
oi.setStatus("New");
oi.setSpecimenClass("DNA");
oi.setSpecimenType("Fluid");
items.add(oi);
order.setComment("Order Comments " + UniqueKeyGeneratorUtil.getUniqueKey());
order.setName("Order name " + UniqueKeyGeneratorUtil.getUniqueKey());
order.setOrderItemCollection(items);
order.setStatus("New");
DistributionProtocol dp = getDistributionProtocolById((long)2);
order.setDistributionProtocol(dp);
OrderDetails o = insert(order);
assertTrue(o.getId() > 0);
log.debug(">>> INSERTED ORDER: " + o.getId());
System.out.println(">>> INSERTED ORDER: " + o.getId());
}
public void testNewOrderWithDerivedSpecimenOrderItem() throws ApplicationException {
OrderDetails order = new OrderDetails();
Collection items = new HashSet();
DerivedSpecimenOrderItem oi = new DerivedSpecimenOrderItem();
Specimen s = new Specimen();
s.setId((long)3720);
oi.setDescription("OI Description " + UniqueKeyGeneratorUtil.getUniqueKey());
oi.setRequestedQuantity(2.9);
oi.setOrderDetails(order);
oi.setStatus("New");
oi.setSpecimenClass("DNA");
oi.setSpecimenType("Fluid");
oi.setParentSpecimen(s);
items.add(oi);
order.setComment("Order Comments " + UniqueKeyGeneratorUtil.getUniqueKey());
order.setName("Order name " + UniqueKeyGeneratorUtil.getUniqueKey());
order.setOrderItemCollection(items);
order.setStatus("New");
DistributionProtocol dp = getDistributionProtocolById((long)2);
order.setDistributionProtocol(dp);
OrderDetails o = insert(order);
assertTrue(o.getId() > 0);
log.debug(">>> INSERTED ORDER: " + o.getId());
System.out.println(">>> INSERTED ORDER: " + o.getId());
}
public void testNewEmptyOrder() throws ApplicationException {
OrderDetails order = new OrderDetails();
order.setComment("Order Comments " + UniqueKeyGeneratorUtil.getUniqueKey());
order.setName("Order name " + UniqueKeyGeneratorUtil.getUniqueKey());
order.setStatus("New");
DistributionProtocol dp = getDistributionProtocolById((long)2);
order.setDistributionProtocol(dp);
OrderDetails o = insert(order);
assertTrue(o.getId() > 0);
log.debug(">>> INSERTED ORDER: " + o.getId());
System.out.println(">>> INSERTED ORDER: " + o.getId());
}
public void testInsertDistributionProtocol() throws ApplicationException {
DistributionProtocol dp = new DistributionProtocol();
User u = new User();
u.setId((long)1);
dp.setDistributionSpecimenRequirementCollection(new HashSet());
dp.setPrincipalInvestigator(u);
dp.setActivityStatus("Active");
dp.setTitle("DP Title" + UniqueKeyGeneratorUtil.getUniqueKey());
dp.setShortTitle("DP Short Title");
dp.setStartDate(new Date());
dp = insert(dp);
assertTrue(dp.getId() > 0);
System.out.println(dp.getId());
}
}
| bsd-3-clause |
gnu3ra/SCC15HPCRepast | INSTALLATION/mpich2-1.4.1p1/src/mpe2/src/slog2sdk/src/logformat/clog/RecDefState.java | 3957 | /*
* (C) 2001 by Argonne National Laboratory
* See COPYRIGHT in top-level directory.
*/
/*
* @author Anthony Chan
*/
package logformat.clog;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.*;
// Class corresponds to CLOG_STATE
public class RecDefState
{
public final static int RECTYPE = Const.RecType.STATEDEF;
private final static int BYTESIZE = 4 * 4
+ StrDesc.BYTESIZE
+ StrCname.BYTESIZE;
public int stateID; // integer identifier for state
public Integer startetype; // starting event for state
public Integer endetype; // ending event for state
private static int pad;
public String color; // string for color
public String description; // string describing state
//read the record from the given input stream
public int readFromDataStream( MixedDataInputStream in )
{
try {
stateID = in.readInt();
startetype = new Integer( in.readInt() );
endetype = new Integer( in.readInt() );
pad = in.readInt();
color = in.readString( StrCname.BYTESIZE );
description = in.readString( StrDesc.BYTESIZE );
} catch ( IOException ioerr ) {
ioerr.printStackTrace();
return 0;
}
return BYTESIZE;
}
public int skipBytesFromDataStream( DataInputStream in )
{
try {
in.skipBytes( BYTESIZE );
} catch ( IOException ioerr ) {
ioerr.printStackTrace();
return 0;
}
return BYTESIZE;
}
// Mimic <MPE>/src/log_wrap.c's definition of MPI_Init() in initialization
// of states[] and the way MPI_xxx routines's CLOG_STATE is defined
// in MPI_Finalize();
public static List getMPIinitUndefinedStateDefs()
{
RecDefState def;
// evtID is equivalent to the variable "stateid" MPI_Init()
// in <MPE>/src/log_wrap.c
int evtID = Const.MPE_1ST_EVENT;
List defs = new ArrayList( Const.MPE_MAX_STATES );
for ( int idx = 0; idx < Const.MPE_MAX_STATES; idx++ ) {
def = new RecDefState();
def.startetype = new Integer( evtID++ );
def.endetype = new Integer( evtID++ );
def.color = "pink";
def.description = null;
defs.add( def );
}
return defs;
}
public static List getUSERinitUndefinedStateDefs()
{
RecDefState def;
// evtID is equivalent to the variable "stateid" MPI_Init()
// in <MPE>/src/log_wrap.c
int evtID = Const.MPE_USER_1ST_EVENT;
List defs = new ArrayList( Const.MPE_USER_MAX_STATES );
for ( int idx = 0; idx < Const.MPE_USER_MAX_STATES; idx++ ) {
def = new RecDefState();
def.startetype = new Integer( evtID++ );
def.endetype = new Integer( evtID++ );
def.color = "pink";
def.description = null;
defs.add( def );
}
return defs;
}
public String toString()
{
return ( "RecDefState"
+ "[ stateID=" + stateID
+ ", startetype=" + startetype
+ ", endetype=" + endetype
+ ", pad=" + pad
+ ", color=" + color
+ ", description=" + description
// + ", BYTESIZE=" + BYTESIZE
+ " ]" );
}
public static final void main( String[] args )
{
List defs = RecDefState.getMPIinitUndefinedStateDefs();
Iterator itr = defs.iterator();
while ( itr.hasNext() )
System.out.println( (RecDefState) itr.next() );
}
}
| bsd-3-clause |
ThreeToes/lathanbot | src/main/java/com/stephengream/lathanbot/models/StatusObject.java | 418 | package com.stephengream.lathanbot.models;
import java.io.Serializable;
/**
* Simple status object to pass back to clients
* @author stephen
*/
public class StatusObject implements Serializable{
private String message;
public void setMessage(String message) {
this.message = message;
}
public StatusObject(){}
public String getMessage(){
return message;
}
}
| bsd-3-clause |
NCIP/c3pr | codebase/projects/rules/src/java/edu/duke/cabig/c3pr/rules/common/adapter/CaAERSJBossXSLTRuleAdapter.java | 4654 | /*******************************************************************************
* Copyright Duke Comprehensive Cancer Center and SemanticBits
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/c3pr/LICENSE.txt for details.
******************************************************************************/
package edu.duke.cabig.c3pr.rules.common.adapter;
import gov.nih.nci.cabig.c3pr.rules.brxml.Column;
import gov.nih.nci.cabig.c3pr.rules.brxml.Rule;
import gov.nih.nci.cabig.c3pr.rules.brxml.RuleSet;
import edu.duke.cabig.c3pr.rules.common.XMLUtil;
import edu.duke.cabig.c3pr.rules.exception.RuleException;
import edu.duke.cabig.c3pr.utils.XsltTransformer;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.drools.rule.Package;
public class CaAERSJBossXSLTRuleAdapter implements RuleAdapter {
private static final Log log = LogFactory.getLog(CaAERSJBossXSLTRuleAdapter.class);
public Package adapt(RuleSet ruleSet) throws RuleException {
/*
* Add adverseEventEvaluationResult here and remove it from everywhere else since this is a
* hidden column, it should not be used for authoring. It is used only at runtime. So it
* make sense to add to the condition here. IMP: This is only required for caAERS project.
*/
List<Rule> rules = ruleSet.getRule();
for (Rule r : rules) {
Column column_fixed = new Column();
column_fixed
.setObjectType("edu.duke.cabig.c3pr.rules.common.AdverseEventEvaluationResult");
column_fixed.setIdentifier("adverseEventEvaluationResult");
r.getCondition().getColumn().add(column_fixed);
}
List<String> imports = ruleSet.getImport();
if (log.isDebugEnabled()) {
log.debug("Size of imports:" + imports.size());
for (String s : imports) {
log.debug("each import :" + s);
}
}
// marshal and transform
String xml1 = XMLUtil.marshal(ruleSet);
log.debug("Marshalled, Before transforming using [jboss-rules-intermediate.xsl]:\r\n"
+ xml1);
XsltTransformer xsltTransformer = new XsltTransformer();
String xml = "";
try {
xml = xsltTransformer.toXml(xml1, "jboss-rules-intermediate.xsl");
log.debug("After transforming using [jboss-rules-intermediate.xsl] :\n\r" + xml);
} catch (Exception e) {
log.error("Exception while transforming to New Scheme: " + e.getMessage(), e);
}
StringWriter writer = new StringWriter();
System.setProperty("javax.xml.transform.TransformerFactory",
"org.apache.xalan.processor.TransformerFactoryImpl");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
try {
Templates translet = transformerFactory.newTemplates(new StreamSource(Thread
.currentThread().getContextClassLoader().getResourceAsStream(
"new_jobss_rules.xsl")));
Transformer transformer = translet.newTransformer();
if (log.isDebugEnabled()) {
log.debug("Before transforming using [new_jobss_rules.xsl] :\r\n" + xml);
StringWriter strWriter = new StringWriter();
transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(
strWriter));
log.debug("After transforming using [new_jboss_rules.xsl]:\r\n"
+ strWriter.toString());
}
transformer
.transform(new StreamSource(new StringReader(xml)), new StreamResult(
writer));
} catch (Exception e) {
log.error("Error while transforming using new_jboss_rules.xsl", e);
throw new RuleException("Unable to transform using new_jboss_rules.xsl", e);
}
// create the rules package
return XMLUtil.unmarshalToPackage(writer.toString());
}
}
| bsd-3-clause |
atomixnmc/jmonkeyengine | jme3-vr/src/main/java/com/jme3/system/jopenvr/HmdMatrix34_t.java | 1455 | package com.jme3.system.jopenvr;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
/**
* <i>native declaration : headers\openvr_capi.h:933</i><br>
* This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
* a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br>
* For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>.
*/
public class HmdMatrix34_t extends Structure {
/**
* float[3][4]<br>
* C type : float[3][4]
*/
public float[] m = new float[((3) * (4))];
public HmdMatrix34_t() {
super();
}
protected List<String> getFieldOrder() {
return Arrays.asList("m");
}
/**
* @param m float[3][4]<br>
* C type : float[3][4]
*/
public HmdMatrix34_t(float m[]) {
super();
if ((m.length != this.m.length))
throw new IllegalArgumentException("Wrong array size !");
this.m = m;
}
public HmdMatrix34_t(Pointer peer) {
super(peer);
}
public static class ByReference extends HmdMatrix34_t implements Structure.ByReference {
};
public static class ByValue extends HmdMatrix34_t implements Structure.ByValue {
};
}
| bsd-3-clause |
SnakeDoc/GuestVM | guestvm~guestvm/com.oracle.max.ve.tools/src/com/sun/max/ve/tools/trace/cmds/misc/SplitCommand.java | 2523 | /*
* Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.max.ve.tools.trace.cmds.misc;
import java.io.*;
import java.util.List;
import com.sun.max.ve.tools.trace.Command;
import com.sun.max.ve.tools.trace.CommandHelper;
import com.sun.max.ve.tools.trace.TraceElement;
import com.sun.max.ve.tools.trace.TraceMain;
public class SplitCommand extends CommandHelper implements Command {
private static final String OUT_TRACE_FILE = "outfile=";
@Override
public void doIt(List<TraceElement> traces, String[] args) throws Exception {
final int cpu = TraceMain.cpuOption();
if (cpu < 0) {
// TODO split all CPUs
} else {
PrintStream wr = null;
final String outFile = outFile(args);
try {
if (outFile == null) {
wr = System.out;
} else {
wr = new PrintStream(new FileOutputStream(outFile));
}
for (TraceElement traceElement : traces) {
if (cpu == traceElement.getCpu()) {
wr.println(traceElement);
}
}
} catch (Exception ex) {
System.err.println(ex);
} finally {
if (wr != null && wr != System.out) {
wr.close();
}
}
}
}
private String outFile(String[] args) {
return stringArgValue(args, OUT_TRACE_FILE);
}
}
| bsd-3-clause |
bluemind-net/ical4j-vcard | src/main/java/net/fortuna/ical4j/vcard/property/Mailer.java | 4251 | /**
* Copyright (c) 2012, Ben Fortuna
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* o Neither the name of Ben Fortuna nor the names of any other contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.fortuna.ical4j.vcard.property;
import java.net.URISyntaxException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.List;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.vcard.Group;
import net.fortuna.ical4j.vcard.Parameter;
import net.fortuna.ical4j.vcard.Property;
import net.fortuna.ical4j.vcard.PropertyFactory;
/**
* MAILER property (vCard 3.0 only).
*
* $Id$
*
* Created on 24/08/2008
*
* @author Ben
*
*/
public final class Mailer extends Property {
private static final long serialVersionUID = 6134254373259957228L;
public static final PropertyFactory<Mailer> FACTORY = new Factory();
private String value;
/**
* @param value an email address string
*/
public Mailer(String value) {
this((Group) null, value);
}
/**
* @param group property group
* @param value an email address string
*/
public Mailer(Group group, String value) {
super(group, Id.MAILER);
this.value = value;
}
/**
* Factory constructor.
* @param params property parameters
* @param value string representation of a property value
*/
public Mailer(List<Parameter> params, String value) {
this(null, params, value);
}
/**
* Factory constructor.
* @param group property group
* @param params property parameters
* @param value string representation of a property value
*/
public Mailer(Group group, List<Parameter> params, String value) {
super(group, Id.MAILER, params);
this.value = value;
}
/**
* {@inheritDoc}
*/
@Override
public String getValue() {
return value;
}
/**
* {@inheritDoc}
*/
@Override
public void validate() throws ValidationException {
for (Parameter param : getParameters()) {
final Parameter.Id id = param.getId();
if (!Parameter.Id.EXTENDED.equals(id)) {
throw new ValidationException(MessageFormat.format(ILLEGAL_PARAMETER_MESSAGE, id));
}
}
}
private static class Factory implements PropertyFactory<Mailer> {
/**
* {@inheritDoc}
*/
public Mailer createProperty(final List<Parameter> params, final String value) {
return new Mailer(params, value);
}
/**
* {@inheritDoc}
*/
public Mailer createProperty(final Group group, final List<Parameter> params, final String value)
throws URISyntaxException, ParseException {
return new Mailer(group, params, value);
}
}
}
| bsd-3-clause |
AllTheDucks/jshack | b2/src/main/java/org/oscelot/jshack/security/EntitlementFilter.java | 1059 | package org.oscelot.jshack.security;
import blackboard.platform.security.Entitlement;
import blackboard.platform.security.SecurityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import java.io.IOException;
public class EntitlementFilter implements ContainerRequestFilter {
final Logger logger = LoggerFactory.getLogger(EntitlementFilter.class);
final static Entitlement REQUIRED_ENTITLEMENT = new Entitlement("system.jshacks.CREATE");
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if(!SecurityUtil.userHasEntitlement(REQUIRED_ENTITLEMENT)) {
throw buildAuthException();
}
}
private WebApplicationException buildAuthException() {
return new WebApplicationException(
Response.status(Response.Status.UNAUTHORIZED).build());
}
}
| bsd-3-clause |
grammarware/slps | topics/fl/java1/types/Binary.java | 332 | package types;
/**
* Binary expressions
*/
public class Binary extends Expr {
public Ops ops;
public Expr left, right;
public Binary(Ops o, Expr left, Expr right) {
this.ops = o;
this.left = left;
this.right = right;
}
public void accept(Visitor v) {
v.visit(this);
}
}
| bsd-3-clause |
Errryx/AndroidSocialManager | src_renren/com/renren/api/connect/android/pay/view/PayRepaiListAdapter.java | 4693 | package com.renren.api.connect.android.pay.view;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.renren.api.connect.android.pay.bean.PayOrder;
import com.renren.api.connect.android.pay.impl.RenrenPay;
import com.socialmanager.R;
public class PayRepaiListAdapter extends BaseAdapter {
private ArrayList<RepairListItem> items = new ArrayList<RepairListItem>();
@Override
public int getCount() {
if (items != null) {
return items.size();
}
return 0;
}
public PayRepaiListAdapter(List<PayOrder> orders) {
super();
if (orders != null) {
for (PayOrder o : orders) {
items.add(new RepairListItem(o));
}
}
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
if (items != null && position >= 0 && position < items.size()) {
return items.get(position);
}
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, final ViewGroup parent) {
if (items != null && position >= 0 && position < items.size()) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.renren_sdk_pay_repair_item, null);
final RepairListItem item = items.get(position);
TextView orderNumView = (TextView) itemView
.findViewById(R.id.renren_sdk_pay_repair_item_order_num);
TextView desView = (TextView) itemView
.findViewById(R.id.renren_sdk_pay_repair_item_des);
TextView bidView = (TextView) itemView
.findViewById(R.id.renren_sdk_pay_repair_item_bid);
TextView timeView = (TextView) itemView
.findViewById(R.id.renren_sdk_pay_repair_item_time);
TextView amountView = (TextView) itemView
.findViewById(R.id.renren_sdk_pay_repair_item_amount);
TextView statusView = (TextView) itemView
.findViewById(R.id.renren_sdk_pay_repair_item_status);
Button repairBtn = (Button) itemView
.findViewById(R.id.renren_sdk_pay_repair_item_repair_button);
orderNumView.setText(item.getOrderNumber());
desView.setText(item.getOrderDes());
bidView.setText(item.getOrderBid());
timeView.setText(item.getOrderTime());
amountView.setText(item.getOrderAmount());
statusView.setText(item.getOrderStatus());
//如果订单失败,则设置红色醒目
if(!item.getOrder().isSuccess())
{
statusView.setTextColor(Color.RED);
}
repairBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
RenrenPay.getInstance().repairOrder(parent.getContext(),
item.getOrder());
} catch (Exception e) {
e.printStackTrace();// do nothing
}
}
});
convertView = itemView;
}
return convertView;
}
class RepairListItem {
public String getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
public String getOrderDes() {
return orderDes;
}
public void setOrderDes(String orderDes) {
this.orderDes = orderDes;
}
public String getOrderBid() {
return orderBid;
}
public void setOrderBid(String orderBid) {
this.orderBid = orderBid;
}
public String getOrderAmount() {
return orderAmount;
}
public void setOrderAmount(String orderAmount) {
this.orderAmount = orderAmount;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
public String getOrderTime() {
return orderTime;
}
public void setOrderTime(String orderTime) {
this.orderTime = orderTime;
}
private String orderNumber;
private String orderDes;
private String orderBid;
private String orderAmount;
private String orderStatus;
private String orderTime;
private PayOrder order;
public PayOrder getOrder() {
return order;
}
public RepairListItem(PayOrder order) {
this.order = order;
orderNumber = order.getOrderNumber();
orderDes = order.getDescr();
if ((orderBid = order.getBid()) == null || orderBid.equals("")) {
orderBid = "未获得流水号";
}
orderAmount = String.valueOf(order.getAmount());
orderStatus = order.isSuccess() ? "订单成功" : "订单失败";
orderTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getOrderTime());
}
}
}
| bsd-3-clause |
NCIP/catissue-core | software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/NewSpecimenAction.java | 62248 | /*L
* Copyright Washington University in St. Louis
* Copyright SemanticBits
* Copyright Persistent Systems
* Copyright Krishagni
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/catissue-core/LICENSE.txt for details.
*/
/**
* <p>
* Title: NewSpecimenAction Class>
* <p>
* Description: NewSpecimenAction initializes the fields in the New Specimen
* page.
* </p>
* Copyright: Copyright (c) year Company: Washington University, School of
* Medicine, St. Louis.
*
* @author Aniruddha Phadnis
* @version 1.00
*/
package edu.wustl.catissuecore.action;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.common.dynamicextensions.xmi.AnnotationUtil;
import edu.wustl.catissuecore.action.annotations.AnnotationConstants;
import edu.wustl.catissuecore.actionForm.NewSpecimenForm;
import edu.wustl.catissuecore.bizlogic.NewSpecimenBizLogic;
import edu.wustl.catissuecore.bizlogic.StorageContainerForSpecimenBizLogic;
import edu.wustl.catissuecore.bizlogic.UserBizLogic;
import edu.wustl.catissuecore.domain.Biohazard;
import edu.wustl.catissuecore.domain.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domain.ConsentTier;
import edu.wustl.catissuecore.domain.ConsentTierResponse;
import edu.wustl.catissuecore.domain.ConsentTierStatus;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domain.SpecimenRequirement;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.catissuecore.factory.DomainInstanceFactory;
import edu.wustl.catissuecore.factory.InstanceFactory;
import edu.wustl.catissuecore.util.CatissueCoreCacheManager;
import edu.wustl.catissuecore.util.ConsentUtil;
import edu.wustl.catissuecore.util.EventsUtil;
import edu.wustl.catissuecore.util.SpecimenUtil;
import edu.wustl.catissuecore.util.StorageContainerUtil;
import edu.wustl.catissuecore.util.global.AppUtility;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.DefaultValueManager;
import edu.wustl.catissuecore.util.global.Variables;
import edu.wustl.common.action.SecureAction;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.cde.CDE;
import edu.wustl.common.cde.CDEManager;
import edu.wustl.common.cde.PermissibleValue;
import edu.wustl.common.exception.ApplicationException;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.factory.AbstractFactoryConfig;
import edu.wustl.common.factory.IFactory;
import edu.wustl.common.util.MapDataParser;
import edu.wustl.common.util.Utility;
import edu.wustl.common.util.global.CommonServiceLocator;
import edu.wustl.common.util.global.Validator;
import edu.wustl.common.util.logger.Logger;
import edu.wustl.dao.DAO;
import edu.wustl.dao.QueryWhereClause;
import edu.wustl.dao.condition.EqualClause;
import edu.wustl.dao.exception.DAOException;
// TODO: Auto-generated Javadoc
/**
* The Class NewSpecimenAction.
*
* @author renuka_bajpai
*/
public class NewSpecimenAction extends CatissueBaseAction
{
/** logger. */
private static final Logger LOGGER = Logger.getCommonLogger(NewSpecimenAction.class);
/** The Constant CONSENT_BEN. */
private static final String CONSENT_BEN="ConsentBean:";
/**
* Overrides the execute method of Action class.
*
* @param mapping object of ActionMapping
* @param form object of ActionForm
* @param request object of HttpServletRequest
* @param response object of HttpServletResponse
*
* @return the action forward
*
* @throws Exception generic exception
*/
public ActionForward executeCatissueAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
DAO dao = null;
try
{
final SessionDataBean sessionData = (SessionDataBean) request.getSession()
.getAttribute(Constants.SESSION_DATA);
final NewSpecimenForm newSpecimenForm = (NewSpecimenForm) form;
if(!(newSpecimenForm.getDisposeStatus()==null)&&!(newSpecimenForm.getDisposeStatus().equals("")))
{
newSpecimenForm.setActivityStatus(newSpecimenForm.getDisposeStatus());
newSpecimenForm.setDisposeStatus("");
}
String transferStatus=newSpecimenForm.getTransferStatus();
if(transferStatus!=null && !transferStatus.equals("transferDone"))
{
request.setAttribute("transferStatus", transferStatus);
}
// else if(transferStatus!=null && transferStatus.equals("transferDone"))
// {
// request.setAttribute("transferStatus", "");
// }
else
{
request.setAttribute("transferStatus", "");
}
dao = AppUtility.openDAOSession(sessionData);
// Logger.out.debug("NewSpecimenAction start@@@@@@@@@");
final NewSpecimenForm specimenForm = (NewSpecimenForm) form;
final List<NameValueBean> storagePositionList = AppUtility.getStoragePositionTypeList();
if(transferStatus!=null && !transferStatus.equals(""))
{
storagePositionList.remove(0);
}
request.setAttribute("storageList", storagePositionList);
String pageOf = request.getParameter(Constants.PAGE_OF);
final String forwardPage = specimenForm.getForwardTo();
if (forwardPage.equals(Constants.PAGE_OF_SPECIMEN_COLLECTION_REQUIREMENT_GROUP))
{
pageOf = forwardPage;
request.setAttribute(Constants.STATUS_MESSAGE_KEY,
"errors.specimencollectionrequirementgroupedit");
return mapping.findForward(pageOf);
}
final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
final NewSpecimenBizLogic bizLogic = (NewSpecimenBizLogic) factory
.getBizLogic(Constants.NEW_SPECIMEN_FORM_ID);
final String treeRefresh = request.getParameter("refresh");
request.setAttribute("refresh", treeRefresh);
// Gets the value of the operation parameter.
final String operation = (String) request.getParameter(Constants.OPERATION);
final String transfer = (String) request.getParameter("transfer");
// boolean to indicate whether the suitable containers to be shown in
// dropdown
// is exceeding the max limit.
final String exceedingMaxLimit = "";
// Sets the operation attribute to be used in the Edit/View Specimen
// Page in Advance Search Object View.
request.setAttribute(Constants.OPERATION, operation);
request.setAttribute("transfer", transfer);
request.setAttribute("fromPositionDimensionOne", specimenForm.getFromPositionDimensionOne());
request.setAttribute("fromPositionDimensionTwo", specimenForm.getFromPositionDimensionTwo());
request.setAttribute("fromStorageContainer", specimenForm.getFromStorageContainerId());
if (operation != null && operation.equalsIgnoreCase(Constants.ADD))
{
specimenForm.setId(0);
}
final String virtuallyLocated = request.getParameter("virtualLocated");
if (virtuallyLocated != null && virtuallyLocated.equals("true"))
{
specimenForm.setVirtuallyLocated(true);
}
// Name of button clicked
final String button = request.getParameter("button");
Map map = null;
if (button != null)
{
if ("deleteExId".equals(button))
{
final List<String> key = new ArrayList<String>();
key.add("ExternalIdentifier:i_name");
key.add("ExternalIdentifier:i_value");
// Gets the map from ActionForm
map = specimenForm.getExternalIdentifier();
MapDataParser.deleteRow(key, map, request.getParameter("status"));
}
else
{
final List<String> key = new ArrayList<String>();
key.add("Biohazard:i_type");
key.add("Biohazard:i_id");
// Gets the map from ActionForm
map = specimenForm.getBiohazard();
MapDataParser.deleteRow(key, map, request.getParameter("status"));
}
}
// ************* ForwardTo implementation *************
final HashMap forwardToHashMap = (HashMap) request.getAttribute("forwardToHashMap");
String specimenCollectionGroupName = "";
if (forwardToHashMap != null)
{
final String specimenCollectionGroupId = (String) forwardToHashMap
.get("specimenCollectionGroupId");
/** For Migration Start **/
specimenCollectionGroupName = (String) forwardToHashMap
.get("specimenCollectionGroupName");
this.LOGGER
.debug("specimenCollectionGroupName found in forwardToHashMap========>>>>>>"
+ specimenCollectionGroupName);
specimenForm.setSpecimenCollectionGroupName(specimenCollectionGroupName);
/** For Migration End **/
this.LOGGER
.debug("SpecimenCollectionGroupId found in forwardToHashMap========>>>>>>"
+ specimenCollectionGroupId);
if (specimenCollectionGroupId != null)
{
/**
* Retaining properties of specimen when more is clicked. Bug no
* -- 2623
*/
// Populating the specimen collection group name in the specimen
// page
this.setFormValues(specimenForm, specimenCollectionGroupId,
specimenCollectionGroupName);
}
}
// ************* ForwardTo implementation *************
// Consent Tracking (Virender Mehta) - Start
// Adding name,value pair in NameValueBean
final String tabSelected = request.getParameter(Constants.SELECTED_TAB);
if (tabSelected != null)
{
request.setAttribute(Constants.SELECTED_TAB, tabSelected);
}
final String scg_id = String.valueOf(specimenForm.getSpecimenCollectionGroupId());
final SpecimenCollectionGroup specimenCollectionGroup = AppUtility.getSCGObj(scg_id,
dao);
// PHI Data
String initialURLValue = "";
String initialWitnessValue = "";
String initialSignedConsentDateValue = "";
// Lazy - specimenCollectionGroup.getCollectionProtocolRegistration()
final CollectionProtocolRegistration collectionProtocolRegistration = specimenCollectionGroup
.getCollectionProtocolRegistration();
String parentLabelFormat = null;
String derivativeLabelFormat = null;
String aliquotLabelFormat = null;
if(Variables.isTemplateBasedLblGeneratorAvl){
parentLabelFormat = collectionProtocolRegistration.getCollectionProtocol().getSpecimenLabelFormat();
derivativeLabelFormat = collectionProtocolRegistration.getCollectionProtocol().getDerivativeLabelFormat();
aliquotLabelFormat = collectionProtocolRegistration.getCollectionProtocol().getAliquotLabelFormat();
}
String lineage = specimenForm.getLineage();
if(lineage == null || "".equals(lineage))
{
lineage = Constants.NEW_SPECIMEN;
}
boolean generateLabel = SpecimenUtil.isLblGenOnForCP(parentLabelFormat, derivativeLabelFormat, aliquotLabelFormat, lineage);
if(!Validator.isEmpty(specimenForm.getOperation()) && !specimenForm.getOperation().equals(Constants.EDIT))
{
specimenForm.setGenerateLabel(generateLabel);
}
if (!Validator.isEmpty(specimenForm.getOperation()) && !specimenForm.getOperation().equals(Constants.ADD))
{
String hql = "select specimen.specimenRequirement from edu.wustl.catissuecore.domain.Specimen as specimen"
+" where specimen.id="+ specimenForm.getId();
List<Object[]> list=null;
list=AppUtility.executeQuery(hql);
if(list!=null && !list.isEmpty())
{
Object object = list.get(0);
SpecimenRequirement requirement = (SpecimenRequirement)object;
InstanceFactory<Specimen> instFact = DomainInstanceFactory.getInstanceFactory(Specimen.class);
Specimen specimen = instFact.createObject();//new Specimen();
specimen.setSpecimenRequirement(requirement);
specimen.setLineage(specimenForm.getLineage());
specimen.setSpecimenCollectionGroup(specimenCollectionGroup);
// if(requirement != null && requirement.getGenLabel() && !Validator.isEmpty(requirement.getLabelFormat()))
// {
// generateLabel = requirement.getGenLabel();
// }
// else if(requirement != null && !requirement.getGenLabel())
// {
generateLabel = SpecimenUtil.isGenLabel(specimen);
// }
// /objSpecimen.setSpecimenRequirement((SpecimenRequirement)object);
}
}
if(Variables.isTemplateBasedLblGeneratorAvl)
{
specimenForm.setGenerateLabel(generateLabel);
}
else if(Variables.isSpecimenLabelGeneratorAvl)
{
specimenForm.setGenerateLabel(Variables.isSpecimenLabelGeneratorAvl);
}
else
{
specimenForm.setGenerateLabel(false);
}
if (collectionProtocolRegistration == null
|| collectionProtocolRegistration.getSignedConsentDocumentURL() == null)
{
initialURLValue = Constants.NULL;
}
User consentWitness = null;
if (collectionProtocolRegistration.getId() != null)
{
final List consentWitnessList = dao.retrieveAttribute(
(Class) (CollectionProtocolRegistration.class), "id",
collectionProtocolRegistration.getId(), "consentWitness");
if ((consentWitnessList != null) && (!consentWitnessList.isEmpty()))
{
consentWitness = (User) consentWitnessList.get(0);
}
}
// User consentWitness=
// collectionProtocolRegistration.getConsentWitness();
// Resolved lazy
if (consentWitness == null)
{
initialWitnessValue = Constants.NULL;
}
if (collectionProtocolRegistration.getConsentSignatureDate() == null)
{
initialSignedConsentDateValue = Constants.NULL;
}
// final List<CollectionProtocolRegistration> cprObjectList = new ArrayList<CollectionProtocolRegistration>();
// cprObjectList.add(collectionProtocolRegistration);
/*
* SessionDataBean sessionDataBean = (SessionDataBean)
* request.getSession().getAttribute( Constants.SESSION_DATA);
*/
// CaCoreAppServicesDelegator caCoreAppServicesDelegator = new
// CaCoreAppServicesDelegator();
// String userName = Utility.toString(sessionDataBean.getUserName());
/*
* List collProtObject =
* caCoreAppServicesDelegator.delegateSearchFilter(userName,
* cprObjectList);
*/
CollectionProtocolRegistration cprObject;
cprObject = collectionProtocolRegistration;
String witnessName = "";
String getConsentDate = "";
String getSignedConsentURL = "";
User witness = cprObject.getConsentWitness();
if (witness == null)
{
if (initialWitnessValue.equals(Constants.NULL))
{
witnessName = "";
}
else
{
witnessName = Constants.HASHED_OUT;
}
specimenForm.setWitnessName(witnessName);
}
else
{
final List userList = dao.retrieveAttribute(
(Class) CollectionProtocolRegistration.class, "id", cprObject.getId(),
"consentWitness");
if ((userList != null) && (!userList.isEmpty()))
{
witness = (User) userList.get(0);
}
final String witnessFullName = witness.getLastName() + ", "
+ witness.getFirstName();
specimenForm.setWitnessName(witnessFullName);
}
if (cprObject.getConsentSignatureDate() == null)
{
if (initialSignedConsentDateValue.equals(Constants.NULL))
{
getConsentDate = "";
}
else
{
getConsentDate = Constants.HASHED_OUT;
}
}
else
{
getConsentDate = Utility.parseDateToString(cprObject.getConsentSignatureDate(),
CommonServiceLocator.getInstance().getDatePattern());
}
if (cprObject.getSignedConsentDocumentURL() == null)
{
if (initialURLValue.equals(Constants.NULL))
{
getSignedConsentURL = "";
}
else
{
getSignedConsentURL = Constants.HASHED_OUT;
}
}
else
{
getSignedConsentURL = Utility.toString(cprObject.getSignedConsentDocumentURL());
}
specimenForm.setConsentDate(getConsentDate);
specimenForm.setSignedConsentUrl(getSignedConsentURL);
final List consentTierRespCollection = dao.retrieveAttribute(
CollectionProtocolRegistration.class, "id", cprObject.getId(),
"elements(consentTierResponseCollection)");
// Lazy Resolved --- cprObject.getConsentTierResponseCollection()
List participantResponseList;
if (consentTierRespCollection == null)
{
participantResponseList = new ArrayList();
}
else
{
participantResponseList = new ArrayList(consentTierRespCollection);
}
if (operation.equalsIgnoreCase(Constants.ADD))
{
final ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);
if (errors == null)
{
final String scgDropDown = request.getParameter(Constants.SCG_DROPDOWN);
if (scgDropDown == null || scgDropDown.equalsIgnoreCase(Constants.TRUE))
{
final Collection consentResponseStatuslevel = (Collection) dao
.retrieveAttribute((Class) SpecimenCollectionGroup.class, "id",
specimenCollectionGroup.getId(),
"elements(consentTierStatusCollection)");
final Map<String, Comparable> tempMap = this.prepareConsentMap(participantResponseList,
consentResponseStatuslevel);
specimenForm.setConsentResponseForSpecimenValues(tempMap);
}
}
specimenForm.setConsentTierCounter(participantResponseList.size());
}
else
{
// // List added for grid
final List specimenDetails = new ArrayList();
final List specimenDetailList = new ArrayList();
specimenDetailList.add(specimenForm.getLabel());
specimenDetailList.add(specimenForm.getType());
if (specimenForm.getStContSelection() == Constants.STORAGE_TYPE_POSITION_VIRTUAL_VALUE) {
specimenDetailList.add(Constants.VIRTUALLY_LOCATED);
} else {
if (specimenForm.getStorageContainer() != null) {
final String storageLocation = specimenForm.getSelectedContainerName()
+ ": X-Axis-"
+ specimenForm.getPositionDimensionOne()
+ ", Y-Axis-"
+ specimenForm.getPositionDimensionTwo();
specimenDetailList.add(storageLocation);
}
}
specimenDetailList.add(specimenForm.getClass());
specimenDetails.add(specimenDetailList);
// Added by Falguni=To set Specimen label in Form.
/*
* Bug id = 11480Resolved by : Himanshu Aseeja
*/
final List<String> columnList = this.columnNames();
final String consentResponseHql = "select elements(scg.collectionProtocolRegistration."
+ "consentTierResponseCollection)"
+ " from edu.wustl.catissuecore.domain.SpecimenCollectionGroup as scg,"
+ " edu.wustl.catissuecore.domain.Specimen as spec "
+ " where spec.specimenCollectionGroup.id=scg.id and spec.id="
+ specimenForm.getId();
final Collection consentResponse = dao.executeQuery(consentResponseHql);
final List consentResponseStatuslevel = dao.retrieveAttribute(Specimen.class, "id",
specimenForm.getId(), "elements(consentTierStatusCollection)");
final String specimenResponse = "_specimenLevelResponse";
final String specimenResponseId = "_specimenLevelResponseID";
final Map<String, Comparable> tempMap = ConsentUtil.prepareSCGResponseMap(consentResponseStatuslevel,
consentResponse, specimenResponse, specimenResponseId);
specimenForm.setConsentResponseForSpecimenValues(tempMap);
specimenForm.setConsentTierCounter(participantResponseList.size());
final HttpSession session = request.getSession();
request.setAttribute("showContainer", specimenForm.getCollectionStatus());
session.setAttribute(Constants.SPECIMEN_LIST, specimenDetails);
session.setAttribute(Constants.COLUMNLIST, columnList);
}
specimenForm.setConsentResponseForSpecimenValues(ConsentUtil.updateConsentMap(specimenForm.getConsentResponseForSpecimenValues()));
List specimenResponseList = new ArrayList();
specimenResponseList = AppUtility.responceList(operation);
request.setAttribute(Constants.SPECIMEN_RESPONSELIST, specimenResponseList);
// Consent Tracking (Virender Mehta) - Stop
pageOf = request.getParameter(Constants.PAGE_OF);
request.setAttribute(Constants.PAGE_OF, pageOf);
// Sets the activityStatusList attribute to be used in the Site Add/Edit
// Page.
request.setAttribute(Constants.ACTIVITYSTATUSLIST, Constants.ACTIVITY_STATUS_VALUES);
// Sets the collectionStatusList attribute to be used in the Site
// Add/Edit Page.
request.setAttribute(Constants.COLLECTIONSTATUSLIST,
Constants.SPECIMEN_COLLECTION_STATUS_VALUES);
if(specimenForm.getActivityStatus().equals(Constants.ACTIVE)||specimenForm.getActivityStatus().equals(""))
{
request.setAttribute(Constants.NOTCLOSEDACTIVITYSTATUS,
Constants.NOT_CLOSED_ACTIVITY_STATUS);
}
else
{
request.setAttribute(Constants.NOTCLOSEDACTIVITYSTATUS,
Constants.CLOSED_ACTIVITY_STATUS);
}
// NewSpecimenBizLogic bizLogic = (NewSpecimenBizLogic)
// BizLogicFactory.getInstance
// ().getBizLogic(Constants.NEW_SPECIMEN_FORM_ID);
// if (specimenForm.isParentPresent())// If parent specimen is present then
// {
// // String[] fields = {Constants.SYSTEM_LABEL};
// // List parentSpecimenList =
// // bizLogic.getList(Specimen.class.getName(), fields,
// // Constants.SYSTEM_IDENTIFIER, true);
// // request.setAttribute(Constants.PARENT_SPECIMEN_ID_LIST,
// // parentSpecimenList);
// }
String[] bhIdArray = {"-1"};
String[] bhTypeArray = {Constants.SELECT_OPTION};
String[] bhNameArray = {Constants.SELECT_OPTION};
final String[] selectColNames = {Constants.SYSTEM_IDENTIFIER, "name", "type"};
List biohazardList = dao.retrieve(Biohazard.class.getName(), selectColNames);
final Iterator iterator = biohazardList.iterator();
// Creating & setting the biohazard name, id & type list
if (biohazardList != null && !biohazardList.isEmpty())
{
bhIdArray = new String[biohazardList.size() + 1];
bhTypeArray = new String[biohazardList.size() + 1];
bhNameArray = new String[biohazardList.size() + 1];
bhIdArray[0] = "-1";
bhTypeArray[0] = "";
bhNameArray[0] = Constants.SELECT_OPTION;
int arrayCtr = 1;
while (iterator.hasNext())
{
final Object[] hazard = (Object[]) iterator.next();
bhIdArray[arrayCtr] = String.valueOf(hazard[0]);
bhNameArray[arrayCtr] = (String) hazard[1];
bhTypeArray[arrayCtr] = (String) hazard[2];
arrayCtr++;
}
}
request.setAttribute(Constants.BIOHAZARD_NAME_LIST, bhNameArray);
request.setAttribute(Constants.BIOHAZARD_ID_LIST, bhIdArray);
request.setAttribute(Constants.BIOHAZARD_TYPES_LIST, bhTypeArray);
/**
* Name: Chetan Patil Reviewer: Sachin Lale Bug ID: Bug#3184 Patch ID:
* Bug#3184_1 Also See: 2-6 Description: Here the older code has been
* integrated again inorder to restrict the specimen values based on
* requirements of study calendar event point. Two method are written to
* separate the code. Method populateAllRestrictedLists() will populate
* the values for the lists form Specimen Requirements whereas, method
* populateAllLists() will populate the values of the list form the
* system.
*/
// Setting Secimen Collection Group
/** For Migration Start **/
// initializeAndSetSpecimenCollectionGroupIdList(bizLogic,request);
/** For Migration Start **/
/**
* Patch ID: Bug#4245_2
*/
final List<NameValueBean> specimenClassList = new ArrayList<NameValueBean>();
final List<NameValueBean> specimenTypeList = new ArrayList<NameValueBean>();
final List<NameValueBean> tissueSiteList = new ArrayList<NameValueBean>();
final List<NameValueBean> tissueSideList = new ArrayList<NameValueBean>();
final List<NameValueBean> pathologicalStatusList = new ArrayList<NameValueBean>();
final Map<String, List<NameValueBean>> subTypeMap = new HashMap<String, List<NameValueBean>>();
final String specimenCollectionGroupId = specimenForm.getSpecimenCollectionGroupId();
if (Validator.isEmpty(specimenCollectionGroupId))
{ // On adding a new specimen independently.
this.populateAllLists(specimenForm, specimenClassList, specimenTypeList,
tissueSiteList, tissueSideList, pathologicalStatusList, subTypeMap);
}
else
{
// If specimen is being added form specimen collection group page or a
// specimen is being edited.
if (Constants.ALIQUOT.equals(specimenForm.getLineage()))
{
this.populateListBoxes(specimenForm, request);
}
this.populateAllLists(specimenForm, specimenClassList, specimenTypeList,
tissueSiteList, tissueSideList, pathologicalStatusList, subTypeMap);
}
/**
* Name : Virender Mehta Reviewer: Sachin Lale Bug ID:
* defaultValueConfiguration_BugID Patch
* ID:defaultValueConfiguration_BugID_10 See
* also:defaultValueConfiguration_BugID_9,11 Description: Configuration
* of default value for TissueSite, TissueSite, PathologicalStatus Note
* by Chetan: Value setting for TissueSite and PathologicalStatus has
* been moved into the method populateAllLists().
*/
// Setting the default values
if (specimenForm.getTissueSide() == null || specimenForm.getTissueSide().equals("-1"))
{
specimenForm.setTissueSide((String) DefaultValueManager
.getDefaultValue(Constants.DEFAULT_TISSUE_SIDE));
}
// sets the Specimen Class list
request.setAttribute(Constants.SPECIMEN_CLASS_LIST, specimenClassList);
// sets the Specimen Type list
request.setAttribute(Constants.SPECIMEN_TYPE_LIST, specimenTypeList);
// sets the Tissue Site list
request.setAttribute(Constants.TISSUE_SITE_LIST, tissueSiteList);
// sets the PathologicalStatus list
request.setAttribute(Constants.PATHOLOGICAL_STATUS_LIST, pathologicalStatusList);
// sets the Side list
request.setAttribute(Constants.TISSUE_SIDE_LIST, tissueSideList);
// set the map of subtype
request.setAttribute(Constants.SPECIMEN_TYPE_MAP, subTypeMap);
// Setting biohazard list
biohazardList = CDEManager.getCDEManager().getPermissibleValueList(
Constants.CDE_NAME_BIOHAZARD, null);
request.setAttribute(Constants.BIOHAZARD_TYPE_LIST, biohazardList);
final Object scgForm = request.getAttribute("scgForm");
if (scgForm == null)
{
// SpecimenCollectionGroupForm specimenCollectionGroupForm =
// (SpecimenCollectionGroupForm) scgForm;
// Mandar : 10-July-06 AutoEvents : CollectionEvent
this.setCollectionEventRequestParameters(request, specimenForm);
// Mandar : 11-July-06 AutoEvents : ReceivedEvent
this.setReceivedEventRequestParameters(request, specimenForm);
// Mandar : set default date and time too event fields
this.setDateParameters(specimenForm);
}
// ---- chetan 15-06-06 ----
final StorageContainerForSpecimenBizLogic scbizLogic = new StorageContainerForSpecimenBizLogic();
TreeMap<NameValueBean, Map<NameValueBean, List<NameValueBean>>> containerMap = new TreeMap<NameValueBean, Map<NameValueBean, List<NameValueBean>>>();
List<String[]> initialValues = null;
if (operation.equals(Constants.ADD) || (transferStatus != null && transferStatus.equals("transferred")))
{
// if (specimenForm.getLabel() == null || specimenForm.getLabel().equals(""))
// {
// // int totalNoOfSpecimen =
// // bizLogic.totalNoOfSpecimen(sessionData)+1;
// /**
// * Name : Virender Mehta Reviewer: Sachin Lale Description:
// * By getting instance of AbstractSpecimenGenerator abstract
// * class current label retrived and set.
// */
// }
if (specimenForm.getSpecimenCollectionGroupName() != null
&& !specimenForm.getSpecimenCollectionGroupName().equals("")
&& specimenForm.getClassName() != null
&& !specimenForm.getClassName().equals("")
&& !specimenForm.getClassName().equals("-1"))
{
final List spCollGroupList = this.getSpCollGroupList(specimenForm
.getSpecimenCollectionGroupName(), dao);
if (spCollGroupList != null && !spCollGroupList.isEmpty())
{
final long cpId = ((Long) spCollGroupList.get(0)).longValue();
final String spClass = specimenForm.getClassName();
LOGGER.info("cpId :" + cpId + "spClass:" + spClass);
request.setAttribute(Constants.COLLECTION_PROTOCOL_ID, String.valueOf(cpId));
if (virtuallyLocated != null && virtuallyLocated.equals("false"))
{
specimenForm.setVirtuallyLocated(false);
}
if (specimenForm.getStContSelection() == 2)
{
containerMap = scbizLogic.getAllocatedContainerMapForSpecimen
(AppUtility.setparameterList(cpId,spClass,0,specimenForm.getType()),sessionData, dao);
LOGGER
.debug("finish ---calling getAllocatedContaienrMapForSpecimen() function from NewSpecimenAction---");
ActionErrors errors = (ActionErrors) request
.getAttribute(Globals.ERROR_KEY);
if (containerMap.isEmpty())
{
if (errors == null || errors.size() == 0)
{
errors = new ActionErrors();
}
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(
"storageposition.not.available"));
this.saveErrors(request, errors);
}
LOGGER
.debug("calling checkForInitialValues() function from NewSpecimenAction---");
if (errors == null || errors.size() == 0)
{
initialValues = StorageContainerUtil
.checkForInitialValues(containerMap);
}
else
{
final String[] startingPoints = new String[3];
startingPoints[0] = specimenForm.getStorageContainer();
startingPoints[1] = specimenForm.getPositionDimensionOne();
startingPoints[2] = specimenForm.getPositionDimensionTwo();
initialValues = new Vector<String[]>();
initialValues.add(startingPoints);
}
LOGGER
.debug("finish ---calling"
+ " checkForInitialValues() function from NewSpecimenAction---");
}
}
}
}
else
{
containerMap = new TreeMap<NameValueBean, Map<NameValueBean, List<NameValueBean>>>();
final String[] startingPoints = new String[]{"-1", "-1", "-1"};
LOGGER.info("--------------container:" + specimenForm.getStorageContainer());
LOGGER.info("--------------pos1:" + specimenForm.getPositionDimensionOne());
LOGGER.info("--------------pos2:" + specimenForm.getPositionDimensionTwo());
if (specimenForm.getStorageContainer() != null
&& !specimenForm.getStorageContainer().equals(""))
{
final Integer identifier = Integer.valueOf(specimenForm.getStorageContainer());
String parentContainerName = "";
Object object = null;
if (identifier > 0)
{
object = dao.retrieveById(StorageContainer.class.getName(), Long.valueOf(
specimenForm.getStorageContainer()));
}
if (object != null)
{
final StorageContainer container = (StorageContainer) object;
parentContainerName = container.getName();
}
final Integer pos1 = Integer.valueOf(specimenForm.getPositionDimensionOne());
final Integer pos2 = Integer.valueOf(specimenForm.getPositionDimensionTwo());
final List<NameValueBean> pos2List = new ArrayList<NameValueBean>();
pos2List.add(new NameValueBean(pos2, pos2));
final Map<NameValueBean, List<NameValueBean>> pos1Map = new TreeMap<NameValueBean, List<NameValueBean>>();
pos1Map.put(new NameValueBean(pos1, pos1), pos2List);
containerMap.put(new NameValueBean(parentContainerName, identifier), pos1Map);
if (specimenForm.getStorageContainer() != null
&& !specimenForm.getStorageContainer().equals("-1"))
{
startingPoints[0] = specimenForm.getStorageContainer();
}
if (specimenForm.getPositionDimensionOne() != null
&& !specimenForm.getPositionDimensionOne().equals("-1"))
{
startingPoints[1] = specimenForm.getPositionDimensionOne();
}
if (specimenForm.getPositionDimensionTwo() != null
&& !specimenForm.getPositionDimensionTwo().equals("-1"))
{
startingPoints[2] = specimenForm.getPositionDimensionTwo();
}
}
initialValues = new Vector<String[]>();
LOGGER.info("Starting points[0]" + startingPoints[0]);
LOGGER.info("Starting points[1]" + startingPoints[1]);
LOGGER.info("Starting points[2]" + startingPoints[2]);
initialValues.add(startingPoints);
final String showContainer = (String) request.getAttribute("showContainer");
if ((showContainer == null || showContainer.equals("Pending")) && (specimenForm.getStContSelection() == Constants.RADIO_BUTTON_FOR_MAP || specimenForm
.getStContSelection() == 2))
{
final long cpId = specimenCollectionGroup.getCollectionProtocolRegistration().getCollectionProtocol().getId();
final String spClass = specimenForm.getClassName();
final String spType = specimenForm.getType();
LOGGER.info("cpId :" + cpId + "spClass:" + spClass);
request.setAttribute(Constants.COLLECTION_PROTOCOL_ID, String.valueOf(cpId));
if (virtuallyLocated != null && virtuallyLocated.equals("false"))
{
specimenForm.setVirtuallyLocated(false);
}
containerMap = scbizLogic.getAllocatedContainerMapForSpecimen(AppUtility.
setparameterList(cpId,spClass,0,spType), sessionData, dao);
LOGGER.debug("finish ---calling getAllocatedContaienrMapForSpecimen() function from NewSpecimenAction---");
ActionErrors errors = (ActionErrors) request
.getAttribute(Globals.ERROR_KEY);
if (containerMap.isEmpty())
{
if (specimenForm.getSelectedContainerName() == null
|| "".equals(specimenForm.getSelectedContainerName()))
{
if (errors == null || errors.size() == 0)
{
errors = new ActionErrors();
}
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(
"storageposition.not." + "available"));
this.saveErrors(request, errors);
}
}
Logger.out.debug("calling checkForInitialValues()"
+ " function from NewSpecimenAction---");
if (errors == null || errors.size() == 0)
{
initialValues = StorageContainerUtil
.checkForInitialValues(containerMap);
}
else
{
final String[] startingPoints1 = new String[3];
startingPoints1[0] = specimenForm.getStorageContainer();
startingPoints1[1] = specimenForm.getPositionDimensionOne();
startingPoints1[2] = specimenForm.getPositionDimensionTwo();
initialValues = new Vector<String[]>();
initialValues.add(startingPoints1);
}
if (spClass != null
&& specimenForm.getStContSelection() == Constants.RADIO_BUTTON_FOR_MAP)
{
final String[] startingPoints2 = new String[]{"-1", "-1", "-1"};
initialValues = new ArrayList<String[]>();
initialValues.add(startingPoints2);
request.setAttribute("initValues", initialValues);
}
}
// }
}
// }
request.setAttribute("initValues", initialValues);
request.setAttribute(Constants.EXCEEDS_MAX_LIMIT, exceedingMaxLimit);
request.setAttribute(Constants.AVAILABLE_CONTAINER_MAP, containerMap);
// -------------------------
// Falguni:Performance Enhancement.
Long specimenEntityId;
/*if (CatissueCoreCacheManager.getInstance().getObjectFromCache("specimenEntityId") != null)
{
specimenEntityId = (Long) CatissueCoreCacheManager.getInstance()
.getObjectFromCache("specimenEntityId");
}
else
{
specimenEntityId = AnnotationUtil
.getEntityId(AnnotationConstants.ENTITY_NAME_SPECIMEN);
CatissueCoreCacheManager.getInstance().addObjectToCache("specimenEntityId",
specimenEntityId);
}
request.setAttribute("specimenEntityId", specimenEntityId);*/
if (CatissueCoreCacheManager.getInstance().getObjectFromCache(
AnnotationConstants.SPECIMEN_REC_ENTRY_ENTITY_ID) == null)
{
specimenEntityId = AnnotationUtil
.getEntityId(AnnotationConstants.ENTITY_NAME_SPECIMEN_REC_ENTRY);
CatissueCoreCacheManager.getInstance().addObjectToCache(
AnnotationConstants.SPECIMEN_REC_ENTRY_ENTITY_ID, specimenEntityId);
}
else
{
specimenEntityId = (Long) CatissueCoreCacheManager.getInstance().getObjectFromCache(
AnnotationConstants.SPECIMEN_REC_ENTRY_ENTITY_ID);
}
request.setAttribute(AnnotationConstants.SPECIMEN_REC_ENTRY_ENTITY_ID, specimenEntityId);
if (specimenForm.isVirtuallyLocated())
{
request.setAttribute("disabled", "true");
}
// set associated identified report id
Long reportId = this.getAssociatedIdentifiedReportId(specimenForm.getId(), dao);
if (reportId == null)
{
reportId = -1l;
}
else if (AppUtility.isQuarantined(reportId))
{
reportId = -2l;
}
/*
if(StringUtils.isBlank(specimenForm.getGlobalSpecimenIdentifer())) {
//validate identifier
GSIDClient client = new GSIDClient();
boolean isValid = false;
try {
// validates every time not matter user updates or not .. second time the validation fails because this id exists in GSID DB ,
// so if validation fails we need to make sure this gsid is new one . to do that we can check in caTissue db if the id is assigned to some other specimen
isValid = client.validateIdentifier(specimenForm.getGlobalSpecimenIdentifer());
if (!isValid) {
//check in caTissue DB if this identifier belongs to another specimen id
Object obj = dao.retrieveById(Specimen.class.getName(), specimenForm.getId());
//Specimen s1 = (Specimen)obj;
//String className = s1.getClass().getName();
//System.out.println(s1.getId());
List list = dao.executeQuery(" from Specimen s where s.globalSpecimenIdentifier = '"+specimenForm.getGlobalSpecimenIdentifer()+"'");
if (list.size() > 0 ) {
Specimen s = (Specimen)list.get(0);
Long id = s.getId();
if (id.longValue() == specimenForm.getId()) {
isValid = true;
}
}
}
} catch (Exception e) {
// error if format is not valid ..
e.printStackTrace();
}
if (isValid) {
}
}*/
final HttpSession session = request.getSession();
session.setAttribute(Constants.IDENTIFIED_REPORT_ID, reportId);
// Logger.out.debug("End of specimen action");
request.setAttribute("createdDate", specimenForm.getCreatedDate());
request.setAttribute("specimenActivityStatus",
Constants.SPECIMEN_ACTIVITY_STATUS_VALUES);
//session.setAttribute("assignedGsId", );
return mapping.findForward(pageOf);
}
catch (final DAOException daoException)
{
LOGGER.error(daoException.getMessage(),daoException);
throw AppUtility.getApplicationException(daoException, daoException.getErrorKeyName(),
daoException.getMsgValues());
}
catch (RemoteException re) {
LOGGER.error(re.getMessage(),re);
throw AppUtility.getApplicationException(re, re.getMessage(),
re.getMessage());
}
finally
{
AppUtility.closeDAOSession(dao);
}
}
/**
* This method populates the list boxes for type, tissue site, tissue side
* and pathological status if this specimen is an aliquot.
*
* @param specimenForm object of NewSpecimenForm
* @param request object of HttpServletRequest
*/
private void populateListBoxes(NewSpecimenForm specimenForm, HttpServletRequest request)
{
// Setting the specimen type list
NameValueBean bean = new NameValueBean(specimenForm.getType(), specimenForm.getType());
final List<NameValueBean> specimenTypeList = new ArrayList<NameValueBean>();
specimenTypeList.add(bean);
request.setAttribute(Constants.SPECIMEN_TYPE_LIST, specimenTypeList);
// Setting tissue site list
bean = new NameValueBean(specimenForm.getTissueSite(), specimenForm.getTissueSite());
final List<NameValueBean> tissueSiteList = new ArrayList<NameValueBean>();
tissueSiteList.add(bean);
request.setAttribute(Constants.TISSUE_SITE_LIST, tissueSiteList);
// Setting tissue side list
bean = new NameValueBean(specimenForm.getTissueSide(), specimenForm.getTissueSide());
final List<NameValueBean> tissueSideList = new ArrayList<NameValueBean>();
tissueSideList.add(bean);
request.setAttribute(Constants.TISSUE_SIDE_LIST, tissueSideList);
// Setting pathological status list
bean = new NameValueBean(specimenForm.getPathologicalStatus(), specimenForm
.getPathologicalStatus());
final List<NameValueBean> pathologicalStatusList = new ArrayList<NameValueBean>();
pathologicalStatusList.add(bean);
request.setAttribute(Constants.PATHOLOGICAL_STATUS_LIST, pathologicalStatusList);
}
// Mandar AutoEvents CollectionEvent start
/**
* This method sets all the collection event parameters for the
* SpecimenEventParameter pages.
*
* @param request HttpServletRequest instance in which the data will be set.
* @param specimenForm NewSpecimenForm instance
*
* @throws Exception Throws Exception. Helps in handling exceptions at one common
* point.
*/
private void setCollectionEventRequestParameters(HttpServletRequest request,
NewSpecimenForm specimenForm) throws Exception
{
final String operation = request.getParameter(Constants.OPERATION);
request.setAttribute(Constants.OPERATION, operation);
request.setAttribute(Constants.MINUTES_LIST, Constants.MINUTES_ARRAY);
request.setAttribute(Constants.HOUR_LIST, Constants.HOUR_ARRAY);
final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
final UserBizLogic userBizLogic = (UserBizLogic) factory
.getBizLogic(Constants.USER_FORM_ID);
final Collection userCollection = userBizLogic.getUsers(operation);
request.setAttribute(Constants.USERLIST, userCollection);
final SessionDataBean sessionData = this.getSessionData(request);
if (sessionData != null)
{
setEvents(specimenForm, userCollection, sessionData);
}
final List procedureList = CDEManager.getCDEManager().getPermissibleValueList(
Constants.CDE_NAME_COLLECTION_PROCEDURE, null);
request.setAttribute(Constants.PROCEDURE_LIST, procedureList);
// Bug- setting the default collection event procedure
if (specimenForm.getCollectionEventCollectionProcedure() == null)
{
specimenForm.setCollectionEventCollectionProcedure((String) DefaultValueManager
.getDefaultValue(Constants.DEFAULT_COLLECTION_PROCEDURE));
}
final List containerList = CDEManager.getCDEManager().getPermissibleValueList(
Constants.CDE_NAME_CONTAINER, null);
request.setAttribute(Constants.CONTAINER_LIST, containerList);
if (specimenForm.getCollectionEventContainer() == null)
{
specimenForm.setCollectionEventContainer((String) DefaultValueManager
.getDefaultValue(Constants.DEFAULT_CONTAINER));
}
}
/**
* This will set events in the form.
*
* @param specimenForm specimenForm
* @param userCollection userCollection
* @param sessionData sessionData
*/
private void setEvents(NewSpecimenForm specimenForm, final Collection userCollection,
final SessionDataBean sessionData)
{
final String user = sessionData.getLastName() + ", " + sessionData.getFirstName();
final long collectionEventUserId = EventsUtil.getIdFromCollection(userCollection, user);
if (specimenForm.getCollectionEventUserId() == 0)
{
specimenForm.setCollectionEventUserId(collectionEventUserId);
}
if (specimenForm.getReceivedEventUserId() == 0)
{
specimenForm.setReceivedEventUserId(collectionEventUserId);
}
}
// Mandar AutoEvents CollectionEvent end
// Mandar Autoevents ReceivedEvent start
/**
* This method sets all the received event parameters for the
* SpecimenEventParameter pages.
*
* @param request HttpServletRequest instance in which the data will be set.
* @param specimenForm NewSpecimenForm instance
*
* @throws Exception Throws Exception. Helps in handling exceptions at one common
* point.
*/
private void setReceivedEventRequestParameters(HttpServletRequest request,
NewSpecimenForm specimenForm) throws Exception
{
final List qualityList = CDEManager.getCDEManager().getPermissibleValueList(
Constants.CDE_NAME_RECEIVED_QUALITY, null);
request.setAttribute(Constants.RECEIVED_QUALITY_LIST, qualityList);
// Bug- setting the default recieved event quality
if (specimenForm.getReceivedEventReceivedQuality() == null)
{
specimenForm.setReceivedEventReceivedQuality((String) DefaultValueManager
.getDefaultValue(Constants.DEFAULT_RECEIVED_QUALITY));
}
}
/**
* Set date parameters.
*
* @param specimenForm instance of NewSpecimenForm
*/
private void setDateParameters(NewSpecimenForm specimenForm)
{
// Collection Event fields
setCollectionEvents(specimenForm);
// ReceivedEvent Fields
setRecievedEvents(specimenForm);
}
/**
* set recieved events.
*
* @param specimenForm specimenForm
*/
private void setRecievedEvents(NewSpecimenForm specimenForm)
{
final Calendar cal;
cal = Calendar.getInstance();
if (specimenForm.getReceivedEventDateOfEvent() == null)
{
specimenForm.setReceivedEventDateOfEvent(Utility.parseDateToString(cal.getTime(),
CommonServiceLocator.getInstance().getDatePattern()));
}
if (specimenForm.getReceivedEventTimeInHours() == null)
{
specimenForm.setReceivedEventTimeInHours(Integer
.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (specimenForm.getReceivedEventTimeInMinutes() == null)
{
specimenForm.setReceivedEventTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
/**
* set collected events.
*
* @param specimenForm specimenForm
*/
private void setCollectionEvents(NewSpecimenForm specimenForm)
{
final Calendar cal = Calendar.getInstance();
if (specimenForm.getCollectionEventdateOfEvent() == null)
{
specimenForm.setCollectionEventdateOfEvent(Utility.parseDateToString(cal.getTime(),
CommonServiceLocator.getInstance().getDatePattern()));
}
if (specimenForm.getCollectionEventTimeInHours() == null)
{
specimenForm.setCollectionEventTimeInHours(Integer.toString(cal
.get(Calendar.HOUR_OF_DAY)));
}
if (specimenForm.getCollectionEventTimeInMinutes() == null)
{
specimenForm
.setCollectionEventTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
/**
* Prepare consent map.
*
* @param participantResponseList the participant response list
* @param consentResponse the consent response
*
* @return the map
*/
/*
* private void clearCollectionEvent(NewSpecimenForm specimenForm) {
* specimenForm.setCollectionEventCollectionProcedure("");
* specimenForm.setCollectionEventComments("");
* specimenForm.setCollectionEventContainer("");
* specimenForm.setCollectionEventdateOfEvent("");
* specimenForm.setCollectionEventTimeInHours("");
* specimenForm.setCollectionEventTimeInMinutes("");
* specimenForm.setCollectionEventUserId(-1); }
*/
/**
* @param specimenForm
* instance of NewSpecimenForm
*/
/*
* private void clearReceivedEvent(NewSpecimenForm specimenForm) {
* specimenForm.setReceivedEventComments("");
* specimenForm.setReceivedEventDateOfEvent("");
* specimenForm.setReceivedEventReceivedQuality("");
* specimenForm.setReceivedEventTimeInHours("");
* specimenForm.setReceivedEventTimeInMinutes("");
* specimenForm.setReceivedEventUserId(-1); }
*/
/**
*
* @param participantResponseList : participantResponseList
* @param consentResponse : consentResponse
* @return Map : Map
*/
private Map<String, Comparable> prepareConsentMap(List participantResponseList, Collection consentResponse)
{
final Map<String, Comparable> tempMap = new HashMap<String, Comparable>();
Long consentTierID;
Long consentID;
if (participantResponseList != null || consentResponse != null)
{
int counter = 0;
final Iterator consentResponseCollectionIter = participantResponseList.iterator();
while (consentResponseCollectionIter.hasNext())
{
final ConsentTierResponse consentTierResponse = (ConsentTierResponse) consentResponseCollectionIter
.next();
final Iterator statusCollectionIter = consentResponse.iterator();
consentTierID = consentTierResponse.getConsentTier().getId();
while (statusCollectionIter.hasNext())
{
final ConsentTierStatus consentTierstatus = (ConsentTierStatus) statusCollectionIter
.next();
consentID = consentTierstatus.getConsentTier().getId();
if (consentTierID.longValue() == consentID.longValue())
{
final ConsentTier consent = consentTierResponse.getConsentTier();
final String idKey = CONSENT_BEN + counter + "_consentTierID";
final String statementKey = CONSENT_BEN + counter + "_statement";
final String responseKey = "ConsentBean:" + counter + "_participantResponse";
final String participantResponceIdKey = CONSENT_BEN + counter
+ "_participantResponseID";
final String scgResponsekey = CONSENT_BEN + counter
+ "_specimenCollectionGroupLevelResponse";
final String scgResponseIDkey = CONSENT_BEN + counter
+ "_specimenCollectionGroupLevelResponseID";
final String specimenResponsekey = CONSENT_BEN + counter
+ "_specimenLevelResponse";
final String specimenResponseIDkey = CONSENT_BEN + counter
+ "_specimenLevelResponseID";
tempMap.put(idKey, consent.getId());
tempMap.put(statementKey, consent.getStatement());
tempMap.put(responseKey, consentTierResponse.getResponse());
tempMap.put(participantResponceIdKey, consentTierResponse.getId());
tempMap.put(scgResponsekey, consentTierstatus.getStatus());
tempMap.put(scgResponseIDkey, consentTierstatus.getId());
tempMap.put(specimenResponsekey, consentTierstatus.getStatus());
tempMap.put(specimenResponseIDkey, null);
counter++;
break;
}
}
}
return tempMap;
}
else
{
return null;
}
}
// Consent Tracking (Virender Mehta)
/**
* Sets the form values.
*
* @param specimenForm instance of NewSpecimenForm
* @param specimenCollectionGroupId String containing specimen collection group Id
* @param specimenCollectionGroupName String containing specimen collection group name
*/
private void setFormValues(NewSpecimenForm specimenForm, String specimenCollectionGroupId,
String specimenCollectionGroupName)
{
specimenForm.setSpecimenCollectionGroupId(specimenCollectionGroupId);
specimenForm.setSpecimenCollectionGroupName(specimenCollectionGroupName);
specimenForm.setVirtuallyLocated(true);
specimenForm.setParentSpecimenId("");
specimenForm.setLabel("");
specimenForm.setBarcode("");
specimenForm.setPositionInStorageContainer("");
specimenForm.setPositionDimensionOne("");
specimenForm.setPositionDimensionTwo("");
specimenForm.setStorageContainer("");
}
/**
* Patch ID: Bug#3184_2.
*
* @param specimenForm the specimen form
* @param specimenClassList the specimen class list
* @param specimenTypeList the specimen type list
* @param tissueSiteList the tissue site list
* @param tissueSideList the tissue side list
* @param pathologicalStatusList the pathological status list
* @param subTypeMap the sub type map
*
* @throws BizLogicException the biz logic exception
*/
/**
* This method initializes the List of SpecimenCollectionGroup in the system
* and sets the list as an attribute in the request.
*
* @param bizLogic
* NewSpecimenBizLogic to fetch the SpecimenCollectionGroup list
* @param request
* HttpServletRequest in which the list is set as an attribute
* @throws DAOException
* on failure to initialize the list
*/
/** For Migration Start **/
/*
* private void
* initializeAndSetSpecimenCollectionGroupIdList(NewSpecimenBizLogic
* bizLogic, HttpServletRequest request) throws DAOException { String
* sourceObjectName = SpecimenCollectionGroup.class.getName(); String[]
* displayNameFields = {"name"}; String valueField =
* Constants.SYSTEM_IDENTIFIER; List specimenCollectionGroupList =
* bizLogic.getList(sourceObjectName, displayNameFields, valueField, true);
* request.setAttribute(Constants.SPECIMEN_COLLECTION_GROUP_LIST,
* specimenCollectionGroupList); }
*/
/**
* This method generates Map of SpecimenClass and the List of the
* corresponding Types.
*
* @param tempMap
* a temporary Map for avoiding duplication of values.
* @param subTypeMap
* the Map of SpecimenClass and the List of the corresponding
* Types
* @param specimenClass
* Class of Speciment
* @param specimenType
* Type of Specimen
*/
/*
* private void populateSpecimenTypeLists(Map < String , String > tempMap,
* Map < String , List < NameValueBean >> subTypeMap, String specimenClass,
* String specimenType) { List < NameValueBean > tempList =
* subTypeMap.get(specimenClass); if (tempList == null) { tempList = new
* ArrayList < NameValueBean >(); tempList.add(new
* NameValueBean(Constants.SELECT_OPTION, "-1")); tempList.add(new
* NameValueBean(specimenType, specimenType)); subTypeMap.put(specimenClass,
* tempList); tempMap.put(specimenClass + specimenType +
* Constants.SPECIMEN_TYPE, specimenType); } else { tempList =
* subTypeMap.get(specimenClass); tempList.add(new
* NameValueBean(specimenType, specimenType)); Collections.sort(tempList);
* subTypeMap.put(specimenClass, tempList); tempMap.put(specimenClass +
* specimenType + Constants.SPECIMEN_TYPE, specimenType); } }
*/
/**
* This method populates all the values form the system for the respective
* lists.
*
* @param specimenForm
* NewSpecimenForm to set the List of TissueSite and
* PathologicalStatus
* @param specimenClassList
* List of Specimen Class
* @param specimenTypeList
* List of Specimen Type
* @param tissueSiteList
* List of Tissue Site
* @param tissueSideList
* List of Tissue Side
* @param pathologicalStatusList
* List of Pathological Status
* @param subTypeMap
* Map of the Class and their corresponding Types
* @throws BizLogicException
* on failure to populate values from the system
*/
private void populateAllLists(NewSpecimenForm specimenForm,
List<NameValueBean> specimenClassList, List<NameValueBean> specimenTypeList,
List<NameValueBean> tissueSiteList, List<NameValueBean> tissueSideList,
List<NameValueBean> pathologicalStatusList, Map<String, List<NameValueBean>> subTypeMap)
throws BizLogicException
{
// Getting the specimen type list
specimenTypeList = AppUtility.getListFromCDE(Constants.CDE_NAME_SPECIMEN_TYPE);
/**
* Name : Virender Mehta Reviewer: Sachin Lale Bug ID:
* TissueSiteCombo_BugID Patch ID:TissueSiteCombo_BugID_1 See
* also:TissueSiteCombo_BugID_2 Description: Getting TissueList with
* only Leaf node
*/
tissueSiteList.addAll(AppUtility.tissueSiteList());
// Getting tissue side list
tissueSideList.addAll(AppUtility.getListFromCDE(Constants.CDE_NAME_TISSUE_SIDE));
// Getting pathological status list
pathologicalStatusList.addAll(AppUtility
.getListFromCDE(Constants.CDE_NAME_PATHOLOGICAL_STATUS));
// get the Specimen class and type from the cde
final CDE specimenClassCDE = CDEManager.getCDEManager().getCDE(
Constants.CDE_NAME_SPECIMEN_CLASS);
final Set<PermissibleValue> setPV = specimenClassCDE.getPermissibleValues();
for (final PermissibleValue pv : setPV)
{
final String tmpStr = pv.getValue();
this.LOGGER.debug(tmpStr);
specimenClassList.add(new NameValueBean(tmpStr, tmpStr));
final List<NameValueBean> innerList = new ArrayList<NameValueBean>();
innerList.add(new NameValueBean(Constants.SELECT_OPTION, "-1"));
final Set<PermissibleValue> list1 = pv.getSubPermissibleValues();
this.LOGGER.debug("list1 " + list1);
for (final PermissibleValue pv1 : list1)
{
// set specimen type
final String tmpInnerStr = pv1.getValue();
this.LOGGER.debug("\t\t" + tmpInnerStr);
innerList.add(new NameValueBean(tmpInnerStr, tmpInnerStr));
}
Collections.sort(innerList);
subTypeMap.put(tmpStr, innerList);
} // class and values set
this.LOGGER.debug("\n\n\n\n**********MAP DATA************\n");
// Setting the default values
if (specimenForm.getTissueSite() == null)
{
specimenForm.setTissueSite((String) DefaultValueManager
.getDefaultValue(Constants.DEFAULT_TISSUE_SITE));
}
if (specimenForm.getPathologicalStatus() == null)
{
specimenForm.setPathologicalStatus((String) DefaultValueManager
.getDefaultValue(Constants.DEFAULT_PATHOLOGICAL_STATUS));
}
AppUtility.setDefaultPrinterTypeLocation(specimenForm);
}
/**
* Checks if is scg event coll empty.
*
* @param scgEventColl the scg event coll
*
* @return true, if checks if is scg event coll empty
*/
private static boolean isSCGEventCollEmpty(final Collection scgEventColl)
{
return scgEventColl != null && !scgEventColl.isEmpty();
}
/**
* This function adds the columns to the List.
*
* @return columnList
*/
public List<String> columnNames()
{
final List<String> columnList = new ArrayList<String>();
columnList.add(Constants.LABLE);
columnList.add(Constants.TYPE);
columnList.add(Constants.STORAGE_CONTAINER_LOCATION);
columnList.add(Constants.CLASS_NAME);
return columnList;
}
/**
* Gets the associated identified report id.
*
* @param specimenId : specimenId
* @param dao the dao
*
* @return Long : Long
*
* @throws ApplicationException : ApplicationException
*/
private Long getAssociatedIdentifiedReportId(Long specimenId, DAO dao)
throws ApplicationException
{
Long valueToReturn = null;
final String hqlString = "select scg.identifiedSurgicalPathologyReport.id "
+ " from edu.wustl.catissuecore.domain.SpecimenCollectionGroup as scg, "
+ " edu.wustl.catissuecore.domain.Specimen as specimen" + " where specimen.id = "
+ specimenId + " and specimen.id in elements(scg.specimenCollection)";
final List reportIDList = dao.executeQuery(hqlString);
if (reportIDList != null && !reportIDList.isEmpty())
{
valueToReturn = ((Long) reportIDList.get(0));
}
return valueToReturn;
}
/**
* Gets the sp coll group list.
*
* @param scgName the scg name
* @param dao the dao
*
* @return String : String
*
* @throws BizLogicException the biz logic exception
*/
/*protected String getObjectId(AbstractActionForm form)
{
NewSpecimenForm specimenForm = (NewSpecimenForm) form;
SpecimenCollectionGroup specimenCollectionGroup = null;
if (specimenForm.getSpecimenCollectionGroupId() != null
|| specimenForm.getSpecimenCollectionGroupId() != "")
{
try
{
specimenCollectionGroup = AppUtility.getSCGObj(specimenForm
.getSpecimenCollectionGroupId());
CollectionProtocolRegistration cpr = specimenCollectionGroup
.getCollectionProtocolRegistration();
if (cpr != null)
{
CollectionProtocol cp = cpr.getCollectionProtocol();
return Constants.COLLECTION_PROTOCOL_CLASS_NAME + "_" + cp.getId();
}
}
catch (ApplicationException e)
{
logger.debug(e.getMessage(), e);
e.printStackTrace();
}
}
return null;
}*/
/**
* This will return the SCG list.
* @param scgName scgName
* @param dao dao
* @return scg list
* @throws BizLogicException BizLogicException
*/
private List getSpCollGroupList(String scgName, DAO dao) throws BizLogicException
{
String name = scgName;
final String[] selectColumnName = {"collectionProtocolRegistration.collectionProtocol.id"};
List spCollGroupList = null;
try
{
final QueryWhereClause queryWhereClause = new QueryWhereClause(
SpecimenCollectionGroup.class.getName());
if(name.contains("'"))
{
name = name.replace("'", "''");
}
queryWhereClause.addCondition(new EqualClause("name", name));
spCollGroupList = dao.retrieve(SpecimenCollectionGroup.class.getName(),
selectColumnName, queryWhereClause);
}
catch (final DAOException e)
{
LOGGER.error(e.getMessage(), e);
throw new BizLogicException(e);
}
return spCollGroupList;
}
}
| bsd-3-clause |
iti-luebeck/RTeasy1 | src/main/java/de/uniluebeck/iti/rteasy/gui/MemoryFrameTableModel.java | 3660 | /*
* Copyright (c) 2003-2013, University of Luebeck, Institute of Computer Engineering
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Luebeck, the Institute of Computer
* Engineering nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE UNIVERSITY OF LUEBECK OR THE INSTITUTE OF COMPUTER
* ENGINEERING 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 de.uniluebeck.iti.rteasy.gui;
import javax.swing.table.AbstractTableModel;
import javax.swing.JOptionPane;
import de.uniluebeck.iti.rteasy.RTSimGlobals;
import de.uniluebeck.iti.rteasy.kernel.Memory;
import java.awt.Component;
public class MemoryFrameTableModel extends AbstractTableModel {
private Memory m;
public int base = RTSimGlobals.BASE_HEX;
private int memdw, memaw;
private int memsize;
private boolean taddr[];
private Component parent;
MemoryFrameTableModel(Memory tm, Component tp) {
m = tm;
parent = tp;
memaw = m.getAddrWidth();
taddr = new boolean[memaw];
memdw = m.getDataWidth();
memsize = 1 << memaw;
}
public int getMemSize() { return memsize; }
public boolean isCellEditable(int row, int col) {
return col == 1;
}
public int getRowCount() { return memsize; }
public int getColumnCount() { return 2; }
public Object getValueAt(int row, int col) {
if(col == 0)
return Integer.toString(row,16).toUpperCase();
else if(col == 1) {
RTSimGlobals.intInBoolArray(taddr,row);
return RTSimGlobals.boolArray2String(m.getDataAt(taddr),base);
}
else return "";
}
public void setValueAt(Object value, int row, int col) {
if(col == 1 && row < memsize) {
RTSimGlobals.intInBoolArray(taddr,row);
try {
m.setDataAt(taddr,RTSimGlobals.string2boolArray(value.toString(),
memdw,base));
}
catch (NumberFormatException e) {
JOptionPane.showInternalMessageDialog(parent,
RTSimGlobals.baseInputErrorMsg(base),
"Eingabefehler in Speicherzelle",JOptionPane.ERROR_MESSAGE);
}
}
}
public String getColumnName(int col) {
switch(col) {
case 0: return IUI.get("COLUMN_ADDRESS");
case 1: return IUI.get("BUTTON_CONTENT");
}
return "";
}
}
| bsd-3-clause |
felixjongleur/NSui | src/mdes/slick/sui/test/ThemeDump.java | 12680 | /*
* ThemeDump.java
*
* Created on November 10, 2007, 7:52 PM
*/
package mdes.slick.sui.test;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import mdes.slick.sui.Sui;
import mdes.slick.sui.Button;
import mdes.slick.sui.CheckBox;
import mdes.slick.sui.Container;
import mdes.slick.sui.Display;
import mdes.slick.sui.Label;
import mdes.slick.sui.Theme;
import mdes.slick.sui.Frame;
import mdes.slick.sui.event.ActionEvent;
import mdes.slick.sui.event.ActionListener;
import mdes.slick.sui.skin.simple.SimpleSkin;
import mdes.slick.sui.theme.BitterLemonTheme;
import mdes.slick.sui.theme.CopperTheme;
import mdes.slick.sui.theme.SteelAcidTheme;
import mdes.slick.sui.theme.SteelBlueTheme;
import mdes.slick.sui.theme.SteelSepiaTheme;
import mdes.slick.sui.theme.XMLThemeIO;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.gui.GUIContext;
/**
*
* @author davedes
*/
public class ThemeDump extends BasicGame {
public static void main(String[] args) throws Exception {
AppGameContainer app = new AppGameContainer(new ThemeDump());
app.setDisplayMode(800,600,false);
app.start();
}
/** Creates a new instance of ThemeDump */
public ThemeDump() {
super("ThemeDump");
}
public static final int COLORS = 17;
private Label[] labels = new Label[COLORS];
private Label[] methodNames = new Label[COLORS];
private Color[] colors = new Color[COLORS];
private String[] methods;
private ArrayList themes = new ArrayList();
private Label nameLabel;
private Display display;
private int currentIndex = 0;
private Button left, right;
private Frame demoBox = null;
private void populateThemes() {
themes.add(new SteelBlueTheme());
themes.add(new SteelSepiaTheme());
themes.add(new SteelAcidTheme());
themes.add(new BitterLemonTheme());
themes.add(new CopperTheme());
try { themes.add(XMLThemeIO.read("res/steelBlue.xml")); }
catch (Exception e) {}
}
public void init(GameContainer container) throws SlickException {
//Sui.setSkin(new WireframeSkin());
display = new Display(container);
display.setSendingGlobalEvents(false);
display.setFocusable(true);
//setup method names
Method[] m = Theme.class.getMethods();
Arrays.sort(m, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Method)o1).getName().compareTo(((Method)o2).getName());
}
});
ArrayList list = new ArrayList(COLORS);
for (int i=0; i<m.length; i++) {
String nameStr = m[i].getName();
if (nameStr.indexOf("getName") == -1)
list.add(nameStr);
}
methods = (String[])list.toArray(new String[list.size()]);
//dump names
//for (int i=0;i<methods.length;i++) {
// System.out.println("private color "+Character.toLowerCase(methods[i].charAt(3))+methods[i].substring(4)+" =");
//}
//dump methods
//for (int i=0;i<methods.length;i++) {
// String var = Character.toLowerCase(methods[i].charAt(3))+methods[i].substring(4);
// System.out.println("public Color "+methods[i]+"() { return "+var+"; }");
//}
class BorderLabel extends Label {
public void renderComponent(GUIContext c, Graphics g) {
super.renderComponent(c, g);
g.setColor(Color.darkGray);
g.draw(this.getAbsoluteBounds());
}
};
float startx = 280;
float starty = 70;
Container parent = display;
for (int i=0; i<labels.length; i++) {
methodNames[i] = new BorderLabel();
methodNames[i].setText(methods[i]);
methodNames[i].setSize(155, 25);
methodNames[i].setOpaque(true);
methodNames[i].setLocation(startx, starty+i*(methodNames[i].getHeight()+5));
parent.add(methodNames[i]);
labels[i] = new BorderLabel();
labels[i].setOpaque(true);
labels[i].setSize(65, 25);
labels[i].setLocation(startx+methodNames[i].getWidth()+5, starty+i*(labels[i].getHeight()+5));
parent.add(labels[i]);
}
Container panel = new Container();
left = new Button("Previous");
left.pack();
left.setRequestFocusEnabled(false);
left.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (currentIndex>0) {
currentIndex--;
setTheme((Theme)themes.get(currentIndex));
updateButtons();
}
}
});
panel.add(left);
right = new Button("Next");
right.pack();
right.setRequestFocusEnabled(false);
right.setX(left.getWidth()+5);
right.setHeight(left.getHeight());
right.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (currentIndex<themes.size()-1) {
currentIndex++;
setTheme((Theme)themes.get(currentIndex));
updateButtons();
}
}
});
panel.add(right);
panel.setSize(right.getX()+right.getWidth(), left.getHeight());
panel.setLocationRelativeTo(display);
panel.setY(starty-panel.getHeight()-5);
display.add(panel);
nameLabel = new Label("No themes found.");
nameLabel.pack();
nameLabel.setLocationRelativeTo(display);
nameLabel.setY(panel.getY()-nameLabel.getHeight()-5);
display.add(nameLabel);
final CheckBox box = new CheckBox("Show Demo Box");
demoBox = new DemoFrame();
demoBox.setLocation(50, 100);
demoBox.getCloseButton().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
box.setSelected(false);
}
});
display.add(demoBox);
box.pack();
box.setX(demoBox.getX());
box.setY(demoBox.getY()-box.getHeight()-5);
box.setSelected(true);
box.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
demoBox.setVisible(box.isSelected());
}
});
box.setRequestFocusEnabled(false);
display.add(box);
if (Sui.getSkin() instanceof SimpleSkin) {
final CheckBox roundBox = new CheckBox("Round Rectangles");
roundBox.pack();
roundBox.setSelected(true);
SimpleSkin.setRoundRectanglesEnabled(roundBox.isSelected());
roundBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SimpleSkin.setRoundRectanglesEnabled(roundBox.isSelected());
}
});
box.setWidth(Math.max(roundBox.getWidth(), box.getWidth()));
roundBox.setWidth(Math.max(roundBox.getWidth(), box.getWidth()));
roundBox.setLocation(box.getX(), box.getY()-roundBox.getHeight()-5);
roundBox.setRequestFocusEnabled(false);
display.add(roundBox);
}
//load up the themes
populateThemes();
if (!themes.isEmpty()) {
setTheme((Theme)themes.get(0));
}
updateButtons();
}
private void setTheme(Theme theme) {
if (theme==null)
return;
Sui.setTheme(theme);
colors[0] = theme.getActiveTitleBar1();
colors[1] = theme.getActiveTitleBar2();
colors[2] = theme.getBackground();
colors[3] = theme.getDisabledMask();
colors[4] = theme.getForeground();
colors[5] = theme.getPrimary1();
colors[6] = theme.getPrimary2();
colors[7] = theme.getPrimary3();
colors[8] = theme.getPrimaryBorder1();
colors[9] = theme.getPrimaryBorder2();
colors[10] = theme.getSecondary1();
colors[11] = theme.getSecondary2();
colors[12] = theme.getSecondary3();
colors[13] = theme.getSecondaryBorder1();
colors[14] = theme.getSecondaryBorder2();
colors[15] = theme.getTitleBar1();
colors[16] = theme.getTitleBar2();
for (int i=0; i<labels.length; i++) {
Color c = colors[i];
labels[i].setBackground(new Color(c.r, c.g, c.b, c.a));
methodNames[i].setBackground(theme.getBackground());
methodNames[i].setForeground(theme.getForeground());
}
nameLabel.setForeground(theme.getForeground());
nameLabel.setText(theme.getName());
Sui.updateComponentTreeTheme(display);
}
public void updateButtons() {
left.setEnabled(currentIndex!=0 && !themes.isEmpty());
right.setEnabled(currentIndex<themes.size()-1 && !themes.isEmpty());
}
public void update(GameContainer container, int delta) throws SlickException {
display.update(container, delta);
if (container.getInput().isKeyPressed(Input.KEY_ESCAPE))
container.exit();
}
public void render(GameContainer container, Graphics g) throws SlickException {
g.setBackground(Color.lightGray);
display.render(container, g);
}
}
/* CODE
import mdes.slick.sui.skin.ColorUIResource;
import mdes.slick.sui.theme.Theme;
import org.newdawn.slick.Color;
private Color activeTitleBar1 =
private Color activeTitleBar2 =
private Color background =
private Color disabledMask =
private Color foreground =
private Color primary1 =
private Color primary2 =
private Color primary3 =
private Color primaryBorder1 =
private Color primaryBorder2 =
private Color secondary1 =
private Color secondary2 =
private Color secondary3 =
private Color secondaryBorder1 =
private Color secondaryBorder2 =
private Color titleBar1 =
private Color titleBar2 =
public String getName() { return ; }
public Color getActiveTitleBar1() { return activeTitleBar1; }
public Color getActiveTitleBar2() { return activeTitleBar2; }
public Color getBackground() { return background; }
public Color getDisabledMask() { return disabledMask; }
public Color getForeground() { return foreground; }
public Color getPrimary1() { return primary1; }
public Color getPrimary2() { return primary2; }
public Color getPrimary3() { return primary3; }
public Color getPrimaryBorder1() { return primaryBorder1; }
public Color getPrimaryBorder2() { return primaryBorder2; }
public Color getSecondary1() { return secondary1; }
public Color getSecondary2() { return secondary2; }
public Color getSecondary3() { return secondary3; }
public Color getSecondaryBorder1() { return secondaryBorder1; }
public Color getSecondaryBorder2() { return secondaryBorder2; }
public Color getTitleBar1() { return titleBar1; }
public Color getTitleBar2() { return titleBar2; }
/*TODO: fix overlap bug
Container panel = new Container();
final Button left = new Button("Previous");
left.pack();
panel.add(left);
final Button right = new Button("Next");
right.pack();
right.setX(left.getX()+5);
right.setHeight(left.getHeight());
panel.add(right);
panel.setSize(right.getX()+right.getWidth(), left.getHeight());
panel.setLocationRelativeTo(display);
panel.setY(starty-panel.getHeight()-5);
display.add(panel);*/
| bsd-3-clause |
Team3482/Code-2015 | src/org/usfirst/frc3482/robot/commands/Autonomous.java | 1819 | package org.usfirst.frc3482.robot.commands;
import org.usfirst.frc3482.robot.Robot;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.command.CommandGroup;
/**
*
*/
public class Autonomous extends CommandGroup {
// 1: pull back two center trash cans
// 2: push forward one set of tote/trash can
// 3: push forward three sets of tote/trash can
int mode = 1;
public Autonomous() {
// Add Commands here:
// e.g. addSequential(new Command1());
// addSequential(new Command2());
// these will run in order.
// To run multiple commands at the same time,
// use addParallel()
// e.g. addParallel(new Command1());
// addSequential(new Command2());
// Command1 and Command2 will run in parallel.
// A command group will require all of the subsystems that each member
// would require.
// e.g. if Command1 requires chassis, and Command2 requires arm,
// a CommandGroup containing them would require both the chassis and the
// arm.
requires(Robot.chassis);
if(mode == 1) {
addSequential(new ManualRaiseArms(), .5);
addSequential(new Move(.5, 0, 0, .25), .25);
} /*else if(mode == 2) {
addSequential(new ArmsToBottom());
addSequential(new Move(0, .8, 0, .5), .5);
} else if(mode == 3) {
addSequential(new ArmsToBottom());
addSequential(new Move(.5, 0, 0, .25), .25);
addSequential(new Move(-.5, 0, 0, .25), .25);
addSequential(new Move(0, 0.5, 0, .5), .5);
addSequential(new Move(.5, 0, 0, .25), .25);
addSequential(new Move(-.5, 0, 0, .25), .25);
addSequential(new Move(0, 0.5, 0, .5), .5);
addSequential(new Move(.5, 0, 0, .25), .25);
}*/
}
}
| bsd-3-clause |
RealityShard/ProductionEnvironment | src/main/java/com/realityshard/host/dynamicloading/ClassLoaderFactory.java | 3249 | /**
* For copyright information see the LICENSE document.
*/
package com.realityshard.host.dynamicloading;
import java.io.File;
import java.io.FileFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A class loader that is used to load the shardlet
* classes from a GameApp directory.
* Build upon an URL classloader
*
* TODO: Include resources, clean up, review
*
* @author _rusty
*/
public final class ClassLoaderFactory
{
private final static Logger LOGGER = LoggerFactory.getLogger(ClassLoaderFactory.class);
/**
* Creates a new protocol ClassLoader
*
* @param path The path to the PROT-INF folder.
* @param parent The parent class loader
* (will be used for class lookup first)
* @return The newly created class loader
*/
public static ClassLoader produceClassLoaderWithLibs(File path, ClassLoader parent)
{
// a "PROT-INF" or "GAME-INF" protocol/gameapp folder should include
// /lib/*.jar - meaning any external 3rd party jar goes here
// /classes/ - meaning any protocol filter stuff goes there
// /ressource/ - TODO: all resources go here
// so what we do is adding these dirs to the URL class loader
// this list will contain the URLS later on
// (those that we need to give to the URL class loader
List<URL> urls = new ArrayList<>();
// search for all the libs
// because the protocol filter expects them to be there
// (we need to include their paths directly within the URLClassLoader,
// as it can load the classes implicitly then)
File lib = new File(path, "lib");
try
{
if (lib.exists())
{
// quick and dirty: get all jars from there (not including sub directories)
File[] libs = lib.listFiles(new FileFilter()
{
@Override
public boolean accept(File file)
{
return file.getName().toLowerCase().endsWith(".jar");
}
});
// add the found jars to the URL's
for (File file : libs)
{
urls.add(file.toURI().toURL());
}
}
// create the URL that contains the "classes" folder
// we must assume that classes from here are never packed into jars
// else i guess they couldnt be loaded that way
urls.add(new File(path, "classes").toURI().toURL());
}
catch (MalformedURLException ex)
{
LOGGER.error("Folder could not be converted to URL.", ex);
}
// TODO: Check if this is the right way to do it:
return new URLClassLoader(urls.toArray(new URL[0]), parent);
}
}
| bsd-3-clause |
robertsmieja/clarity | src/main/java/skadistats/clarity/decoder/unpacker/IntVarUnsignedUnpacker.java | 272 | package skadistats.clarity.decoder.unpacker;
import skadistats.clarity.decoder.bitstream.BitStream;
public class IntVarUnsignedUnpacker implements Unpacker<Integer> {
@Override
public Integer unpack(BitStream bs) {
return bs.readVarUInt();
}
}
| bsd-3-clause |
NCIP/stats-analysis | src/gov/nih/nci/caintegrator/dto/de/ClusterTypeDE.java | 1833 | /*L
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/stats-analysis/LICENSE.txt for details.
*/
/**
*
*/
package gov.nih.nci.caintegrator.dto.de;
import gov.nih.nci.caintegrator.enumeration.ClusterByType;
/**
* @author sahnih
*
*/
/**
*
*
*/
public class ClusterTypeDE extends DomainElement {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @param value
*/
public ClusterTypeDE(ClusterByType clusterByType) {
super(clusterByType);
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see gov.nih.nci.caintegrator.dto.de.DomainElement#setValue(java.lang.Object)
*/
public void setValue(Object obj) throws Exception {
if (!(obj instanceof ClusterByType))
throw new Exception(
"Could not set the value. Parameter is of invalid data type: "
+ obj);
setValueObject((ClusterByType) obj);
}
/**
* Returns the ClusterByType for this ClusterTypeDE obect.
*
* @return the ClusterByType for this <code>ClusterTypeDE</code> object
*/
public ClusterByType getValueObject() {
return (ClusterByType) getValue();
}
/**
* Sets the clusterByType for this <code>ClusterTypeDE</code> object
*
* @param clusterByType
* the clusterByType
*/
public void setValueObject(ClusterByType clusterByType) {
if (clusterByType != null) {
value = clusterByType;
}
}
/**L
* Overrides the protected Object.clone() method exposing it as public.
* It performs a 2 tier copy, that is, it does a memcopy of the instance
* and then sets all the non-primitive data fields to clones of themselves.
*
* @return -A minimum 2 deep copy of this object.
*/
public Object clone() {
ClusterTypeDE myClone = (ClusterTypeDE) super.clone();
return myClone;
}
}
| bsd-3-clause |
mabrosim/ShoppingList | app/src/main/java/fi/mabrosim/shoppinglist/utils/Prefs.java | 1058 | package fi.mabrosim.shoppinglist.utils;
import android.content.Context;
import android.content.SharedPreferences;
public final class Prefs {
private static final String PREFS_NAME = "fi.mabrosim.shoppinglist.prefs";
private static final String PREF_READY = "READY";
private Prefs() {
}
public static boolean isReady(Context context) {
return getBoolean(context);
}
public static void setReady(Context context) {
putBoolean(context);
}
private static SharedPreferences sharedPreferences(Context context) {
return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
private static void putBoolean(Context context) {
SharedPreferences.Editor sharedPrefEditor = sharedPreferences(context).edit();
sharedPrefEditor.putBoolean(Prefs.PREF_READY, true);
sharedPrefEditor.apply();
}
private static boolean getBoolean(Context context) {
return sharedPreferences(context).getBoolean(Prefs.PREF_READY, false);
}
}
| bsd-3-clause |
NCIP/cagrid-core | integration-tests/projects/fqpTests/src/org/cagrid/fqp/test/local/secure/SecureLocalFQPSystemTests.java | 3289 | /**
*============================================================================
* Copyright The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC, and
* Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-core/LICENSE.txt for details.
*============================================================================
**/
package org.cagrid.fqp.test.local.secure;
import gov.nih.nci.cagrid.fqp.processor.FederatedQueryEngine;
import gov.nih.nci.cagrid.testing.system.deployment.ServiceContainer;
import gov.nih.nci.cagrid.testing.system.deployment.steps.DestroyContainerStep;
import gov.nih.nci.cagrid.testing.system.deployment.steps.StopContainerStep;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.fqp.test.common.DataServiceDeploymentStory;
import org.cagrid.fqp.test.common.FederatedQueryProcessorHelper;
import org.cagrid.fqp.test.common.QueryStory;
import org.junit.After;
import org.junit.Test;
/**
* SecureLocalFQPSystemTests
* Runs tests against the local Federated Query Engine using secure data services
* and delegated credentials
*
* @author David
*/
public class SecureLocalFQPSystemTests {
private static Log logger = LogFactory.getLog(SecureLocalFQPSystemTests.class);
private DataServiceDeploymentStory[] dataServiceDeployments;
@Test
public void secureLocalFQPSystemTests() throws Throwable {
// deploy two example SDK data services with security enabled
// which pull from slightly different data
DataServiceDeploymentStory exampleService1Deployment =
new DataServiceDeploymentStory(new File("resources/services/ExampleSdkService1.zip"), true, false);
DataServiceDeploymentStory exampleService2Deployment =
new DataServiceDeploymentStory(new File("resources/services/ExampleSdkService2.zip"), true, false);
// sources of data service containers. This allows stories to grab
// service containers after they've been created in the order of execution
dataServiceDeployments = new DataServiceDeploymentStory[] {
exampleService1Deployment, exampleService2Deployment
};
exampleService1Deployment.runBare();
exampleService2Deployment.runBare();
FederatedQueryEngine fqpEngine = new FederatedQueryEngine(null, null);
FederatedQueryProcessorHelper fqpHelper = new FederatedQueryProcessorHelper(fqpEngine);
QueryStory queryStory = new QueryStory(dataServiceDeployments, fqpHelper);
queryStory.runBare();
}
@After
public void cleanUp() {
logger.debug("Cleaning Up Secure Local FQP Tests");
for (DataServiceDeploymentStory deployment : dataServiceDeployments) {
ServiceContainer container = deployment.getServiceContainer();
try {
new StopContainerStep(container).runStep();
new DestroyContainerStep(container).runStep();
} catch (Throwable ex) {
ex.printStackTrace();
}
}
}
}
| bsd-3-clause |
NCIP/cagrid | cagrid/Software/portal/cagrid-portal/authn-portlet/src/java/gov/nih/nci/cagrid/portal/authn/AuthnTimeoutException.java | 760 | /**
*
*/
package gov.nih.nci.cagrid.portal.authn;
/**
* @author <a href="mailto:joshua.phillips@semanticbits.com">Joshua Phillips</a>
*
*/
public class AuthnTimeoutException extends Exception {
/**
*
*/
public AuthnTimeoutException() {
// TODO Auto-generated constructor stub
}
/**
* @param message
*/
public AuthnTimeoutException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
/**
* @param cause
*/
public AuthnTimeoutException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
/**
* @param message
* @param cause
*/
public AuthnTimeoutException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
}
| bsd-3-clause |
anirudhSK/chromium | chrome/android/java/src/org/chromium/chrome/browser/banners/SwipableOverlayView.java | 23765 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.banners;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import org.chromium.content.browser.ContentView;
import org.chromium.content_public.browser.GestureStateListener;
import org.chromium.ui.UiUtils;
/**
* View that appears on the screen as the user scrolls on the page and can be swiped away.
* Meant to be tacked onto the {@link org.chromium.content.browser.ContentView} layer and alerted
* when either the page scroll position or viewport size changes.
*
* GENERAL BEHAVIOR
* This View is brought onto the screen by sliding upwards from the bottom of the screen. Afterward
* the View slides onto and off of the screen vertically as the user scrolls upwards or
* downwards on the page. Users dismiss the View by swiping it away horizontally.
*
* VERTICAL SCROLL CALCULATIONS
* To determine how close the user is to the top of the page, the View must not only be informed of
* page scroll position changes, but also of changes in the viewport size (which happens as the
* omnibox appears and disappears, or as the page rotates e.g.). When the viewport size gradually
* shrinks, the user is most likely to be scrolling the page downwards while the omnibox comes back
* into view.
*
* When the user first begins scrolling the page, both the scroll position and the viewport size are
* summed and recorded together. This is because a pixel change in the viewport height is
* equivalent to a pixel change in the content's scroll offset:
* - As the user scrolls the page downward, either the viewport height will increase (as the omnibox
* is slid off of the screen) or the content scroll offset will increase.
* - As the user scrolls the page upward, either the viewport height will decrease (as the omnibox
* is brought back onto the screen) or the content scroll offset will decrease.
*
* As the scroll offset or the viewport height are updated via a scroll or fling, the difference
* from the initial value is used to determine the View's Y-translation. If a gesture is stopped,
* the View will be snapped back into the center of the screen or entirely off of the screen, based
* on how much of the View is visible, or where the user is currently located on the page.
*
* HORIZONTAL SCROLL CALCULATIONS
* Horizontal drags and swipes are used to dismiss the View. Translating the View far enough
* horizontally (with "enough" defined by the DISMISS_SWIPE_THRESHOLD AND DISMISS_FLING_THRESHOLD)
* triggers an animation that removes the View from the hierarchy. Failing to meet the threshold
* will result in the View being translated back to the center of the screen.
*
* Because the fling velocity handed in by Android is highly inaccurate and often indicates
* that a fling is moving in an opposite direction than expected, the scroll direction is tracked
* to determine which direction the user was dragging the View when the fling was initiated. When a
* fling is completed, the more forgiving FLING_THRESHOLD is used to determine how far a user must
* swipe to dismiss the View rather than try to use the fling velocity.
*/
public abstract class SwipableOverlayView extends FrameLayout {
private static final float ALPHA_THRESHOLD = 0.25f;
private static final float DISMISS_SWIPE_THRESHOLD = 0.75f;
private static final float FULL_THRESHOLD = 0.5f;
private static final float VERTICAL_FLING_SHOW_THRESHOLD = 0.2f;
private static final float VERTICAL_FLING_HIDE_THRESHOLD = 0.9f;
protected static final float ZERO_THRESHOLD = 0.001f;
private static final int GESTURE_NONE = 0;
private static final int GESTURE_SCROLLING = 1;
private static final int GESTURE_FLINGING = 2;
private static final int DRAGGED_LEFT = -1;
private static final int DRAGGED_CANCEL = 0;
private static final int DRAGGED_RIGHT = 1;
protected static final long MS_ANIMATION_DURATION = 250;
private static final long MS_DISMISS_FLING_THRESHOLD = MS_ANIMATION_DURATION * 2;
// Detects when the user is dragging the View.
private final GestureDetector mGestureDetector;
// Detects when the user is dragging the ContentView.
private final GestureStateListener mGestureStateListener;
// Monitors for animation completions and resets the state.
private final AnimatorListenerAdapter mAnimatorListenerAdapter;
// Interpolator used for the animation.
private final Interpolator mInterpolator;
// Tracks whether the user is scrolling or flinging.
private int mGestureState;
// Animation currently being used to translate the View.
private AnimatorSet mCurrentAnimation;
// Whether or not the current animation is adding or removing the View.
private boolean mIsAnimationAddingOrRemovingView;
// Direction the user is horizontally dragging.
private int mDragDirection;
// How quickly the user is horizontally dragging.
private float mDragXPerMs;
// WHen the user first started dragging.
private long mDragStartMs;
// Used to determine when the layout has changed and the Viewport must be updated.
private int mParentHeight;
// Location of the View when the current gesture was first started.
private float mInitialTranslationY;
// Offset from the top of the page when the current gesture was first started.
private int mInitialOffsetY;
// How tall the View is, including its margins.
private int mTotalHeight;
/**
* Creates a SwipableOverlayView.
* @param context Context for acquiring resources.
* @param attrs Attributes from the XML layout inflation.
*/
public SwipableOverlayView(Context context, AttributeSet attrs) {
super(context, attrs);
SimpleOnGestureListener gestureListener = createGestureListener();
mGestureDetector = new GestureDetector(context, gestureListener);
mGestureStateListener = createGestureStateListener();
mGestureState = GESTURE_NONE;
mAnimatorListenerAdapter = createAnimatorListenerAdapter();
mInterpolator = new DecelerateInterpolator(1.0f);
}
/**
* Adds this View to the given ContentView.
* @param layout Layout to add this View to.
*/
protected void addToView(ContentView contentView) {
contentView.addView(this, 0, createLayoutParams());
contentView.getContentViewCore().addGestureStateListener(mGestureStateListener);
// Listen for the layout to know when to animate the View coming onto the screen.
addOnLayoutChangeListener(createLayoutChangeListener());
}
/**
* Creates a set of LayoutParams that makes the View hug the bottom of the screen. Override it
* for other types of behavior.
* @return LayoutParams for use when adding the View to its parent.
*/
protected ViewGroup.MarginLayoutParams createLayoutParams() {
return new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
}
/**
* Removes the View from its parent.
*/
boolean removeFromParent() {
if (getParent() instanceof ContentView) {
ContentView parent = (ContentView) getParent();
parent.removeView(this);
parent.getContentViewCore().removeGestureStateListener(mGestureStateListener);
return true;
}
return false;
}
/**
* See {@link #android.view.ViewGroup.onLayout(boolean, int, int, int, int)}.
*/
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// Hide the View when the keyboard is showing.
boolean keyboardIsShowing = UiUtils.isKeyboardShowing(getContext(), this);
setVisibility(keyboardIsShowing ? INVISIBLE : VISIBLE);
// Update the viewport height when the parent View's height changes (e.g. after rotation).
int currentParentHeight = getParent() == null ? 0 : ((View) getParent()).getHeight();
if (mParentHeight != currentParentHeight) {
mParentHeight = currentParentHeight;
mGestureState = GESTURE_NONE;
if (mCurrentAnimation != null) mCurrentAnimation.end();
}
// Update the known effective height of the View.
mTotalHeight = getMeasuredHeight();
if (getLayoutParams() instanceof MarginLayoutParams) {
MarginLayoutParams params = (MarginLayoutParams) getLayoutParams();
mTotalHeight += params.topMargin + params.bottomMargin;
}
super.onLayout(changed, l, t, r, b);
}
/**
* See {@link #android.view.View.onTouchEvent(MotionEvent)}.
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mGestureDetector.onTouchEvent(event)) return true;
if (mCurrentAnimation != null) return true;
int action = event.getActionMasked();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
createHorizontalAnimation();
return true;
}
return false;
}
/**
* Creates a listener that monitors horizontal gestures performed on the View.
* @return The SimpleOnGestureListener that will monitor the View.
*/
private SimpleOnGestureListener createGestureListener() {
return new SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
mGestureState = GESTURE_SCROLLING;
mDragDirection = DRAGGED_CANCEL;
mDragXPerMs = 0;
mDragStartMs = e.getEventTime();
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distX, float distY) {
float distance = e2.getX() - e1.getX();
setTranslationX(getTranslationX() + distance);
setAlpha(calculateAnimationAlpha());
// Because the Android-calculated fling velocity is highly unreliable, we track what
// direction the user is dragging the View from here.
mDragDirection = distance < 0 ? DRAGGED_LEFT : DRAGGED_RIGHT;
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float vX, float vY) {
mGestureState = GESTURE_FLINGING;
// The direction and speed of the Android-given velocity feels completely disjoint
// from what the user actually perceives.
float androidXPerMs = Math.abs(vX) / 1000.0f;
// Track how quickly the user has translated the view to this point.
float dragXPerMs = Math.abs(getTranslationX()) / (e2.getEventTime() - mDragStartMs);
// Check if the velocity from the user's drag is higher; if so, use that one
// instead since that often feels more correct.
mDragXPerMs = mDragDirection * Math.max(androidXPerMs, dragXPerMs);
createHorizontalAnimation();
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
onViewClicked();
return true;
}
@Override
public void onShowPress(MotionEvent e) {
onViewPressed(e);
}
};
}
/**
* Creates a listener than monitors the ContentViewCore for scrolls and flings.
* The listener updates the location of this View to account for the user's gestures.
* @return GestureStateListener to send to the ContentViewCore.
*/
private GestureStateListener createGestureStateListener() {
return new GestureStateListener() {
@Override
public void onFlingStartGesture(int vx, int vy, int scrollOffsetY, int scrollExtentY) {
if (!cancelCurrentAnimation()) return;
if (mGestureState == GESTURE_NONE) beginGesture(scrollOffsetY, scrollExtentY);
mGestureState = GESTURE_FLINGING;
}
@Override
public void onFlingEndGesture(int scrollOffsetY, int scrollExtentY) {
if (mGestureState != GESTURE_FLINGING) return;
mGestureState = GESTURE_NONE;
int finalOffsetY = computeScrollDifference(scrollOffsetY, scrollExtentY);
boolean isScrollingDownward = finalOffsetY > 0;
boolean isVisibleInitially = mInitialTranslationY < mTotalHeight;
float percentageVisible = 1.0f - (getTranslationY() / mTotalHeight);
float visibilityThreshold = isVisibleInitially
? VERTICAL_FLING_HIDE_THRESHOLD : VERTICAL_FLING_SHOW_THRESHOLD;
boolean isVisibleEnough = percentageVisible > visibilityThreshold;
boolean show = !isScrollingDownward;
if (isVisibleInitially) {
// Check if the View was moving off-screen.
boolean isHiding = getTranslationY() > mInitialTranslationY;
show &= isVisibleEnough || !isHiding;
} else {
// When near the top of the page, there's not much room left to scroll.
boolean isNearTopOfPage = finalOffsetY < (mTotalHeight * FULL_THRESHOLD);
show &= isVisibleEnough || isNearTopOfPage;
}
createVerticalSnapAnimation(show);
}
@Override
public void onScrollStarted(int scrollOffsetY, int scrollExtentY) {
if (!cancelCurrentAnimation()) return;
if (mGestureState == GESTURE_NONE) beginGesture(scrollOffsetY, scrollExtentY);
mGestureState = GESTURE_SCROLLING;
}
@Override
public void onScrollEnded(int scrollOffsetY, int scrollExtentY) {
if (mGestureState != GESTURE_SCROLLING) return;
mGestureState = GESTURE_NONE;
int finalOffsetY = computeScrollDifference(scrollOffsetY, scrollExtentY);
boolean isNearTopOfPage = finalOffsetY < (mTotalHeight * FULL_THRESHOLD);
boolean isVisibleEnough = getTranslationY() < mTotalHeight * FULL_THRESHOLD;
createVerticalSnapAnimation(isNearTopOfPage || isVisibleEnough);
}
@Override
public void onScrollOffsetOrExtentChanged(int scrollOffsetY, int scrollExtentY) {
// This function is called for both fling and scrolls.
if (mGestureState == GESTURE_NONE || !cancelCurrentAnimation()) return;
float translation = mInitialTranslationY
+ computeScrollDifference(scrollOffsetY, scrollExtentY);
translation = Math.max(0.0f, Math.min(mTotalHeight, translation));
setTranslationY(translation);
}
};
}
/**
* Creates a listener that is used only to animate the View coming onto the screen.
* @return The SimpleOnGestureListener that will monitor the View.
*/
private View.OnLayoutChangeListener createLayoutChangeListener() {
return new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
removeOnLayoutChangeListener(this);
// Animate the View coming in from the bottom of the screen.
setTranslationY(mTotalHeight);
mIsAnimationAddingOrRemovingView = true;
createVerticalSnapAnimation(true);
mCurrentAnimation.start();
}
};
}
/**
* Create an animation that snaps the View into position vertically.
* @param visible If true, snaps the View to the bottom-center of the screen. If false,
* translates the View below the bottom-center of the screen so that it is
* effectively invisible.
*/
void createVerticalSnapAnimation(boolean visible) {
float translationY = visible ? 0.0f : mTotalHeight;
float yDifference = Math.abs(translationY - getTranslationY()) / mTotalHeight;
long duration = (long) (MS_ANIMATION_DURATION * yDifference);
createAnimation(1.0f, 0, translationY, duration, false);
}
/**
* Dismisses the View, animating it moving vertically off of the screen if needed.
*/
void dismiss() {
if (getParent() == null) return;
float translationY = mTotalHeight;
float yDifference = Math.abs(translationY - getTranslationY()) / mTotalHeight;
long duration = (long) (MS_ANIMATION_DURATION * yDifference);
createAnimation(1.0f, 0, translationY, duration, true);
}
/**
* Calculates how transparent the View should be.
*
* The transparency value is proportional to how far the View has been swiped away from the
* center of the screen. The {@link ALPHA_THRESHOLD} determines at what point the View should
* start fading away.
* @return The alpha value to use for the View.
*/
private float calculateAnimationAlpha() {
float percentageSwiped = Math.abs(getTranslationX() / getWidth());
float percentageAdjusted = Math.max(0.0f, percentageSwiped - ALPHA_THRESHOLD);
float alphaRange = 1.0f - ALPHA_THRESHOLD;
return 1.0f - percentageAdjusted / alphaRange;
}
private int computeScrollDifference(int scrollOffsetY, int scrollExtentY) {
return scrollOffsetY + scrollExtentY - mInitialOffsetY;
}
/**
* Horizontally slide the View either to the center of the screen or off of it for dismissal.
* If the animation translates the View off the screen, the View is removed from the hierarchy
* and marked as a manual removal.
*/
private void createHorizontalAnimation() {
long duration = MS_ANIMATION_DURATION;
// Determine where the View needs to move. Because of the unreliability of the fling
// velocity, we ignore it and instead rely on the direction the user was last dragging the
// View. Moreover, we lower the translation threshold for dismissal.
boolean isFlinging = mGestureState == GESTURE_FLINGING;
// If the user hasn't tried hard enough to dismiss the View, move it back to the center.
if (isFlinging) {
// Assuming a linear velocity, allow flinging the View away if it would fly off the
// screen in a reasonable time frame.
float remainingDifference = mDragDirection * getWidth() - getTranslationX();
float msRequired = Math.abs(remainingDifference / mDragXPerMs);
if (msRequired < MS_DISMISS_FLING_THRESHOLD) {
duration = (long) msRequired;
} else {
mDragDirection = DRAGGED_CANCEL;
}
} else {
// Check if the user has dragged the View far enough to be dismissed.
float dismissPercentage = DISMISS_SWIPE_THRESHOLD;
float dismissThreshold = getWidth() * dismissPercentage;
if (Math.abs(getTranslationX()) < dismissThreshold) mDragDirection = DRAGGED_CANCEL;
}
// Set up the animation parameters.
float finalAlpha = mDragDirection == DRAGGED_CANCEL ? 1.0f : 0.0f;
float finalX = mDragDirection * getWidth();
boolean isSwipedAway = mDragDirection != DRAGGED_CANCEL;
createAnimation(finalAlpha, finalX, getTranslationY(), duration, isSwipedAway);
}
/**
* Creates an animation that slides the View to the given location and visibility.
* @param alpha How opaque the View should be at the end.
* @param x X-coordinate of the final translation.
* @param y Y-coordinate of the final translation.
* @param duration How long the animation should run for.
* @param remove If true, remove the View from its parent ViewGroup.
*/
private void createAnimation(float alpha, float x, float y, long duration, boolean remove) {
Animator alphaAnimator =
ObjectAnimator.ofPropertyValuesHolder(this,
PropertyValuesHolder.ofFloat("alpha", getAlpha(), alpha));
Animator translationXAnimator =
ObjectAnimator.ofPropertyValuesHolder(this,
PropertyValuesHolder.ofFloat("translationX", getTranslationX(), x));
Animator translationYAnimator =
ObjectAnimator.ofPropertyValuesHolder(this,
PropertyValuesHolder.ofFloat("translationY", getTranslationY(), y));
mIsAnimationAddingOrRemovingView = remove;
mCurrentAnimation = new AnimatorSet();
mCurrentAnimation.setDuration(duration);
mCurrentAnimation.playTogether(alphaAnimator, translationXAnimator, translationYAnimator);
mCurrentAnimation.addListener(mAnimatorListenerAdapter);
mCurrentAnimation.setInterpolator(mInterpolator);
mCurrentAnimation.start();
}
/**
* Creates an AnimatorListenerAdapter that cleans up after an animation is completed.
* @return {@link AnimatorListenerAdapter} to use for animations.
*/
private AnimatorListenerAdapter createAnimatorListenerAdapter() {
return new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mGestureState = GESTURE_NONE;
mCurrentAnimation = null;
if (mIsAnimationAddingOrRemovingView) removeFromParent();
mIsAnimationAddingOrRemovingView = false;
}
};
}
/**
* Records the conditions of the page when a gesture is initiated.
*/
private void beginGesture(int scrollOffsetY, int scrollExtentY) {
mInitialTranslationY = getTranslationY();
boolean isInitiallyVisible = mInitialTranslationY < mTotalHeight;
int startingY = isInitiallyVisible ? scrollOffsetY : Math.min(scrollOffsetY, mTotalHeight);
mInitialOffsetY = startingY + scrollExtentY;
}
/**
* Cancels the current animation, if the View isn't being dismissed.
* @return True if the animation was canceled or wasn't running, false otherwise.
*/
private boolean cancelCurrentAnimation() {
if (mIsAnimationAddingOrRemovingView) return false;
if (mCurrentAnimation != null) mCurrentAnimation.cancel();
return true;
}
/**
* Called when the View has been clicked.
*/
protected abstract void onViewClicked();
/**
* Called when the View needs to show that it's been pressed.
*/
protected abstract void onViewPressed(MotionEvent event);
}
| bsd-3-clause |
davidpicard/jkernelmachines | src/test/java/net/jkernelmachines/test/classifier/TSMKLTest.java | 3295 | /*******************************************************************************
* Copyright (c) 2016, David Picard.
* 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.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 net.jkernelmachines.test.classifier;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import net.jkernelmachines.classifier.TSMKL;
import net.jkernelmachines.kernel.typed.DoubleGaussL2;
import net.jkernelmachines.type.TrainingSample;
import net.jkernelmachines.util.generators.GaussianGenerator;
import org.junit.Before;
import org.junit.Test;
/**
* @author picard
*
*/
public class TSMKLTest {
List<TrainingSample<double[]>> train;
TSMKL<double[]> svm;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
GaussianGenerator g = new GaussianGenerator(10, 5.0f, 1.0);
train = g.generateList(10);
svm = new TSMKL<double[]>();
svm.addKernel(new DoubleGaussL2());
}
/**
* Test method for {@link net.jkernelmachines.classifier.TSMKL#train(java.util.List)}.
*/
@Test
public final void testTrainListOfTrainingSampleOfT() {
svm.train(train);
for(TrainingSample<double[]> t : train) {
double v = t.label * svm.valueOf(t.sample);
assertTrue(v > 0);
}
}
/**
* Test method for {@link net.jkernelmachines.classifier.TSMKL#addKernel(net.jkernelmachines.kernel.Kernel)}.
*/
@Test
public final void testAddKernel() {
DoubleGaussL2 k = new DoubleGaussL2(1.0);
svm.addKernel(k);
assertTrue(svm.getKernels().contains(k));
}
/**
* Test method for {@link net.jkernelmachines.classifier.TSMKL#setC(double)}.
*/
@Test
public final void testSetC() {
svm.setC(10.0);
assertEquals(10.0, svm.getC(), 1e-15);
}
}
| bsd-3-clause |
muloem/xins | src/java-common/org/xins/common/spec/AttributeComboSpec.java | 1283 | /*
* $Id$
*
* Copyright 2003-2008 Online Breedband B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.common.spec;
import java.util.Map;
/**
* Specification of a attribute combo.
*
* @version $Revision$ $Date$
* @author <a href="mailto:anthony.goubard@japplis.com">Anthony Goubard</a>
*
* @since XINS 1.4.0
*/
public final class AttributeComboSpec extends ComboSpec {
/**
* Creates a new <code>AttributeComboSpec</code>.
*
* @param type
* the type of the attribute-combo, cannot be <code>null</code>.
*
* @param attributes
* the attributes this attribute-combo refers to, cannot be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>type == null || attributes == null</code>.
*/
AttributeComboSpec(String type, Map attributes) throws IllegalArgumentException {
super(type, attributes);
}
/**
* Gets the attributes defined in the attribute combo.
* The key is the name of the attribute, the value is the {@link ParameterSpec} object.
*
* @return
* The specification of the attributes defined in the attribute combo, never <code>null</code>.
*/
public Map getAttributes() {
return getReferences();
}
}
| bsd-3-clause |
bsaylor/jbehave-core | jbehave-core/src/test/java/org/jbehave/core/steps/ChainedRowBehaviour.java | 1035 | package org.jbehave.core.steps;
import java.util.HashMap;
import java.util.Map;
import org.jbehave.core.model.TableTransformers;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class ChainedRowBehaviour {
@Test
public void shouldChainRowValuesWithoutOverwritingAlreadyExisting() throws Exception {
Map<String,String> map1 = new HashMap<String, String>();
map1.put("one", "11");
Map<String,String> map2 = new HashMap<String, String>();
map2.put("one", "21");
map2.put("two", "22");
ParameterConverters parameterConverters = new ParameterConverters(new TableTransformers());
Map<String,String> chainedValues = new ChainedRow(new ConvertedParameters(map1, parameterConverters),
new ConvertedParameters(map2, parameterConverters)).values();
assertThat(chainedValues.get("one"), equalTo("11"));
assertThat(chainedValues.get("two"), equalTo("22"));
}
}
| bsd-3-clause |
PeterMitrano/EKIPS_code | src/org/usfirst/frc293/EKIPS/commands/RaiseWrist.java | 235 | package org.usfirst.frc293.EKIPS.commands;
import edu.wpi.first.wpilibj.command.CommandGroup;
public class RaiseWrist extends CommandGroup {
public RaiseWrist() {
addParallel(new SetWristSetpoint(-2));
}
}
| bsd-3-clause |
ihr/esapi-c14n | src/main/java/org/owasp/esapi/c14n/decoder/HTMLEntityDecoder.java | 5658 | /**
* OWASP Enterprise Security API (ESAPI)
*
* This file is part of the Open Web Application Security Project (OWASP)
* Enterprise Security API (ESAPI) project. For details, please see
* <a href="http://www.owasp.org/index.php/ESAPI">http://www.owasp.org/index.php/ESAPI</a>.
*
* Copyright (c) 2007 - The OWASP Foundation
*
* The ESAPI is published by OWASP under the BSD license. You should read and accept the
* LICENSE before you use, modify, and/or redistribute this software.
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created 2007
*/
package org.owasp.esapi.c14n.decoder;
import org.owasp.esapi.c14n.codecs.PushbackString;
import static org.owasp.esapi.c14n.util.HtmlEntityMap.getNamedEntity;
/**
* Implementation of the Codec interface for HTML entity encoding.
*
* @author Jeff Williams (jeff.williams .at. aspectsecurity.com) <a
* href="http://www.aspectsecurity.com">Aspect Security</a>
* @since June 1, 2007
*/
public class HtmlEntityDecoder implements Decoder {
/**
*
*/
public HtmlEntityDecoder() {
}
/**
* {@inheritDoc}
* <p/>
* Returns the decoded version of the character starting at index, or
* null if no decoding is possible.
* <p/>
* Formats all are legal both with and without semi-colon, upper/lower case:
* &#dddd;
* &#xhhhh;
* &name;
*/
public Character decodeCharacter(PushbackString input) {
input.mark();
Character first = input.next();
if (first == null) {
input.reset();
return null;
}
// if this is not an encoded character, return null
if (first != '&') {
input.reset();
return null;
}
// test for numeric encodings
Character second = input.next();
if (second == null) {
input.reset();
return null;
}
if (second == '#') {
// handle numbers
Character c = getNumericEntity(input);
if (c != null) return c;
} else if (Character.isLetter(second.charValue())) {
// handle entities
input.pushback(second);
Character c = getNamedEntity(input);
if (c != null) return c;
}
input.reset();
return null;
}
/**
* getNumericEntry checks input to see if it is a numeric entity
*
* @param input The input to test for being a numeric entity
* @return null if input is null, the character of input after decoding
*/
private Character getNumericEntity(PushbackString input) {
Character first = input.peek();
if (first == null) return null;
if (first == 'x' || first == 'X') {
input.next();
return parseHex(input);
}
return parseNumber(input);
}
/**
* Parse a decimal number, such as those from JavaScript's String.fromCharCode(value)
*
* @param input decimal encoded string, such as 65
* @return character representation of this decimal value, e.g. A
* @throws NumberFormatException
*/
private Character parseNumber(PushbackString input) {
StringBuilder sb = new StringBuilder();
while (input.hasNext()) {
Character c = input.peek();
// if character is a digit then add it on and keep going
if (Character.isDigit(c.charValue())) {
sb.append(c);
input.next();
// if character is a semi-colon, eat it and quit
} else if (c == ';') {
input.next();
break;
// otherwise just quit
} else {
break;
}
}
try {
int i = Integer.parseInt(sb.toString());
if (Character.isValidCodePoint(i)) {
return (char) i;
}
} catch (NumberFormatException e) {
// throw an exception for malformed entity?
}
return null;
}
/**
* Parse a hex encoded entity
*
* @param input Hex encoded input (such as 437ae;)
* @return A single character from the string
* @throws NumberFormatException
*/
private Character parseHex(PushbackString input) {
StringBuilder sb = new StringBuilder();
while (input.hasNext()) {
Character c = input.peek();
// if character is a hex digit then add it on and keep going
if ("0123456789ABCDEFabcdef".indexOf(c) != -1) {
sb.append(c);
input.next();
// if character is a semi-colon, eat it and quit
} else if (c == ';') {
input.next();
break;
// otherwise just quit
} else {
break;
}
}
try {
int i = Integer.parseInt(sb.toString(), 16);
if (Character.isValidCodePoint(i)) {
return (char) i;
}
} catch (NumberFormatException e) {
// throw an exception for malformed entity?
}
return null;
}
public String decode(String input) {
StringBuilder sb = new StringBuilder();
PushbackString pbs = new PushbackString(input);
while (pbs.hasNext()) {
Character c = decodeCharacter(pbs);
if (c != null) {
sb.append(c);
} else {
sb.append(pbs.next());
}
}
return sb.toString();
}
}
| bsd-3-clause |
vtkio/vtk | src/test/java/vtk/web/display/collection/event/EventListingHelperTest.java | 5212 | /* Copyright (c) 2012, University of Oslo, Norway
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the University of Oslo nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package vtk.web.display.collection.event;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.Before;
import org.junit.Test;
import vtk.testing.mocktypes.MockResourceTypeTree;
import vtk.web.display.collection.event.EventListingHelper.SpecificDateSearchType;
public class EventListingHelperTest {
private EventListingHelper eventListingHelper;
private Mockery context = new JUnit4Mockery();
private HttpServletRequest mockRequest;
@Before
public void init() throws Exception {
this.eventListingHelper = new EventListingHelper();
this.eventListingHelper.setStartPropDefPointer("resource:start-date");
this.eventListingHelper.setEndPropDefPointer("resource:end-date");
this.eventListingHelper.setResourceTypeTree(new MockResourceTypeTree());
this.mockRequest = this.context.mock(HttpServletRequest.class);
}
@Test
public void testGetSpecificDateSearchType() {
this.testGetSpecificDateSearchType("2012-09-15", SpecificDateSearchType.Day);
this.testGetSpecificDateSearchType("2012-09", SpecificDateSearchType.Month);
this.testGetSpecificDateSearchType("2012", SpecificDateSearchType.Year);
}
@Test
public void testGetSpecificDateSearchTypeInvalid() {
context.checking(new Expectations() {
{
one(mockRequest).getParameter(EventListingHelper.REQUEST_PARAMETER_DATE);
will(returnValue("invalid request date string"));
}
});
SpecificDateSearchType searchType = this.eventListingHelper.getSpecificDateSearchType(this.mockRequest);
assertNull("Expected result is not null", searchType);
}
private void testGetSpecificDateSearchType(final String requestDateString, final SpecificDateSearchType expected) {
context.checking(new Expectations() {
{
one(mockRequest).getParameter(EventListingHelper.REQUEST_PARAMETER_DATE);
will(returnValue(requestDateString));
}
});
SpecificDateSearchType searchType = this.eventListingHelper.getSpecificDateSearchType(this.mockRequest);
assertNotNull("Expected result is null", searchType);
assertEquals("Wrong search type", expected, searchType);
}
@Test
public void testGetSpecificSearchDate() {
this.testGetSpecificSearchDate("2012-09-15", "yyyy-MM-dd");
this.testGetSpecificSearchDate("2012-09", "yyyy-MM");
this.testGetSpecificSearchDate("2012", "yyyy");
}
private void testGetSpecificSearchDate(final String requestDateString, final String pattern) {
DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
long millis = dtf.parseMillis(requestDateString);
Date expected = new Date(millis);
context.checking(new Expectations() {
{
one(mockRequest).getParameter(EventListingHelper.REQUEST_PARAMETER_DATE);
will(returnValue(requestDateString));
}
});
Date date = this.eventListingHelper.getSpecificSearchDate(this.mockRequest);
assertNotNull("Expected result is null", date);
assertEquals("Wrong date", expected, date);
}
}
| bsd-3-clause |
ddamiani/cosmic-sim | java/src/main/java/com/ddamiani/cosmicsim/SimulationMain.java | 6209 | package com.ddamiani.cosmicsim;
import com.ddamiani.cosmicsim.particle.Particle;
import com.ddamiani.cosmicsim.particle.Photon;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import java.io.*;
import java.util.*;
/**
* The basic command line interface to run the Java version of the cosmic ray sim
*/
public final class SimulationMain {
/**
* Simple inner class for aggregating the results of multiple simulation runs.
*/
protected static final class Aggregator {
private int mStep;
private double mMean;
private double mSumSquare;
public Aggregator() {
mStep = 0;
mMean = 0.0;
mSumSquare = 0.0;
}
public final void addStep(double stepValue) {
mStep += 1;
double diff = stepValue - mMean;
mMean += diff / mStep;
mSumSquare += diff * (stepValue - mMean);
}
public final int getCounts() {
return mStep;
}
public final double getMean() {
return mMean;
}
public final double getStdError() {
return StrictMath.sqrt(mSumSquare / ((mStep - 1) * mStep));
}
}
private static int printFrequency = 1000;
private static void printOutputLine(String header, double mean, double error) {
System.out.format(" %-8s %12.3f \u00B1 %.3f\n", header, mean, error);
}
private static void runSimulations(int count, double energy, double position) {
System.out.println(String.format("Running the simulation %d times with an initial photon energy of %.0f GeV", count, energy / 1000.));
System.out.println(String.format("The shower will be sampled at %.2f radiation lengths from the top of the atmosphere.", position));
final Aggregator totalAggregator = new Aggregator();
final Aggregator neutralAggregator = new Aggregator();
final Aggregator chargeAggregator = new Aggregator();
final ResultStore results = new ResultStore(position);
final String progressStatus = "Finished processing %d of %d steps so far.\n";
for (int i = 0; i < count; i++) {
final Particle initial = new Photon(energy, 0.0, null, results);
initial.propagate();
totalAggregator.addStep(results.getTotalNumParticles());
neutralAggregator.addStep(results.getNumNeutralParticles());
chargeAggregator.addStep(results.getNumChargedParticles());
//Reset the result counters to zero
results.resetCounts();
if ((i + 1) % printFrequency == 0) {
System.out.format(progressStatus, i + 1, count);
}
}
System.out.format("Average numbers of particles sampled at %.2f radiation lengths:\n", position);
printOutputLine("Charged:", chargeAggregator.getMean(), chargeAggregator.getStdError());
printOutputLine("Neutral:", neutralAggregator.getMean(), neutralAggregator.getStdError());
printOutputLine("Total:", totalAggregator.getMean(), totalAggregator.getStdError());
}
/**
* Parses the cli commands.
*
* @param args Input parameters
*/
public static void cliParse(String... args) throws ArgumentParserException {
// Read in the program and version number - values populated by Maven
final String defaultVersionNum = "unknown";
final String defaultProgName = "cosmic-sim";
String versionNum;
String progName;
Properties config = new Properties();
try {
config.load(SimulationMain.class.getResourceAsStream("/version.properties"));
progName = config.getProperty("name", defaultProgName);
versionNum = config.getProperty("version", defaultVersionNum);
} catch (IOException | NullPointerException e) {
progName = defaultProgName;
versionNum = defaultVersionNum;
}
ArgumentParser parser = ArgumentParsers.newArgumentParser(progName)
.defaultHelp(true)
.version("${prog} " + versionNum)
.description("A quick and dirty simulation of a cosmic ray shower.");
parser.addArgument("energy")
.metavar("ENERGY")
.type(Double.class)
.help("the initial energy of the incoming photon in MeV");
parser.addArgument("position")
.metavar("POSITION")
.type(Double.class)
.help("the position in radiation lengths from the top of the atmosphere at which to sample the shower");
parser.addArgument("count")
.metavar("COUNT")
.type(Integer.class)
.help("the number of times to run the shower simulation");
parser.addArgument("-s", "--seed")
.metavar("SEED")
.type(Long.class)
.setDefault(System.currentTimeMillis())
.help("this option sets a specific seed for the simulation");
parser.addArgument("-p", "--print")
.dest("print_frequency")
.metavar("PRINT")
.type(Integer.class)
.setDefault(printFrequency)
.help("this option sets the frequency at which progress is reported");
parser.addArgument("--version")
.action(Arguments.version())
.help("show program's version number and exit");
Namespace ns = parser.parseArgs(args);
RandomNumberHelper.setSeed(ns.getLong("seed"));
printFrequency = ns.get("print_frequency");
runSimulations(ns.getInt("count"), ns.getDouble("energy"), ns.getDouble("position"));
}
public static void main(String[] args) {
try {
cliParse(args);
} catch (ArgumentParserException e) {
e.getParser().handleError(e);
System.exit(1);
}
}
}
| bsd-3-clause |
markles/GeoGit | src/cli/src/main/java/org/geogit/cli/BuiltinCommandsModule.java | 3694 | /* Copyright (c) 2013 OpenPlans. All rights reserved.
* This code is licensed under the BSD New License, available at the root
* application directory.
*/
package org.geogit.cli;
import org.geogit.cli.plumbing.Cat;
import org.geogit.cli.plumbing.DiffTree;
import org.geogit.cli.plumbing.Insert;
import org.geogit.cli.plumbing.LsTree;
import org.geogit.cli.plumbing.MergeBase;
import org.geogit.cli.plumbing.RebuildGraph;
import org.geogit.cli.plumbing.RevList;
import org.geogit.cli.plumbing.RevParse;
import org.geogit.cli.plumbing.ShowRef;
import org.geogit.cli.plumbing.WalkGraph;
import org.geogit.cli.porcelain.Add;
import org.geogit.cli.porcelain.Apply;
import org.geogit.cli.porcelain.Blame;
import org.geogit.cli.porcelain.Branch;
import org.geogit.cli.porcelain.Checkout;
import org.geogit.cli.porcelain.CherryPick;
import org.geogit.cli.porcelain.Clean;
import org.geogit.cli.porcelain.Clone;
import org.geogit.cli.porcelain.Commit;
import org.geogit.cli.porcelain.Config;
import org.geogit.cli.porcelain.Conflicts;
import org.geogit.cli.porcelain.Diff;
import org.geogit.cli.porcelain.Fetch;
import org.geogit.cli.porcelain.FormatPatch;
import org.geogit.cli.porcelain.Help;
import org.geogit.cli.porcelain.Init;
import org.geogit.cli.porcelain.Log;
import org.geogit.cli.porcelain.Ls;
import org.geogit.cli.porcelain.Merge;
import org.geogit.cli.porcelain.Pull;
import org.geogit.cli.porcelain.Push;
import org.geogit.cli.porcelain.Rebase;
import org.geogit.cli.porcelain.RemoteExtension;
import org.geogit.cli.porcelain.Remove;
import org.geogit.cli.porcelain.Reset;
import org.geogit.cli.porcelain.Revert;
import org.geogit.cli.porcelain.Show;
import org.geogit.cli.porcelain.Squash;
import org.geogit.cli.porcelain.Status;
import org.geogit.cli.porcelain.Tag;
import org.geogit.cli.porcelain.Version;
import com.google.inject.AbstractModule;
/**
* Guice module providing builtin commands for the {@link GeogitCLI CLI} app.
*
* @see Add
* @see Apply
* @see Branch
* @see Cat
* @see Checkout
* @see CherryPick
* @see Clean
* @see Commit
* @see Config
* @see Conflicts
* @see Diff
* @see FormatPatch
* @see Help
* @see Init
* @see Merge
* @see Log
* @see RemoteExtension
* @see Remove
* @see Status
* @see Rebase
* @see Reset
* @see Clone
* @see Push
* @see Pull
* @see Show
* @see Fetch
* @see Version
* @see RebuildGraph
*/
public class BuiltinCommandsModule extends AbstractModule implements CLIModule {
@Override
protected void configure() {
bind(RevParse.class);
bind(Add.class);
bind(Apply.class);
bind(Blame.class);
bind(Branch.class);
bind(Cat.class);
bind(Checkout.class);
bind(CherryPick.class);
bind(Clean.class);
bind(Commit.class);
bind(Config.class);
bind(Conflicts.class);
bind(Diff.class);
bind(DiffTree.class);
bind(FormatPatch.class);
bind(Help.class);
bind(Init.class);
bind(Insert.class);
bind(Log.class);
bind(Ls.class);
bind(LsTree.class);
bind(Merge.class);
bind(Log.class);
bind(MergeBase.class);
bind(RemoteExtension.class);
bind(Remove.class);
bind(Status.class);
bind(Rebase.class);
bind(Reset.class);
bind(Revert.class);
bind(RevList.class);
bind(Show.class);
bind(ShowRef.class);
bind(Clone.class);
bind(Fetch.class);
bind(Push.class);
bind(Pull.class);
bind(Squash.class);
bind(Tag.class);
bind(WalkGraph.class);
bind(Version.class);
bind(RebuildGraph.class);
}
}
| bsd-3-clause |
bponsler/rosjava_roslaunch | src/org/ros/rosjava/roslaunch/util/Util.java | 8472 | package org.ros.rosjava.roslaunch.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.ros.rosjava.roslaunch.logging.PrintLog;
import org.ros.rosjava.roslaunch.parsing.Attribute;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
/**
* The Util class
*
* This class is responsible for providing utility functions
* for performing various functions that are used throughout
* the project.
*/
public class Util
{
/** The current title of the terminal window. */
private static String TERMINAL_TITLE = "";
/**
* Expand any user home directory references contained within the
* given path string.
*
* @param path is the path to expand
* @return the path with any user home directory references expanded
*/
public static String expandUser(final String path)
{
String userHomeDir = System.getProperty("user.home");
return path.replaceFirst("~", userHomeDir);
}
/**
* Get the output of the execution of the given command.
*
* @param command is the command to run
* @return the output of the command
* @throws a RuntimeException if the command is invalid
*/
public static String getCommandOutput(final String command)
{
// Split the command into separate arguments for
// process builder, otherwise it will fail to run
// commands that have any arguments
String[] cmd = command.split(" ");
try
{
ProcessBuilder pb = new ProcessBuilder(cmd);
Process p = pb.start();
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String output = "";
String line = null;
while ((line = br.readLine()) != null) {
output += line + "\n";
}
// Wait for the process to finish
int r = p.waitFor();
if (r == 0) {
return output.trim();
}
}
catch (Exception e)
{
throw new RuntimeException(
"Invalid <param> tag: invalid command: " + e.getMessage());
}
return "";
}
/**
* Get the process ID for the current process.
*
* @return the process ID for the current process
*/
public static Integer getPid()
{
// Grab the name of the process, which will be something like:
// PID@hostname
String processName =
java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
// Split the process name and return the pid
return Integer.parseInt(processName.split("@")[0]);
}
/**
* Get the process ID for the given process.
*
* @param process is the given process
* @return the process ID for the given process
*/
public static int getPid(final Process process)
{
// Currently only support unix PIDs
return getUnixPid(process);
}
/**
* Get the process ID for a unix process.
*
* @param process is the process
* @return the process ID for unix processes, or -1 for other process types
*/
private static int getUnixPid(final Process process)
{
try
{
// The UNIXProcess class (which contains the pid field)
// is not accessible, therefore need to get the pid field
// value without casting
Class<?> classObj = process.getClass();
if (classObj.getName().equals("java.lang.UNIXProcess"))
{
// Grab the pid field from the object
Field pid = classObj.getDeclaredField("pid");
pid.setAccessible(true); // Need to access the pid value
// Return the pid for this process
return (int)pid.get(process);
}
}
catch (Exception e) {
// Ignore errors -- just means we weren't able
// to determine the pid
}
return -1; // No pid found
}
/**
* Write the process ID file.
*
* @param pidFilename is the file to write with the process ID
* @throws a RuntimeException if the file could not be created
*/
public static void writePidFile(final String pidFilename)
{
// Grab the PID for the current process
Integer pid = Util.getPid();
if (pid == null) {
throw new RuntimeException("Failed to get PID for process");
}
// Expand potential references to the user's home directory
String expanded = expandUser(pidFilename);
File path = new File(expanded);
String pidFilePath = path.getAbsolutePath();
// Attempt to write the PID file
FileOutputStream out = null;
try {
out = new FileOutputStream(pidFilePath);
String content = pid.toString();
out.write(content.getBytes());
}
catch (Exception e)
{
throw new RuntimeException(
"cannot create pid file: no such file or directory: " + pidFilename);
}
finally
{
try {
out.close();
}
catch (Exception ex) {
// Ignore errors when closing the files
}
}
}
/**
* Set the title of the terminal this program was executed in.
*
* @param title is the string to set the terminal title to
*/
public static void setTerminalTitle(final String title)
{
// Check if this is a supported OS
String os = System.getProperty("os.name");
if (os.contains("Linux"))
{
TERMINAL_TITLE = title;
System.out.print("\033]2;" + title + "\007");
}
}
/**
* Update the title of the terminal this program was executed in.
*
* @param title is the string to add to the current title
*/
public static void updateTerminalTitle(final String title)
{
setTerminalTitle(TERMINAL_TITLE + " " + title);
}
public static void checkForUnknownAttributes(
final File file,
final Element element,
final Attribute[] supportedAttributes)
{
// Create a List of attribute names
List<String> supportedAttributeNames = new ArrayList<String>();
for (Attribute attr : supportedAttributes) {
supportedAttributeNames.add(attr.val());
}
NamedNodeMap attributes = element.getAttributes();
for (int index = 0; index < attributes.getLength(); ++index)
{
Node node = attributes.item(index);
String attributeName = node.getNodeName();
if (!supportedAttributeNames.contains(attributeName))
{
String filename = file.getAbsolutePath();
PrintLog.error(
"WARNING: [" + filename + "] unknown <" + element.getTagName() +
"> attribute '" + attributeName + "'");
}
}
}
/**
* Get the current working directory.
*
* @return the path to the current working directory
*/
public static File getCurrentWorkingDirectory()
{
final String dir = System.getProperty("user.dir");
return new File(dir);
}
/**
* Get an estimate of the size of a file or folder.
*
* This function was found at:
*
* http://stackoverflow.com/questions/2149785/get-size-of-folder-or-file/19877372#19877372
*
* @param path the path to the file or folder
* @return the size in bytes
*/
public static long size (Path path)
{
final AtomicLong size = new AtomicLong(0);
try
{
Files.walkFileTree (path, new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
{
size.addAndGet(attrs.size());
return FileVisitResult.CONTINUE;
}
@Override public FileVisitResult visitFileFailed(Path file, IOException exc)
{
// Skip folders that can't be traversed
return FileVisitResult.CONTINUE;
}
@Override public FileVisitResult postVisitDirectory (Path dir, IOException exc)
{
// Ignore errors traversing a folder
return FileVisitResult.CONTINUE;
}
});
}
catch (IOException e) {
throw new AssertionError("Error while computing size: " + e.getMessage());
}
return size.get();
}
/**
* Convert a List of Strings into an array of string.
*
* @param list the List of String
* @return the array of Strings
*/
public static String[] listToArray(final List<String> list)
{
String[] array = new String[list.size()];
list.toArray(array);
return array;
}
}
| bsd-3-clause |
masih/nevis | src/main/java/org/derkani/nevis/element/HorizontalRule.java | 1702 | /*
* Copyright © 2014, Masih H. Derkani
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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.derkani.nevis.element;
/**
* @author Masih Hajiarab Derkani
*/
public class HorizontalRule extends Node {
}
| bsd-3-clause |
chrisichris/yetiscript | srclib/yeti/lang/IntNum.java | 6907 | // ex: se sts=4 sw=4 expandtab:
/**
* Yeti core library - Number interface.
*
* Copyright (c) 2007,2008 Madis Janson
* 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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 yeti.lang;
import java.math.BigInteger;
import java.math.BigDecimal;
public final class IntNum extends Num {
public static final IntNum __2 = new IntNum(-2);
public static final IntNum __1 = new IntNum(-1);
public static final IntNum _0 = new IntNum(0);
public static final IntNum _1 = new IntNum(1);
public static final IntNum _2 = new IntNum(2);
public static final IntNum _3 = new IntNum(3);
public static final IntNum _4 = new IntNum(4);
public static final IntNum _5 = new IntNum(5);
public static final IntNum _6 = new IntNum(6);
public static final IntNum _7 = new IntNum(7);
public static final IntNum _8 = new IntNum(8);
public static final IntNum _9 = new IntNum(9);
private final long v;
public IntNum(int num) {
v = num;
}
public IntNum(long num) {
v = num;
}
public Num add(Num num) {
return num.add(v);
}
public Num add(RatNum num) {
return num.add(v);
}
public Num add(long num) {
if (num > 0 ? num > 0x3fffffffffffffffL || v > 0x3fffffffffffffffL
: num < -0x3fffffffffffffffL || v < -0x3fffffffffffffffL) {
return new BigNum(BigInteger.valueOf(v).add(
BigInteger.valueOf(num)));
}
return new IntNum(v + num);
}
public Num add(BigInteger num) {
return new BigNum(BigInteger.valueOf(v).add(num));
}
public Num mul(Num num) {
return num.mul(v);
}
public Num mul(long num) {
if (num < -0x7fffffffL || num > 0x7fffffffL
|| v < -0x7fffffffL || v > 0x7fffffffL) {
return new BigNum(BigInteger.valueOf(v).multiply(
BigInteger.valueOf(num)));
}
return new IntNum(v * num);
}
public Num mul(BigInteger num) {
return new BigNum(BigInteger.valueOf(v).multiply(num));
}
public Num mul(RatNum num) {
return num.mul(v);
}
public Num div(Num num) {
return num.divFrom(v);
}
public Num div(long num) {
return RatNum.div(v, num);
}
public Num divFrom(long num) {
return RatNum.div(num, v);
}
public Num divFrom(RatNum num) {
return num.div(v);
}
public Num intDiv(Num num) {
return num.intDivFrom(v);
}
public Num intDiv(int num) {
return new IntNum(v / num);
}
public Num intDivFrom(long num) {
return new IntNum(num / v);
}
public Num intDivFrom(BigInteger num) {
return new BigNum(num.divide(BigInteger.valueOf(v)));
}
public Num rem(Num num) {
return num.remFrom(v);
}
public Num rem(int num) {
return new IntNum(v % num);
}
public Num remFrom(long num) {
return new IntNum(num % v);
}
public Num remFrom(BigInteger num) {
return new BigNum(num.remainder(BigInteger.valueOf(v)));
}
public Num sub(Num num) {
return num.subFrom(v);
}
public Num sub(long num) {
long n;
if (num < 0 ? num < -0x3fffffffffffffffL || v > 0x3fffffffffffffffL
: num > 0x3fffffffffffffffL || v < -0x3fffffffffffffffL) {
return new BigNum(BigInteger.valueOf(v).subtract(
BigInteger.valueOf(num)));
}
return new IntNum(v - num);
}
public Num subFrom(long num) {
if (num < 0 ? num < -0x3fffffffffffffffL || v > 0x3fffffffffffffffL
: num > 0x3fffffffffffffffL || v < -0x3fffffffffffffffL) {
return new BigNum(BigInteger.valueOf(num).subtract(
BigInteger.valueOf(v)));
}
return new IntNum(num - v);
}
public Num subFrom(RatNum num) {
return num.sub(v);
}
public Num subFrom(BigInteger num) {
return new BigNum(num.subtract(BigInteger.valueOf(v)));
}
public Num and(Num num) {
return new IntNum(num.longValue() & v);
}
public Num and(BigInteger num) {
return new IntNum(num.longValue() & v);
}
public Num or(Num num) {
return num.or(v);
}
public Num or(long num) {
return new IntNum(num | v);
}
public Num xor(Num num) {
return num.xor(v);
}
public Num xor(long num) {
return new IntNum(num ^ v);
}
public byte byteValue() {
return (byte) v;
}
public short shortValue() {
return (short) v;
}
public int intValue() {
return (int) v;
}
public long longValue() {
return v;
}
public float floatValue() {
return v;
}
public double doubleValue() {
return v;
}
public int compareTo(Object num) {
return ((Num) num).rCompare(v);
}
public int rCompare(long num) {
return v < num ? 1 : v > num ? -1 : 0;
}
public int rCompare(RatNum num) {
return -num.rCompare(v);
}
public int rCompare(BigInteger num) {
return num.compareTo(BigInteger.valueOf(v));
}
public BigDecimal toBigDecimal() {
return BigDecimal.valueOf(v);
}
public String toString() {
return Long.toString(v);
}
public int hashCode() {
return (int) (v ^ (v >>> 32));
}
}
| bsd-3-clause |
robototes/Team2412Library | src/com/shsrobotics/library/MaxBotixSonar.java | 1136 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.shsrobotics.library;
import edu.wpi.first.wpilibj.AnalogInput;
import edu.wpi.first.wpilibj.SensorBase;
/**
*
* @author RoboTotes Team 2412
*/
public class MaxBotixSonar extends SensorBase {
// supplied voltage = 4.978 ; 4.91 (b)
public static final double DEFAULT_SCALING_FACTOR = 4.978 / 512;
private double mVperInch = DEFAULT_SCALING_FACTOR;
private AnalogInput channel;
public MaxBotixSonar(int channel) {
this.channel = new AnalogInput(channel);
}
public double getDistanceInFeet() {
double measuredVoltage = channel.getVoltage();
double range = (measuredVoltage / mVperInch) / 12.0; // feet
return range;
}
public double getDistance() {
double measuredVoltage = channel.getVoltage();
double range = (measuredVoltage / mVperInch); // inches
return range;
}
public double getRawVoltage() {
return channel.getVoltage();
}
public void setSensitivity(double scale) {
mVperInch = scale;
}
public void free() {
channel.free();
}
}
| bsd-3-clause |
wshxj123/Android_detection | src/com/mobile/security/ui/SetWordsActivity.java | 2998 | package com.mobile.security.ui;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import com.mobile.security.R;
import com.mobile.security.utils.Logger;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class SetWordsActivity extends Activity {
// private MyDialog dialog;
private LinearLayout layout;
private TextView tView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setwords_dialog);
// dialog=new MyDialog(this);
tView = (TextView) findViewById(R.id.jiancewords);
layout = (LinearLayout) findViewById(R.id.setwords_layout);
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/Securitytest", "Setwords.txt");
String mwords = "";
try {
InputStreamReader read = null;
read = new InputStreamReader(new FileInputStream(file), "UTF-8");
BufferedReader reader = new BufferedReader(read);
String tempcontent = "";
while ((tempcontent = reader.readLine()) != null) {
mwords += tempcontent;
}
reader.close();
Logger.i("###mwords", mwords);
tView.setText(mwords);
} catch (Exception e) {
// TODO ×Ô¶¯Éú³ÉµÄ catch ¿é
e.printStackTrace();
}
layout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Ìáʾ£ºµã»÷´°¿ÚÍⲿ¹Ø±Õ´°¿Ú£¡",
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onTouchEvent(MotionEvent event) {
finish();
return true;
}
public void exitbutton0(View v) {
String temp = tView.getText().toString();
Logger.i("##textview dudaode", temp);
if (temp.equals("")) {
Toast.makeText(getApplicationContext(), "´íÎ󣺼ì²âÎÄ×Ö²»ÄÜΪ¿Õ£¡",
Toast.LENGTH_SHORT).show();
} else {
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/Securitytest", "Setwords.txt");
try {
FileOutputStream out = new FileOutputStream(file);
out.write(temp.getBytes());
out.flush();
out.close();
} catch (IOException e) {
// TODO ×Ô¶¯Éú³ÉµÄ catch ¿é
e.printStackTrace();
}
this.finish();
}
}
public void exitbutton1(View v) {
this.finish();
}
public void exitbutton2(View v) {
tView.setText("ÃØÃÜ;»úÃÜ;¾øÃÜ");
}
}
| bsd-3-clause |
FirebaseExtended/flutterfire | packages/firebase_app_check/firebase_app_check/android/src/main/java/io/flutter/plugins/firebase/appcheck/TokenChannelStreamHandler.java | 1008 | package io.flutter.plugins.firebase.appcheck;
import com.google.firebase.appcheck.FirebaseAppCheck;
import io.flutter.plugin.common.EventChannel;
import java.util.HashMap;
import java.util.Map;
public class TokenChannelStreamHandler implements EventChannel.StreamHandler {
private final FirebaseAppCheck firebaseAppCheck;
private FirebaseAppCheck.AppCheckListener listener;
public TokenChannelStreamHandler(FirebaseAppCheck firebaseAppCheck) {
this.firebaseAppCheck = firebaseAppCheck;
}
@Override
public void onListen(Object arguments, EventChannel.EventSink events) {
listener =
result -> {
Map<String, Object> event = new HashMap<>();
event.put("token", result.getToken());
events.success(event);
};
firebaseAppCheck.addAppCheckListener(listener);
}
@Override
public void onCancel(Object arguments) {
if (listener != null) {
firebaseAppCheck.removeAppCheckListener(listener);
listener = null;
}
}
}
| bsd-3-clause |
sgraham/nope | chrome/android/java/src/org/chromium/chrome/browser/util/IntentUtils.java | 1172 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.util;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import java.util.ArrayList;
import java.util.List;
/**
* Utilities dealing with extracting information from intents.
*/
public class IntentUtils {
/**
* Retrieves a list of components that would handle the given intent.
* @param context The application context.
* @param intent The intent which we are interested in.
* @return The list of component names.
*/
public static List<ComponentName> getIntentHandlers(Context context, Intent intent) {
List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent, 0);
List<ComponentName> nameList = new ArrayList<ComponentName>();
for (ResolveInfo r : list) {
nameList.add(new ComponentName(r.activityInfo.packageName, r.activityInfo.name));
}
return nameList;
}
}
| bsd-3-clause |
gabbasb/JDBC-XC | org/postgresql/jdbc2/AbstractJdbc2Connection.java | 42371 | /*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2011, PostgreSQL Global Development Group
*
*
*-------------------------------------------------------------------------
*/
package org.postgresql.jdbc2;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.*;
import org.postgresql.core.*;
import org.postgresql.Driver;
import org.postgresql.PGNotification;
import org.postgresql.fastpath.Fastpath;
import org.postgresql.largeobject.LargeObjectManager;
import org.postgresql.util.*;
import org.postgresql.util.HostSpec;
import org.postgresql.copy.*;
/**
* This class defines methods of the jdbc2 specification.
* The real Connection class (for jdbc2) is org.postgresql.jdbc2.Jdbc2Connection
*/
public abstract class AbstractJdbc2Connection implements BaseConnection
{
//
// Driver-wide connection ID counter, used for logging
//
private static int nextConnectionID = 1;
//
// Data initialized on construction:
//
// Per-connection logger
private final Logger logger;
/* URL we were created via */
private final String creatingURL;
private Throwable openStackTrace;
/* Actual network handler */
private final ProtocolConnection protoConnection;
/* Compatibility version */
private final String compatible;
/* Actual server version */
private final String dbVersionNumber;
/* Query that runs COMMIT */
private final Query commitQuery;
/* Query that runs ROLLBACK */
private final Query rollbackQuery;
private TypeInfo _typeCache;
// Default statement prepare threshold.
protected int prepareThreshold;
// Connection's autocommit state.
public boolean autoCommit = true;
// Connection's readonly state.
public boolean readOnly = false;
// Bind String to UNSPECIFIED or VARCHAR?
public final boolean bindStringAsVarchar;
// Current warnings; there might be more on protoConnection too.
public SQLWarning firstWarning = null;
/** Set of oids that use binary transfer when sending to server. */
private Set<Integer> useBinarySendForOids;
/** Set of oids that use binary transfer when receiving from server. */
private Set<Integer> useBinaryReceiveForOids;
public abstract DatabaseMetaData getMetaData() throws SQLException;
//
// Ctor.
//
protected AbstractJdbc2Connection(HostSpec[] hostSpecs, String user, String database, Properties info, String url) throws SQLException
{
this.creatingURL = url;
// Read loglevel arg and set the loglevel based on this value;
// In addition to setting the log level, enable output to
// standard out if no other printwriter is set
int logLevel = Driver.getLogLevel();
String connectionLogLevel = info.getProperty("loglevel");
if (connectionLogLevel != null) {
try {
logLevel = Integer.parseInt(connectionLogLevel);
} catch (Exception l_e) {
// XXX revisit
// invalid value for loglevel; ignore it
}
}
synchronized (AbstractJdbc2Connection.class) {
logger = new Logger(nextConnectionID++);
logger.setLogLevel(logLevel);
}
if (logLevel > 0)
enableDriverManagerLogging();
prepareThreshold = 5;
try
{
prepareThreshold = Integer.parseInt(info.getProperty("prepareThreshold", "5"));
if (prepareThreshold < 0)
prepareThreshold = 0;
}
catch (Exception e)
{
}
boolean binaryTransfer = true;
try
{
binaryTransfer = Boolean.valueOf(info.getProperty("binaryTransfer", "true")).booleanValue();
}
catch (Exception e)
{
}
//Print out the driver version number
if (logger.logInfo())
logger.info(Driver.getVersion());
// Now make the initial connection and set up local state
this.protoConnection = ConnectionFactory.openConnection(hostSpecs, user, database, info, logger);
this.dbVersionNumber = protoConnection.getServerVersion();
this.compatible = info.getProperty("compatible", Driver.MAJORVERSION + "." + Driver.MINORVERSION);
// Set read-only early if requested
if (Boolean.valueOf(info.getProperty("readOnly", "false")))
{
setReadOnly(true);
}
// Formats that currently have binary protocol support
Set<Integer> binaryOids = new HashSet<Integer>();
if (binaryTransfer && protoConnection.getProtocolVersion() >= 3) {
binaryOids.add(Oid.BYTEA);
binaryOids.add(Oid.INT2);
binaryOids.add(Oid.INT4);
binaryOids.add(Oid.INT8);
binaryOids.add(Oid.FLOAT4);
binaryOids.add(Oid.FLOAT8);
binaryOids.add(Oid.TIME);
binaryOids.add(Oid.DATE);
binaryOids.add(Oid.TIMETZ);
binaryOids.add(Oid.TIMESTAMP);
binaryOids.add(Oid.TIMESTAMPTZ);
binaryOids.add(Oid.INT2_ARRAY);
binaryOids.add(Oid.INT4_ARRAY);
binaryOids.add(Oid.INT8_ARRAY);
binaryOids.add(Oid.FLOAT4_ARRAY);
binaryOids.add(Oid.FLOAT8_ARRAY);
binaryOids.add(Oid.FLOAT8_ARRAY);
binaryOids.add(Oid.VARCHAR_ARRAY);
binaryOids.add(Oid.TEXT_ARRAY);
binaryOids.add(Oid.POINT);
binaryOids.add(Oid.BOX);
binaryOids.add(Oid.UUID);
}
// the pre 8.0 servers do not disclose their internal encoding for
// time fields so do not try to use them.
if (!haveMinimumCompatibleVersion("8.0")) {
binaryOids.remove(Oid.TIME);
binaryOids.remove(Oid.TIMETZ);
binaryOids.remove(Oid.TIMESTAMP);
binaryOids.remove(Oid.TIMESTAMPTZ);
}
// driver supports only null-compatible arrays
if (!haveMinimumCompatibleVersion("8.3")) {
binaryOids.remove(Oid.INT2_ARRAY);
binaryOids.remove(Oid.INT4_ARRAY);
binaryOids.remove(Oid.INT8_ARRAY);
binaryOids.remove(Oid.FLOAT4_ARRAY);
binaryOids.remove(Oid.FLOAT8_ARRAY);
binaryOids.remove(Oid.FLOAT8_ARRAY);
binaryOids.remove(Oid.VARCHAR_ARRAY);
binaryOids.remove(Oid.TEXT_ARRAY);
}
binaryOids.addAll(getOidSet(info.getProperty("binaryTransferEnable", "")));
binaryOids.removeAll(getOidSet(info.getProperty("binaryTransferDisable", "")));
// split for receive and send for better control
useBinarySendForOids = new HashSet<Integer>();
useBinarySendForOids.addAll(binaryOids);
useBinaryReceiveForOids = new HashSet<Integer>();
useBinaryReceiveForOids.addAll(binaryOids);
/*
* Does not pass unit tests because unit tests expect setDate to have
* millisecond accuracy whereas the binary transfer only supports
* date accuracy.
*/
useBinarySendForOids.remove(Oid.DATE);
protoConnection.setBinaryReceiveOids(useBinaryReceiveForOids);
if (logger.logDebug())
{
logger.debug(" compatible = " + compatible);
logger.debug(" loglevel = " + logLevel);
logger.debug(" prepare threshold = " + prepareThreshold);
logger.debug(" types using binary send = " + oidsToString(useBinarySendForOids));
logger.debug(" types using binary receive = " + oidsToString(useBinaryReceiveForOids));
logger.debug(" integer date/time = " + protoConnection.getIntegerDateTimes());
}
//
// String -> text or unknown?
//
String stringType = info.getProperty("stringtype");
if (stringType != null) {
if (stringType.equalsIgnoreCase("unspecified"))
bindStringAsVarchar = false;
else if (stringType.equalsIgnoreCase("varchar"))
bindStringAsVarchar = true;
else
throw new PSQLException(GT.tr("Unsupported value for stringtype parameter: {0}", stringType),
PSQLState.INVALID_PARAMETER_VALUE);
} else {
bindStringAsVarchar = haveMinimumCompatibleVersion("8.0");
}
// Initialize timestamp stuff
timestampUtils = new TimestampUtils(haveMinimumServerVersion("7.4"), haveMinimumServerVersion("8.2"),
!protoConnection.getIntegerDateTimes());
// Initialize common queries.
commitQuery = getQueryExecutor().createSimpleQuery("COMMIT");
rollbackQuery = getQueryExecutor().createSimpleQuery("ROLLBACK");
int unknownLength = Integer.MAX_VALUE;
String strLength = info.getProperty("unknownLength");
if (strLength != null) {
try {
unknownLength = Integer.parseInt(strLength);
} catch (NumberFormatException nfe) {
throw new PSQLException(GT.tr("unknownLength parameter value must be an integer"), PSQLState.INVALID_PARAMETER_VALUE, nfe);
}
}
// Initialize object handling
_typeCache = createTypeInfo(this, unknownLength);
initObjectTypes(info);
if (Boolean.valueOf(info.getProperty("logUnclosedConnections")).booleanValue()) {
openStackTrace = new Throwable("Connection was created at this point:");
enableDriverManagerLogging();
}
}
private Set<Integer> getOidSet(String oidList) throws PSQLException {
Set oids = new HashSet();
StringTokenizer tokenizer = new StringTokenizer(oidList, ",");
while (tokenizer.hasMoreTokens()) {
String oid = tokenizer.nextToken();
oids.add(Oid.valueOf(oid));
}
return oids;
}
private String oidsToString(Set<Integer> oids) {
StringBuffer sb = new StringBuffer();
for (Integer oid : oids) {
sb.append(Oid.toString(oid));
sb.append(',');
}
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
} else {
sb.append(" <none>");
}
return sb.toString();
}
private final TimestampUtils timestampUtils;
public TimestampUtils getTimestampUtils() { return timestampUtils; }
/*
* The current type mappings
*/
protected java.util.Map typemap;
public java.sql.Statement createStatement() throws SQLException
{
// We now follow the spec and default to TYPE_FORWARD_ONLY.
return createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
}
public abstract java.sql.Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException;
public java.sql.PreparedStatement prepareStatement(String sql) throws SQLException
{
return prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
}
public abstract java.sql.PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException;
public java.sql.CallableStatement prepareCall(String sql) throws SQLException
{
return prepareCall(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
}
public abstract java.sql.CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException;
public java.util.Map getTypeMap() throws SQLException
{
checkClosed();
return typemap;
}
// Query executor associated with this connection.
public QueryExecutor getQueryExecutor() {
return protoConnection.getQueryExecutor();
}
/*
* This adds a warning to the warning chain.
* @param warn warning to add
*/
public void addWarning(SQLWarning warn)
{
// Add the warning to the chain
if (firstWarning != null)
firstWarning.setNextWarning(warn);
else
firstWarning = warn;
}
public ResultSet execSQLQuery(String s) throws SQLException {
return execSQLQuery(s, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
}
/**
* Simple query execution.
*/
public ResultSet execSQLQuery(String s, int resultSetType, int resultSetConcurrency) throws SQLException {
BaseStatement stat = (BaseStatement) createStatement(resultSetType, resultSetConcurrency);
boolean hasResultSet = stat.executeWithFlags(s, QueryExecutor.QUERY_SUPPRESS_BEGIN);
while (!hasResultSet && stat.getUpdateCount() != -1)
hasResultSet = stat.getMoreResults();
if (!hasResultSet)
throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA);
// Transfer warnings to the connection, since the user never
// has a chance to see the statement itself.
SQLWarning warnings = stat.getWarnings();
if (warnings != null)
addWarning(warnings);
return stat.getResultSet();
}
public void execSQLUpdate(String s) throws SQLException {
BaseStatement stmt = (BaseStatement) createStatement();
if (stmt.executeWithFlags(s, QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN))
throw new PSQLException(GT.tr("A result was returned when none was expected."),
PSQLState.TOO_MANY_RESULTS);
// Transfer warnings to the connection, since the user never
// has a chance to see the statement itself.
SQLWarning warnings = stmt.getWarnings();
if (warnings != null)
addWarning(warnings);
stmt.close();
}
/*
* In SQL, a result table can be retrieved through a cursor that
* is named. The current row of a result can be updated or deleted
* using a positioned update/delete statement that references the
* cursor name.
*
* We do not support positioned update/delete, so this is a no-op.
*
* @param cursor the cursor name
* @exception SQLException if a database access error occurs
*/
public void setCursorName(String cursor) throws SQLException
{
checkClosed();
// No-op.
}
/*
* getCursorName gets the cursor name.
*
* @return the current cursor name
* @exception SQLException if a database access error occurs
*/
public String getCursorName() throws SQLException
{
checkClosed();
return null;
}
/*
* We are required to bring back certain information by
* the DatabaseMetaData class. These functions do that.
*
* Method getURL() brings back the URL (good job we saved it)
*
* @return the url
* @exception SQLException just in case...
*/
public String getURL() throws SQLException
{
return creatingURL;
}
/*
* Method getUserName() brings back the User Name (again, we
* saved it)
*
* @return the user name
* @exception SQLException just in case...
*/
public String getUserName() throws SQLException
{
return protoConnection.getUser();
}
/*
* This returns the Fastpath API for the current connection.
*
* <p><b>NOTE:</b> This is not part of JDBC, but allows access to
* functions on the org.postgresql backend itself.
*
* <p>It is primarily used by the LargeObject API
*
* <p>The best way to use this is as follows:
*
* <p><pre>
* import org.postgresql.fastpath.*;
* ...
* Fastpath fp = ((org.postgresql.Connection)myconn).getFastpathAPI();
* </pre>
*
* <p>where myconn is an open Connection to org.postgresql.
*
* @return Fastpath object allowing access to functions on the org.postgresql
* backend.
* @exception SQLException by Fastpath when initialising for first time
*/
public Fastpath getFastpathAPI() throws SQLException
{
checkClosed();
if (fastpath == null)
fastpath = new Fastpath(this);
return fastpath;
}
// This holds a reference to the Fastpath API if already open
private Fastpath fastpath = null;
/*
* This returns the LargeObject API for the current connection.
*
* <p><b>NOTE:</b> This is not part of JDBC, but allows access to
* functions on the org.postgresql backend itself.
*
* <p>The best way to use this is as follows:
*
* <p><pre>
* import org.postgresql.largeobject.*;
* ...
* LargeObjectManager lo = ((org.postgresql.Connection)myconn).getLargeObjectAPI();
* </pre>
*
* <p>where myconn is an open Connection to org.postgresql.
*
* @return LargeObject object that implements the API
* @exception SQLException by LargeObject when initialising for first time
*/
public LargeObjectManager getLargeObjectAPI() throws SQLException
{
checkClosed();
if (largeobject == null)
largeobject = new LargeObjectManager(this);
return largeobject;
}
// This holds a reference to the LargeObject API if already open
private LargeObjectManager largeobject = null;
/*
* This method is used internally to return an object based around
* org.postgresql's more unique data types.
*
* <p>It uses an internal HashMap to get the handling class. If the
* type is not supported, then an instance of org.postgresql.util.PGobject
* is returned.
*
* You can use the getValue() or setValue() methods to handle the returned
* object. Custom objects can have their own methods.
*
* @return PGobject for this type, and set to value
* @exception SQLException if value is not correct for this type
*/
public Object getObject(String type, String value, byte[] byteValue) throws SQLException
{
if (typemap != null)
{
Class c = (Class) typemap.get(type);
if (c != null)
{
// Handle the type (requires SQLInput & SQLOutput classes to be implemented)
throw new PSQLException(GT.tr("Custom type maps are not supported."), PSQLState.NOT_IMPLEMENTED);
}
}
PGobject obj = null;
if (logger.logDebug())
logger.debug("Constructing object from type=" + type + " value=<" + value + ">");
try
{
Class klass = _typeCache.getPGobject(type);
// If className is not null, then try to instantiate it,
// It must be basetype PGobject
// This is used to implement the org.postgresql unique types (like lseg,
// point, etc).
if (klass != null)
{
obj = (PGobject) (klass.newInstance());
obj.setType(type);
if (byteValue != null && obj instanceof PGBinaryObject) {
PGBinaryObject binObj = (PGBinaryObject) obj;
binObj.setByteValue(byteValue, 0);
} else {
obj.setValue(value);
}
}
else
{
// If className is null, then the type is unknown.
// so return a PGobject with the type set, and the value set
obj = new PGobject();
obj.setType( type );
obj.setValue( value );
}
return obj;
}
catch (SQLException sx)
{
// rethrow the exception. Done because we capture any others next
throw sx;
}
catch (Exception ex)
{
throw new PSQLException(GT.tr("Failed to create object for: {0}.", type), PSQLState.CONNECTION_FAILURE, ex);
}
}
protected TypeInfo createTypeInfo(BaseConnection conn, int unknownLength)
{
return new TypeInfoCache(conn, unknownLength);
}
public TypeInfo getTypeInfo()
{
return _typeCache;
}
public void addDataType(String type, String name)
{
try
{
addDataType(type, Class.forName(name));
}
catch (Exception e)
{
throw new RuntimeException("Cannot register new type: " + e);
}
}
public void addDataType(String type, Class klass) throws SQLException
{
checkClosed();
_typeCache.addDataType(type, klass);
}
// This initialises the objectTypes hash map
private void initObjectTypes(Properties info) throws SQLException
{
// Add in the types that come packaged with the driver.
// These can be overridden later if desired.
addDataType("box", org.postgresql.geometric.PGbox.class);
addDataType("circle", org.postgresql.geometric.PGcircle.class);
addDataType("line", org.postgresql.geometric.PGline.class);
addDataType("lseg", org.postgresql.geometric.PGlseg.class);
addDataType("path", org.postgresql.geometric.PGpath.class);
addDataType("point", org.postgresql.geometric.PGpoint.class);
addDataType("polygon", org.postgresql.geometric.PGpolygon.class);
addDataType("money", org.postgresql.util.PGmoney.class);
addDataType("interval", org.postgresql.util.PGInterval.class);
for (Enumeration e = info.propertyNames(); e.hasMoreElements(); )
{
String propertyName = (String)e.nextElement();
if (propertyName.startsWith("datatype."))
{
String typeName = propertyName.substring(9);
String className = info.getProperty(propertyName);
Class klass;
try
{
klass = Class.forName(className);
}
catch (ClassNotFoundException cnfe)
{
throw new PSQLException(GT.tr("Unable to load the class {0} responsible for the datatype {1}", new Object[] { className, typeName }),
PSQLState.SYSTEM_ERROR, cnfe);
}
addDataType(typeName, klass);
}
}
}
/**
* In some cases, it is desirable to immediately release a Connection's
* database and JDBC resources instead of waiting for them to be
* automatically released.
*
* <B>Note:</B> A Connection is automatically closed when it is
* garbage collected. Certain fatal errors also result in a closed
* connection.
*
* @exception SQLException if a database access error occurs
*/
public void close()
{
protoConnection.close();
openStackTrace = null;
}
/*
* A driver may convert the JDBC sql grammar into its system's
* native SQL grammar prior to sending it; nativeSQL returns the
* native form of the statement that the driver would have sent.
*
* @param sql a SQL statement that may contain one or more '?'
* parameter placeholders
* @return the native form of this statement
* @exception SQLException if a database access error occurs
*/
public String nativeSQL(String sql) throws SQLException
{
checkClosed();
StringBuffer buf = new StringBuffer(sql.length());
AbstractJdbc2Statement.parseSql(sql,0,buf,false,getStandardConformingStrings());
return buf.toString();
}
/*
* The first warning reported by calls on this Connection is
* returned.
*
* <B>Note:</B> Sebsequent warnings will be changed to this
* SQLWarning
*
* @return the first SQLWarning or null
* @exception SQLException if a database access error occurs
*/
public synchronized SQLWarning getWarnings()
throws SQLException
{
checkClosed();
SQLWarning newWarnings = protoConnection.getWarnings(); // NB: also clears them.
if (firstWarning == null)
firstWarning = newWarnings;
else
firstWarning.setNextWarning(newWarnings); // Chain them on.
return firstWarning;
}
/*
* After this call, getWarnings returns null until a new warning
* is reported for this connection.
*
* @exception SQLException if a database access error occurs
*/
public synchronized void clearWarnings()
throws SQLException
{
checkClosed();
protoConnection.getWarnings(); // Clear and discard.
firstWarning = null;
}
/*
* You can put a connection in read-only mode as a hunt to enable
* database optimizations
*
* <B>Note:</B> setReadOnly cannot be called while in the middle
* of a transaction
*
* @param readOnly - true enables read-only mode; false disables it
* @exception SQLException if a database access error occurs
*/
public void setReadOnly(boolean readOnly) throws SQLException
{
checkClosed();
if (protoConnection.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
throw new PSQLException(GT.tr("Cannot change transaction read-only property in the middle of a transaction."),
PSQLState.ACTIVE_SQL_TRANSACTION);
if (haveMinimumServerVersion("7.4") && readOnly != this.readOnly)
{
String readOnlySql = "SET SESSION CHARACTERISTICS AS TRANSACTION " + (readOnly ? "READ ONLY" : "READ WRITE");
execSQLUpdate(readOnlySql); // nb: no BEGIN triggered.
}
this.readOnly = readOnly;
}
/*
* Tests to see if the connection is in Read Only Mode.
*
* @return true if the connection is read only
* @exception SQLException if a database access error occurs
*/
public boolean isReadOnly() throws SQLException
{
checkClosed();
return readOnly;
}
/*
* If a connection is in auto-commit mode, than all its SQL
* statements will be executed and committed as individual
* transactions. Otherwise, its SQL statements are grouped
* into transactions that are terminated by either commit()
* or rollback(). By default, new connections are in auto-
* commit mode. The commit occurs when the statement completes
* or the next execute occurs, whichever comes first. In the
* case of statements returning a ResultSet, the statement
* completes when the last row of the ResultSet has been retrieved
* or the ResultSet has been closed. In advanced cases, a single
* statement may return multiple results as well as output parameter
* values. Here the commit occurs when all results and output param
* values have been retrieved.
*
* @param autoCommit - true enables auto-commit; false disables it
* @exception SQLException if a database access error occurs
*/
public void setAutoCommit(boolean autoCommit) throws SQLException
{
checkClosed();
if (this.autoCommit == autoCommit)
return ;
if (!this.autoCommit)
commit();
this.autoCommit = autoCommit;
}
/*
* gets the current auto-commit state
*
* @return Current state of the auto-commit mode
* @see setAutoCommit
*/
public boolean getAutoCommit() throws SQLException
{
checkClosed();
return this.autoCommit;
}
private void executeTransactionCommand(Query query) throws SQLException {
int flags = QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN;
if (prepareThreshold == 0) {
flags |= QueryExecutor.QUERY_ONESHOT;
}
getQueryExecutor().execute(query, null, new TransactionCommandHandler(),
0, 0, flags);
}
/*
* The method commit() makes all changes made since the previous
* commit/rollback permanent and releases any database locks currently
* held by the Connection. This method should only be used when
* auto-commit has been disabled.
*
* @exception SQLException if a database access error occurs,
* this method is called on a closed connection or
* this Connection object is in auto-commit mode
* @see setAutoCommit
*/
public void commit() throws SQLException
{
checkClosed();
if (autoCommit)
throw new PSQLException(GT.tr("Cannot commit when autoCommit is enabled."),
PSQLState.NO_ACTIVE_SQL_TRANSACTION);
if (protoConnection.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
executeTransactionCommand(commitQuery);
}
protected void checkClosed() throws SQLException {
if (isClosed())
throw new PSQLException(GT.tr("This connection has been closed."),
PSQLState.CONNECTION_DOES_NOT_EXIST);
}
/*
* The method rollback() drops all changes made since the previous
* commit/rollback and releases any database locks currently held by
* the Connection.
*
* @exception SQLException if a database access error occurs,
* this method is called on a closed connection or
* this Connection object is in auto-commit mode
* @see commit
*/
public void rollback() throws SQLException
{
checkClosed();
if (autoCommit)
throw new PSQLException(GT.tr("Cannot rollback when autoCommit is enabled."),
PSQLState.NO_ACTIVE_SQL_TRANSACTION);
if (protoConnection.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
executeTransactionCommand(rollbackQuery);
}
public int getTransactionState() {
return protoConnection.getTransactionState();
}
/*
* Get this Connection's current transaction isolation mode.
*
* @return the current TRANSACTION_* mode value
* @exception SQLException if a database access error occurs
*/
public int getTransactionIsolation() throws SQLException
{
checkClosed();
String level = null;
if (haveMinimumServerVersion("7.3"))
{
// 7.3+ returns the level as a query result.
ResultSet rs = execSQLQuery("SHOW TRANSACTION ISOLATION LEVEL"); // nb: no BEGIN triggered
if (rs.next())
level = rs.getString(1);
rs.close();
}
else
{
// 7.2 returns the level as an INFO message. Ew.
// We juggle the warning chains a bit here.
// Swap out current warnings.
SQLWarning saveWarnings = getWarnings();
clearWarnings();
// Run the query any examine any resulting warnings.
execSQLUpdate("SHOW TRANSACTION ISOLATION LEVEL"); // nb: no BEGIN triggered
SQLWarning warning = getWarnings();
if (warning != null)
level = warning.getMessage();
// Swap original warnings back.
clearWarnings();
if (saveWarnings != null)
addWarning(saveWarnings);
}
// XXX revisit: throw exception instead of silently eating the error in unkwon cases?
if (level == null)
return Connection.TRANSACTION_READ_COMMITTED; // Best guess.
level = level.toUpperCase(Locale.US);
if (level.indexOf("READ COMMITTED") != -1)
return Connection.TRANSACTION_READ_COMMITTED;
if (level.indexOf("READ UNCOMMITTED") != -1)
return Connection.TRANSACTION_READ_UNCOMMITTED;
if (level.indexOf("REPEATABLE READ") != -1)
return Connection.TRANSACTION_REPEATABLE_READ;
if (level.indexOf("SERIALIZABLE") != -1)
return Connection.TRANSACTION_SERIALIZABLE;
return Connection.TRANSACTION_READ_COMMITTED; // Best guess.
}
/*
* You can call this method to try to change the transaction
* isolation level using one of the TRANSACTION_* values.
*
* <B>Note:</B> setTransactionIsolation cannot be called while
* in the middle of a transaction
*
* @param level one of the TRANSACTION_* isolation values with
* the exception of TRANSACTION_NONE; some databases may
* not support other values
* @exception SQLException if a database access error occurs
* @see java.sql.DatabaseMetaData#supportsTransactionIsolationLevel
*/
public void setTransactionIsolation(int level) throws SQLException
{
checkClosed();
if (protoConnection.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
throw new PSQLException(GT.tr("Cannot change transaction isolation level in the middle of a transaction."),
PSQLState.ACTIVE_SQL_TRANSACTION);
String isolationLevelName = getIsolationLevelName(level);
if (isolationLevelName == null)
throw new PSQLException(GT.tr("Transaction isolation level {0} not supported.", new Integer(level)), PSQLState.NOT_IMPLEMENTED);
String isolationLevelSQL = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL " + isolationLevelName;
execSQLUpdate(isolationLevelSQL); // nb: no BEGIN triggered
}
protected String getIsolationLevelName(int level)
{
boolean pg80 = haveMinimumServerVersion("8.0");
if (level == Connection.TRANSACTION_READ_COMMITTED)
{
return "READ COMMITTED";
}
else if (level == Connection.TRANSACTION_SERIALIZABLE)
{
return "SERIALIZABLE";
}
else if (pg80 && level == Connection.TRANSACTION_READ_UNCOMMITTED)
{
return "READ UNCOMMITTED";
}
else if (pg80 && level == Connection.TRANSACTION_REPEATABLE_READ)
{
return "REPEATABLE READ";
}
return null;
}
/*
* A sub-space of this Connection's database may be selected by
* setting a catalog name. If the driver does not support catalogs,
* it will silently ignore this request
*
* @exception SQLException if a database access error occurs
*/
public void setCatalog(String catalog) throws SQLException
{
checkClosed();
//no-op
}
/*
* Return the connections current catalog name, or null if no
* catalog name is set, or we dont support catalogs.
*
* @return the current catalog name or null
* @exception SQLException if a database access error occurs
*/
public String getCatalog() throws SQLException
{
checkClosed();
return protoConnection.getDatabase();
}
/*
* Overides finalize(). If called, it closes the connection.
*
* This was done at the request of Rachel Greenham
* <rachel@enlarion.demon.co.uk> who hit a problem where multiple
* clients didn't close the connection, and once a fortnight enough
* clients were open to kill the postgres server.
*/
protected void finalize() throws Throwable
{
if (openStackTrace != null)
logger.log(GT.tr("Finalizing a Connection that was never closed:"), openStackTrace);
close();
}
/*
* Get server version number
*/
public String getDBVersionNumber()
{
return dbVersionNumber;
}
// Parse a "dirty" integer surrounded by non-numeric characters
private static int integerPart(String dirtyString)
{
int start, end;
for (start = 0; start < dirtyString.length() && !Character.isDigit(dirtyString.charAt(start)); ++start)
;
for (end = start; end < dirtyString.length() && Character.isDigit(dirtyString.charAt(end)); ++end)
;
if (start == end)
return 0;
return Integer.parseInt(dirtyString.substring(start, end));
}
/*
* Get server major version
*/
public int getServerMajorVersion()
{
try
{
StringTokenizer versionTokens = new StringTokenizer(dbVersionNumber, "."); // aaXbb.ccYdd
return integerPart(versionTokens.nextToken()); // return X
}
catch (NoSuchElementException e)
{
return 0;
}
}
/*
* Get server minor version
*/
public int getServerMinorVersion()
{
try
{
StringTokenizer versionTokens = new StringTokenizer(dbVersionNumber, "."); // aaXbb.ccYdd
versionTokens.nextToken(); // Skip aaXbb
return integerPart(versionTokens.nextToken()); // return Y
}
catch (NoSuchElementException e)
{
return 0;
}
}
/**
* Is the server we are connected to running at least this version?
* This comparison method will fail whenever a major or minor version
* goes to two digits (10.3.0) or (7.10.1).
*/
public boolean haveMinimumServerVersion(String ver)
{
return (dbVersionNumber.compareTo(ver) >= 0);
}
/*
* This method returns true if the compatible level set in the connection
* (which can be passed into the connection or specified in the URL)
* is at least the value passed to this method. This is used to toggle
* between different functionality as it changes across different releases
* of the jdbc driver code. The values here are versions of the jdbc client
* and not server versions. For example in 7.1 get/setBytes worked on
* LargeObject values, in 7.2 these methods were changed to work on bytea
* values. This change in functionality could be disabled by setting the
* "compatible" level to be 7.1, in which case the driver will revert to
* the 7.1 functionality.
*/
public boolean haveMinimumCompatibleVersion(String ver)
{
return (compatible.compareTo(ver) >= 0);
}
public Encoding getEncoding() {
return protoConnection.getEncoding();
}
public byte[] encodeString(String str) throws SQLException {
try
{
return getEncoding().encode(str);
}
catch (IOException ioe)
{
throw new PSQLException(GT.tr("Unable to translate data into the desired encoding."), PSQLState.DATA_ERROR, ioe);
}
}
public String escapeString(String str) throws SQLException {
return Utils.appendEscapedLiteral(null, str,
protoConnection.getStandardConformingStrings()).toString();
}
public boolean getStandardConformingStrings() {
return protoConnection.getStandardConformingStrings();
}
// This is a cache of the DatabaseMetaData instance for this connection
protected java.sql.DatabaseMetaData metadata;
/*
* Tests to see if a Connection is closed
*
* @return the status of the connection
* @exception SQLException (why?)
*/
public boolean isClosed() throws SQLException
{
return protoConnection.isClosed();
}
public void cancelQuery() throws SQLException
{
checkClosed();
protoConnection.sendQueryCancel();
}
public PGNotification[] getNotifications() throws SQLException
{
checkClosed();
getQueryExecutor().processNotifies();
// Backwards-compatibility hand-holding.
PGNotification[] notifications = protoConnection.getNotifications();
return (notifications.length == 0 ? null : notifications);
}
//
// Handler for transaction queries
//
private class TransactionCommandHandler implements ResultHandler {
private SQLException error;
public void handleResultRows(Query fromQuery, Field[] fields, List tuples, ResultCursor cursor) {
}
public void handleCommandStatus(String status, int updateCount, long insertOID) {
}
public void handleWarning(SQLWarning warning) {
AbstractJdbc2Connection.this.addWarning(warning);
}
public void handleError(SQLException newError) {
if (error == null)
error = newError;
else
error.setNextException(newError);
}
public void handleCompletion() throws SQLException {
if (error != null)
throw error;
}
}
public int getPrepareThreshold() {
return prepareThreshold;
}
public void setPrepareThreshold(int newThreshold) {
this.prepareThreshold = (newThreshold <= 0 ? 0 : newThreshold);
}
public void setTypeMapImpl(java.util.Map map) throws SQLException
{
typemap = map;
}
public Logger getLogger()
{
return logger;
}
//Because the get/setLogStream methods are deprecated in JDBC2
//we use the get/setLogWriter methods here for JDBC2 by overriding
//the base version of this method
protected void enableDriverManagerLogging()
{
if (DriverManager.getLogWriter() == null)
{
DriverManager.setLogWriter(new PrintWriter(System.out, true));
}
}
public int getProtocolVersion()
{
return protoConnection.getProtocolVersion();
}
public boolean getStringVarcharFlag()
{
return bindStringAsVarchar;
}
private CopyManager copyManager = null;
public CopyManager getCopyAPI() throws SQLException
{
checkClosed();
if (copyManager == null)
copyManager = new CopyManager(this);
return copyManager;
}
public boolean binaryTransferSend(int oid) {
return useBinarySendForOids.contains(oid);
}
public int getBackendPID()
{
return protoConnection.getBackendPID();
}
}
| bsd-3-clause |
exponentjs/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/updates/UpdatesModule.java | 9674 | package abi43_0_0.expo.modules.updates;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import abi43_0_0.expo.modules.core.ExportedModule;
import abi43_0_0.expo.modules.core.ModuleRegistry;
import abi43_0_0.expo.modules.core.Promise;
import abi43_0_0.expo.modules.core.interfaces.ExpoMethod;
import androidx.annotation.Nullable;
import expo.modules.updates.db.DatabaseHolder;
import expo.modules.updates.db.entity.AssetEntity;
import expo.modules.updates.db.entity.UpdateEntity;
import expo.modules.updates.launcher.Launcher;
import expo.modules.updates.loader.FileDownloader;
import expo.modules.updates.manifest.UpdateManifest;
import expo.modules.updates.loader.RemoteLoader;
import expo.modules.updates.manifest.ManifestMetadata;
// this unused import must stay because of versioning
import expo.modules.updates.UpdatesConfiguration;
public class UpdatesModule extends ExportedModule {
private static final String NAME = "ExpoUpdates";
private static final String TAG = UpdatesModule.class.getSimpleName();
private ModuleRegistry mModuleRegistry;
public UpdatesModule(Context context) {
super(context);
}
@Override
public String getName() {
return NAME;
}
@Override
public void onCreate(ModuleRegistry moduleRegistry) {
mModuleRegistry = moduleRegistry;
}
private UpdatesInterface getUpdatesService() {
return mModuleRegistry.getModule(UpdatesInterface.class);
}
@Override
public Map<String, Object> getConstants() {
Map<String, Object> constants = new HashMap<>();
try {
UpdatesInterface updatesService = getUpdatesService();
if (updatesService != null) {
constants.put("isEmergencyLaunch", updatesService.isEmergencyLaunch());
constants.put("isMissingRuntimeVersion", updatesService.getConfiguration().isMissingRuntimeVersion());
UpdateEntity launchedUpdate = updatesService.getLaunchedUpdate();
if (launchedUpdate != null) {
constants.put("updateId", launchedUpdate.getId().toString());
constants.put("manifestString", launchedUpdate.getManifest() != null ? launchedUpdate.getManifest().toString() : "{}");
}
Map<AssetEntity, String> localAssetFiles = updatesService.getLocalAssetFiles();
if (localAssetFiles != null) {
Map<String, String> localAssets = new HashMap<>();
for (AssetEntity asset : localAssetFiles.keySet()) {
if (asset.getKey() != null) {
localAssets.put(asset.getKey(), localAssetFiles.get(asset));
}
}
constants.put("localAssets", localAssets);
}
constants.put("isEnabled", updatesService.getConfiguration().isEnabled());
constants.put("releaseChannel", updatesService.getConfiguration().getReleaseChannel());
constants.put("isUsingEmbeddedAssets", updatesService.isUsingEmbeddedAssets());
}
} catch (Exception e) {
// do nothing; this is expected in a development client
constants.put("isEnabled", false);
// In a development client, we normally don't have access to the updates configuration, but
// we should attempt to see if the runtime/sdk versions are defined in AndroidManifest.xml
// and warn the developer if not. This does not take into account any extra configuration
// provided at runtime in MainApplication.java, because we don't have access to that in a
// debug build.
UpdatesConfiguration configuration = new UpdatesConfiguration(getContext(), null);
constants.put("isMissingRuntimeVersion", configuration.isMissingRuntimeVersion());
}
return constants;
}
@ExpoMethod
public void reload(final Promise promise) {
try {
UpdatesInterface updatesService = getUpdatesService();
if (!updatesService.canRelaunch()) {
promise.reject("ERR_UPDATES_DISABLED", "You cannot reload when expo-updates is not enabled.");
return;
}
updatesService.relaunchReactApplication(new Launcher.LauncherCallback() {
@Override
public void onFailure(Exception e) {
Log.e(TAG, "Failed to relaunch application", e);
promise.reject("ERR_UPDATES_RELOAD", e.getMessage(), e);
}
@Override
public void onSuccess() {
promise.resolve(null);
}
});
} catch (IllegalStateException e) {
promise.reject(
"ERR_UPDATES_RELOAD",
"The updates module controller has not been properly initialized. If you're using a development client, you cannot use `Updates.reloadAsync`. Otherwise, make sure you have called the native method UpdatesController.initialize()."
);
}
}
@ExpoMethod
public void checkForUpdateAsync(final Promise promise) {
try {
final UpdatesInterface updatesService = getUpdatesService();
if (!updatesService.getConfiguration().isEnabled()) {
promise.reject("ERR_UPDATES_DISABLED", "You cannot check for updates when expo-updates is not enabled.");
return;
}
DatabaseHolder databaseHolder = updatesService.getDatabaseHolder();
JSONObject extraHeaders = ManifestMetadata.getServerDefinedHeaders(databaseHolder.getDatabase(), updatesService.getConfiguration());
databaseHolder.releaseDatabase();
updatesService.getFileDownloader().downloadManifest(updatesService.getConfiguration(), extraHeaders, getContext(), new FileDownloader.ManifestDownloadCallback() {
@Override
public void onFailure(String message, Exception e) {
promise.reject("ERR_UPDATES_CHECK", message, e);
Log.e(TAG, message, e);
}
@Override
public void onSuccess(UpdateManifest updateManifest) {
UpdateEntity launchedUpdate = updatesService.getLaunchedUpdate();
Bundle updateInfo = new Bundle();
if (launchedUpdate == null) {
// this shouldn't ever happen, but if we don't have anything to compare
// the new manifest to, let the user know an update is available
updateInfo.putBoolean("isAvailable", true);
updateInfo.putString("manifestString", updateManifest.getManifest().toString());
promise.resolve(updateInfo);
return;
}
if (updatesService.getSelectionPolicy().shouldLoadNewUpdate(updateManifest.getUpdateEntity(), launchedUpdate, updateManifest.getManifestFilters())) {
updateInfo.putBoolean("isAvailable", true);
updateInfo.putString("manifestString", updateManifest.getManifest().toString());
promise.resolve(updateInfo);
} else {
updateInfo.putBoolean("isAvailable", false);
promise.resolve(updateInfo);
}
}
});
} catch (IllegalStateException e) {
promise.reject(
"ERR_UPDATES_CHECK",
"The updates module controller has not been properly initialized. If you're using a development client, you cannot check for updates. Otherwise, make sure you have called the native method UpdatesController.initialize()."
);
}
}
@ExpoMethod
public void fetchUpdateAsync(final Promise promise) {
try {
final UpdatesInterface updatesService = getUpdatesService();
if (!updatesService.getConfiguration().isEnabled()) {
promise.reject("ERR_UPDATES_DISABLED", "You cannot fetch updates when expo-updates is not enabled.");
return;
}
AsyncTask.execute(() -> {
final DatabaseHolder databaseHolder = updatesService.getDatabaseHolder();
new RemoteLoader(getContext(), updatesService.getConfiguration(), databaseHolder.getDatabase(), updatesService.getFileDownloader(), updatesService.getDirectory())
.start(
new RemoteLoader.LoaderCallback() {
@Override
public void onFailure(Exception e) {
databaseHolder.releaseDatabase();
promise.reject("ERR_UPDATES_FETCH", "Failed to download new update", e);
}
@Override
public void onAssetLoaded(AssetEntity asset, int successfulAssetCount, int failedAssetCount, int totalAssetCount) {
}
@Override
public boolean onUpdateManifestLoaded(UpdateManifest updateManifest) {
return updatesService.getSelectionPolicy().shouldLoadNewUpdate(
updateManifest.getUpdateEntity(),
updatesService.getLaunchedUpdate(),
updateManifest.getManifestFilters());
}
@Override
public void onSuccess(@Nullable UpdateEntity update) {
databaseHolder.releaseDatabase();
Bundle updateInfo = new Bundle();
if (update == null) {
updateInfo.putBoolean("isNew", false);
} else {
updatesService.resetSelectionPolicy();
updateInfo.putBoolean("isNew", true);
updateInfo.putString("manifestString", update.getManifest().toString());
}
promise.resolve(updateInfo);
}
}
);
});
} catch (IllegalStateException e) {
promise.reject(
"ERR_UPDATES_FETCH",
"The updates module controller has not been properly initialized. If you're using a development client, you cannot fetch updates. Otherwise, make sure you have called the native method UpdatesController.initialize()."
);
}
}
}
| bsd-3-clause |
virgo47/javasimon | core/src/test/java/org/javasimon/utils/ReplacerTest.java | 909 | package org.javasimon.utils;
import static org.testng.Assert.*;
import org.testng.annotations.Test;
public class ReplacerTest {
@Test(timeOut = 100)
public void nonRepeatingReplacerMakesSinglePass() {
Replacer replacer = new Replacer("AA", "A");
assertEquals(replacer.process("AAAA"), "AA");
}
@Test(timeOut = 100)
public void repeatingReplacerReducesStringCompletely() {
Replacer replacer = new Replacer("AA", "A", Replacer.Modificator.REPEAT_UNTIL_UNCHANGED);
assertEquals(replacer.process("AAAA"), "A");
}
@Test(timeOut = 100)
public void replacerIsCaseSensitiveByDefault() {
Replacer replacer = new Replacer("AA", "A");
assertEquals(replacer.process("aaaa"), "aaaa");
}
@Test(timeOut = 100)
public void replacerIgnoresCaseWithModificator() {
Replacer replacer = new Replacer("AA", "A", Replacer.Modificator.IGNORE_CASE);
assertEquals(replacer.process("aaaa"), "AA");
}
} | bsd-3-clause |
wix/petri | wix-petri-core/src/test/java/com/wixpress/petri/laboratory/InMemoryExperimentsSource.java | 815 | package com.wixpress.petri.laboratory;
import com.wixpress.petri.ExperimentsAndState;
import com.wixpress.petri.experiments.domain.Experiment;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: sagyr
* Date: 7/16/14
* Time: 4:28 PM
* To change this template use File | Settings | File Templates.
*/
public class InMemoryExperimentsSource implements CachedExperiments.ExperimentsSource {
private List<Experiment> experiments;
private boolean stale = true;
@Override
public ExperimentsAndState read(){
return new ExperimentsAndState(experiments, stale);
}
public void write(List<Experiment> experiments) {
this.experiments = experiments;
this.stale = false;
}
public void setStale(boolean stale) {
this.stale = stale;
}
}
| bsd-3-clause |
picocontainer/NanoContainer-nanowar | nanowar-webwork2/src/java/org/nanocontainer/nanowar/webwork2/PicoObjectFactory.java | 4161 | /*****************************************************************************
* Copyright (C) NanoContainer Organization. All rights reserved. *
* ------------------------------------------------------------------------- *
* The software in this package is published under the terms of the BSD *
* style license a copy of which has been included with this distribution in *
* the LICENSE.txt file. *
* *
*****************************************************************************/
package org.nanocontainer.nanowar.webwork2;
import com.opensymphony.xwork.ObjectFactory;
import org.nanocontainer.nanowar.ActionsContainerFactory;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.PicoContainer;
import org.picocontainer.defaults.DefaultPicoContainer;
import org.picocontainer.defaults.ObjectReference;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* <p>
* XWork ObjectFactory which uses a PicoContainer to create component instances.
* </p>
*
* @author Cyrille Le Clerc
* @author Jonas Engman
* @author Mauro Talevi
* @author Grégory Joseph
* @author Konstatin Pribluda
*/
public class PicoObjectFactory extends ObjectFactory {
private final ActionsContainerFactory actionsContainerFactory = new ActionsContainerFactory();
private final ObjectReference objectReference;
/**
* Creates a PicoObjectFactory with given object reference,
* used to pass the http request to the factory
*
* @param objectReference the ObjectReference
*/
public PicoObjectFactory(ObjectReference objectReference) {
this.objectReference = objectReference;
}
public boolean isNoArgConstructorRequired() {
return false;
}
/**
* Webwork-2.2 / XWork-1.1 method. ExtraContext can be ignored.
*/
public Object buildBean(Class clazz, Map extraContext) throws Exception {
return buildBean(clazz);
}
/**
* Webwork-2.2 / XWork-1.1 method. ExtraContext can be ignored.
*/
public Object buildBean(String className, Map extraContext) throws Exception {
return buildBean(className);
}
/**
* Webwork-2.2 / XWork-1.1 method. Used to validate a class be loaded.
* Using actionsContainerFactory for consistency with build methods.
*/
public Class getClassInstance(String className) throws ClassNotFoundException {
return actionsContainerFactory.getActionClass(className);
}
/**
* Instantiates an action using the PicoContainer found in the request scope.
* if action or bean is not registered explicitely, new instance will be provided
* on every invocation.
*
* @see com.opensymphony.xwork.ObjectFactory#buildBean(java.lang.Class)
*/
public Object buildBean(Class actionClass) throws Exception {
PicoContainer actionsContainer = actionsContainerFactory.getActionsContainer((HttpServletRequest) objectReference.get());
Object action = actionsContainer.getComponentInstance(actionClass);
if (action == null) {
// The action wasn't registered. Attempt to instantiate it.
// use child container to prevent weirdest errors
MutablePicoContainer child = new DefaultPicoContainer(actionsContainer);
child.registerComponentImplementation(actionClass);
action = child.getComponentInstance(actionClass);
}
return action;
}
/**
* As {@link ObjectFactory#buildBean(java.lang.String)}does not delegate to
* {@link ObjectFactory#buildBean(java.lang.Class)} but directly calls
* <code>clazz.newInstance()</code>, overwrite this method to call
* <code>buildBean()</code>
*
* @see com.opensymphony.xwork.ObjectFactory#buildBean(java.lang.String)
*/
public Object buildBean(String className) throws Exception {
Class actionClass = actionsContainerFactory.getActionClass(className);
return buildBean(actionClass);
}
}
| bsd-3-clause |
William-Hill-Community/flywheel | backplane-kafka/src/main/java/au/com/williamhill/flywheel/edge/backplane/scramjet/AttributeWriter.java | 485 | package au.com.williamhill.flywheel.edge.backplane.scramjet;
import java.util.*;
final class AttributeWriter extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
AttributeWriter(String typeName) {
put(ScramjetMessage.TYPE_ATT, typeName);
}
AttributeWriter write(String key, Object value) {
put(key, value);
return this;
}
AttributeWriter writeAll(Map<String, Object> src) {
putAll(src);
return this;
}
}
| bsd-3-clause |
mikiobraun/jblas | src/main/java/org/jblas/FloatMatrix.java | 110591 | // --- BEGIN LICENSE BLOCK ---
/*
* Copyright (c) 2009, Mikio L. Braun
* Copyright (c) 2008, Johannes Schaback
* Copyright (c) 2009, Jan Saputra Müller
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* * Neither the name of the Technische Universitaet Berlin nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* 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.
*/
// --- END LICENSE BLOCK ---
package org.jblas;
import org.jblas.exceptions.SizeException;
import org.jblas.ranges.Range;
import org.jblas.util.Random;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
/**
* A general matrix class for <tt>float</tt> typed values.
*
* Don't be intimidated by the large number of methods this function defines. Most
* are overloads provided for ease of use. For example, for each arithmetic operation,
* up to six overloaded versions exist to handle in-place computations, and
* scalar arguments (like adding a number to all elements of a matrix).
*
* <h3>Construction</h3>
*
* <p>To construct a two-dimensional matrices, you can use the following constructors
* and static methods.</p>
*
* <table class="my">
* <tr><th>Method<th>Description
* <tr><td>FloatMatrix(m,n, [value1, value2, value3...])<td>Values are filled in column by column.
* <tr><td>FloatMatrix(new float[][] {{value1, value2, ...}, ...}<td>Inner arrays are rows.
* <tr><td>FloatMatrix.zeros(m,n) <td>Initial values set to 0.0f.
* <tr><td>FloatMatrix.ones(m,n) <td>Initial values set to 1.0f.
* <tr><td>FloatMatrix.rand(m,n) <td>Values drawn at random between 0.0f and 1.0f.
* <tr><td>FloatMatrix.randn(m,n) <td>Values drawn from normal distribution.
* <tr><td>FloatMatrix.eye(n) <td>Unit matrix (values 0.0f except for 1.0f on the diagonal).
* <tr><td>FloatMatrix.diag(array) <td>Diagonal matrix with given diagonal elements.
* </table>
*
* <p>Alternatively, you can construct (column) vectors, if you just supply the length
* using the following constructors and static methods.</p>
*
* <table class="my">
* <tr><th>Method</th> <th>Description</th></tr>
* <tr><td>FloatMatrix(m)</td> <td>Constructs a column vector.</td></tr>
* <tr><td>FloatMatrix(new float[] {value1, value2, ...})</td><td>Constructs a column vector.</td></tr>
* <tr><td>FloatMatrix.zeros(m)</td> <td>Initial values set to 0.0f.</td></tr>
* <tr><td>FloatMatrix.ones(m)</td> <td>Initial values set to 1.0f.</td></tr>
* <tr><td>FloatMatrix.rand(m)</td> <td>Values drawn at random between 0.0f and 1.0f.</td></tr>
* <tr><td>FloatMatrix.randn(m)</td> <td>Values drawn from normal distribution.</td></tr>
* <tr><td>FloatMatrix.linspace(a, b, n)</td><td>n linearly spaced values from a to b.</td></tr>
* <tr><td>FloatMatrix.logspace(a, b, n)</td><td>n logarithmically spaced values form 10^a to 10^b.</td></tr>
* </table>
*
* <p>You can also construct new matrices by concatenating matrices either horziontally
* or vertically:</p>
*
* <table class="my">
* <tr><th>Method<th>Description
* <tr><td>x.concatHorizontally(y)<td>New matrix will be x next to y.
* <tr><td>x.concatVertically(y)<td>New matrix will be x atop y.
* </table>
*
* <h3>Element Access, Copying and Duplication</h3>
*
* <p>To access individual elements, or whole rows and columns, use the following
* methods:<p>
*
* <table class="my">
* <tr><th>x.Method<th>Description
* <tr><td>x.get(i,j)<td>Get element in row i and column j.
* <tr><td>x.put(i, j, v)<td>Set element in row i and column j to value v
* <tr><td>x.get(i)<td>Get the ith element of the matrix (traversing rows first).
* <tr><td>x.put(i, v)<td>Set the ith element of the matrix (traversing rows first).
* <tr><td>x.getColumn(i)<td>Get a copy of column i.
* <tr><td>x.putColumn(i, c)<td>Put matrix c into column i.
* <tr><td>x.getRow(i)<td>Get a copy of row i.
* <tr><td>x.putRow(i, c)<td>Put matrix c into row i.
* <tr><td>x.swapColumns(i, j)<td>Swap the contents of columns i and j.
* <tr><td>x.swapRows(i, j)<td>Swap the contents of rows i and j.
* </table>
*
* <p>For <tt>get</tt> and <tt>put</tt>, you can also pass integer arrays,
* FloatMatrix objects, or Range objects, which then specify the indices used
* as follows:
*
* <ul>
* <li><em>integer array:</em> the elements will be used as indices.
* <li><em>FloatMatrix object:</em> non-zero entries specify the indices.
* <li><em>Range object:</em> see below.
* </ul>
*
* <p>When using <tt>put</tt> with multiple indices, the assigned object must
* have the correct size or be a scalar.</p>
*
* <p>There exist the following Range objects. The Class <tt>RangeUtils</tt> also
* contains the a number of handy helper methods for constructing these ranges.</p>
* <table class="my">
* <tr><th>Class <th>RangeUtils method <th>Indices
* <tr><td>AllRange <td>all() <td>All legal indices.
* <tr><td>PointRange <td>point(i) <td> A single point.
* <tr><td>IntervalRange <td>interval(a, b)<td> All indices from a to b (inclusive)
* <tr><td rowspan=3>IndicesRange <td>indices(int[])<td> The specified indices.
* <tr><td>indices(FloatMatrix)<td>The specified indices.
* <tr><td>find(FloatMatrix)<td>The non-zero entries of the matrix.
* </table>
*
* <p>The following methods can be used for duplicating and copying matrices.</p>
*
* <table class="my">
* <tr><th>Method<th>Description
* <tr><td>x.dup()<td>Get a copy of x.
* <tr><td>x.copy(y)<td>Copy the contents of y to x (possible resizing x).
* </table>
*
* <h3>Size and Shape</h3>
*
* <p>The following methods permit to access the size of a matrix and change its size or shape.</p>
*
* <table class="my">
* <tr><th>x.Method<th>Description
* <tr><td>x.rows<td>Number of rows.
* <tr><td>x.columns<td>Number of columns.
* <tr><td>x.length<td>Total number of elements.
* <tr><td>x.isEmpty()<td>Checks whether rows == 0 and columns == 0.
* <tr><td>x.isRowVector()<td>Checks whether rows == 1.
* <tr><td>x.isColumnVector()<td>Checks whether columns == 1.
* <tr><td>x.isVector()<td>Checks whether rows == 1 or columns == 1.
* <tr><td>x.isSquare()<td>Checks whether rows == columns.
* <tr><td>x.isScalar()<td>Checks whether length == 1.
* <tr><td>x.resize(r, c)<td>Resize the matrix to r rows and c columns, discarding the content.
* <tr><td>x.reshape(r, c)<td>Resize the matrix to r rows and c columns.<br> Number of elements must not change.
* </table>
*
* <p>The size is stored in the <tt>rows</tt> and <tt>columns</tt> member variables.
* The total number of elements is stored in <tt>length</tt>. Do not change these
* values unless you know what you're doing!</p>
*
* <h3>Arithmetics</h3>
*
* <p>The usual arithmetic operations are implemented. Each operation exists in a
* in-place version, recognizable by the suffix <tt>"i"</tt>, to which you can supply
* the result matrix (or <tt>this</tt> is used, if missing). Using in-place operations
* can also lead to a smaller memory footprint, as the number of temporary objects is
* reduced (although the JVM garbage collector is usually pretty good at reusing these
* temporary object immediately with little overhead.)</p>
*
* <p>Whenever you specify a result vector, the result vector must already have the
* correct dimensions.</p>
*
* <p>For example, you can add two matrices using the <tt>add</tt> method. If you want
* to store the result in of <tt>x + y</tt> in <tt>z</tt>, type
* <span class=code>
* x.addi(y, z) // computes x = y + z.
* </span>
* Even in-place methods return the result, such that you can easily chain in-place methods,
* for example:
* <span class=code>
* x.addi(y).addi(z) // computes x += y; x += z
* </span></p>
*
* <p>Methods which operate element-wise only make sure that the length of the matrices
* is correct. Therefore, you can add a 3 * 3 matrix to a 1 * 9 matrix, for example.</p>
*
* <p>Finally, there exist versions which take floats instead of FloatMatrix Objects
* as arguments. These then compute the operation with the same value as the
* right-hand-side. The same effect can be achieved by passing a FloatMatrix with
* exactly one element.</p>
*
* <table class="my">
* <tr><th>Operation <th>Method <th>Comment
* <tr><td>x + y <td>x.add(y) <td>
* <tr><td>x - y <td>x.sub(y), y.rsub(x) <td>rsub subtracts left from right hand side
* <tr><td rowspan=3>x * y <td>x.mul(y) <td>element-wise multiplication
* <tr> <td>x.mmul(y)<td>matrix-matrix multiplication
* <tr> <td>x.dot(y) <td>scalar-product
* <tr><td>x / y <td>x.div(y), y.rdiv(x) <td>rdiv divides right hand side by left hand side.
* <tr><td>- x <td>x.neg() <td>
* </table>
*
* <p>There also exist operations which work on whole columns or rows.</p>
*
* <table class="my">
* <tr><th>Method</th> <th>Description</th></tr>
* <tr><td>x.addRowVector</td> <td>adds a vector to each row (addiRowVector works in-place)</td></tr>
* <tr><td>x.addColumnVector</td><td>adds a vector to each column</td></tr>
* <tr><td>x.subRowVector</td> <td>subtracts a vector from each row</td></tr>
* <tr><td>x.subColumnVector</td><td>subtracts a vector from each column</td></tr>
* <tr><td>x.mulRowVector</td> <td>Multiplies each row by a vector (elementwise)</td></tr>
* <tr><td>x.mulColumnVector</td><td>Multiplies each column by a vector (elementwise)</td></tr>
* <tr><td>x.divRowVector</td> <td>Divide each row by a vector (elementwise)</td></tr>
* <tr><td>x.divColumnVector</td><td>Divide each column by a vector (elementwise)</td></tr>
* <tr><td>x.mulRow</td> <td>Multiplies a row by a scalar</td></tr>
* <tr><td>x.mulColumn</td> <td>Multiplies a column by a scalar</td></tr>
* </table>
*
* <p>In principle, you could achieve the same result by first calling getColumn(),
* adding, and then calling putColumn, but these methods are much faster.</p>
*
* <p>The following comparison operations are available</p>
*
* <table class="my">
* <tr><th>Operation <th>Method
* <tr><td>x < y <td>x.lt(y)
* <tr><td>x <= y <td>x.le(y)
* <tr><td>x > y <td>x.gt(y)
* <tr><td>x >= y <td>x.ge(y)
* <tr><td>x == y <td>x.eq(y)
* <tr><td>x != y <td>x.ne(y)
* </table>
*
* <p> Logical operations are also supported. For these operations, a value different from
* zero is treated as "true" and zero is treated as "false". All operations are carried
* out elementwise.</p>
*
* <table class="my">
* <tr><th>Operation <th>Method
* <tr><td>x & y <td>x.and(y)
* <tr><td>x | y <td>x.or(y)
* <tr><td>x ^ y <td>x.xor(y)
* <tr><td>! x <td>x.not()
* </table>
*
* <p>Finally, there are a few more methods to compute various things:</p>
*
* <table class="my">
* <tr><th>Method <th>Description
* <tr><td>x.max() <td>Return maximal element
* <tr><td>x.argmax() <td>Return index of largest element
* <tr><td>x.min() <td>Return minimal element
* <tr><td>x.argmin() <td>Return index of smallest element
* <tr><td>x.columnMins() <td>Return column-wise minima
* <tr><td>x.columnArgmins() <td>Return column-wise index of minima
* <tr><td>x.columnMaxs() <td>Return column-wise maxima
* <tr><td>x.columnArgmaxs() <td>Return column-wise index of maxima
* </table>
*
* @author Mikio Braun, Johannes Schaback
*/
public class FloatMatrix implements Serializable {
/** Number of rows. */
public int rows;
/** Number of columns. */
public int columns;
/** Total number of elements (for convenience). */
public int length;
/** The actual data stored by rows (that is, row 0, row 1...). */
public float[] data = null; // rows are contiguous
public static final FloatMatrix EMPTY = new FloatMatrix();
static final long serialVersionUID = -1249281332731183060L;
// Precompile regex patterns
private static final Pattern SEMICOLON = Pattern.compile(";");
private static final Pattern WHITESPACES = Pattern.compile("\\s+");
private static final Pattern COMMA = Pattern.compile(",");
/**************************************************************************
*
* Constructors and factory functions
*
**************************************************************************/
/** Create a new matrix with <i>newRows</i> rows, <i>newColumns</i> columns
* using <i>newData></i> as the data. Note that any change to the FloatMatrix
* will change the input array, too.
*
* @param newRows the number of rows of the new matrix
* @param newColumns the number of columns of the new matrix
* @param newData the data array to be used. Data must be stored by column (column-major)
*/
public FloatMatrix(int newRows, int newColumns, float... newData) {
rows = newRows;
columns = newColumns;
length = rows * columns;
if (newData != null && newData.length != newRows * newColumns) {
throw new IllegalArgumentException(
"Passed data must match matrix dimensions.");
}
data = newData;
//System.err.printf("%d * %d matrix created\n", rows, columns);
}
/**
* Creates a new <i>n</i> times <i>m</i> <tt>FloatMatrix</tt>.
*
* @param newRows the number of rows (<i>n</i>) of the new matrix.
* @param newColumns the number of columns (<i>m</i>) of the new matrix.
*/
public FloatMatrix(int newRows, int newColumns) {
this(newRows, newColumns, new float[newRows * newColumns]);
}
/**
* Creates a new <tt>FloatMatrix</tt> of size 0 times 0.
*/
public FloatMatrix() {
this(0, 0, (float[]) null);
}
/**
* Create a Matrix of length <tt>len</tt>. This creates a column vector.
*
* @param len
*/
public FloatMatrix(int len) {
this(len, 1, new float[len]);
}
/**
* Create a a column vector using <i>newData</i> as the data array.
* Note that any change to the created FloatMatrix will change in input array.
*/
public FloatMatrix(float[] newData) {
this(newData.length, 1, newData);
}
/**
* Creates a new matrix by reading it from a file.
*
* @param filename the path and name of the file to read the matrix from
* @throws IOException
*/
public FloatMatrix(String filename) throws IOException {
load(filename);
}
/**
* Creates a new <i>n</i> times <i>m</i> <tt>FloatMatrix</tt> from
* the given <i>n</i> times <i>m</i> 2D data array. Note that the input array
* is copied and any change to the FloatMatrix will not change the input array.
* The first dimension of the array makes the
* rows (<i>n</i>) and the second dimension the columns (<i>m</i>). For example, the
* given code <br/><br/>
* <code>new FloatMatrix(new float[][]{{1d, 2d, 3d}, {4d, 5d, 6d}, {7d, 8d, 9d}}).print();</code><br/><br/>
* will constructs the following matrix:
* <pre>
* 1.0f 2.0f 3.0f
* 4.0f 5.0f 6.0f
* 7.0f 8.0f 9.0f
* </pre>.
* @param data <i>n</i> times <i>m</i> data array
*/
public FloatMatrix(float[][] data) {
this(data.length, data[0].length);
for (int r = 0; r < rows; r++) {
assert (data[r].length == columns);
}
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
put(r, c, data[r][c]);
}
}
}
/**
* Creates a FloatMatrix column vector from the given List<Double&rt;.
*
* @param data data from which the entries are taken.
*/
public FloatMatrix(List<Float> data) {
this(data.size());
int c = 0;
for (float d : data) {
put(c++, d);
}
}
/**
* Construct FloatMatrix from ASCII representation.
*
* This is not very fast, but can be quiet useful when
* you want to "just" construct a matrix, for example
* when testing.
*
* The format is semicolon separated rows of space separated values,
* for example "1 2 3; 4 5 6; 7 8 9".
*/
public static FloatMatrix valueOf(String text) {
String[] rowValues = SEMICOLON.split(text);
FloatMatrix result = null;
// process rest
for (int r = 0; r < rowValues.length; r++) {
String[] columnValues = WHITESPACES.split(rowValues[r].trim());
if (r == 0) {
result = new FloatMatrix(rowValues.length, columnValues.length);
}
for (int c = 0; c < columnValues.length; c++) {
result.put(r, c, Float.valueOf(columnValues[c]));
}
}
return result;
}
/**
* Serialization
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
}
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
}
/** Create matrix with random values uniformly in 0..1. */
public static FloatMatrix rand(int rows, int columns) {
FloatMatrix m = new FloatMatrix(rows, columns);
for (int i = 0; i < rows * columns; i++) {
m.data[i] = (float) Random.nextFloat();
}
return m;
}
/** Creates a column vector with random values uniformly in 0..1. */
public static FloatMatrix rand(int len) {
return rand(len, 1);
}
/** Create matrix with normally distributed random values. */
public static FloatMatrix randn(int rows, int columns) {
FloatMatrix m = new FloatMatrix(rows, columns);
for (int i = 0; i < rows * columns; i++) {
m.data[i] = (float) Random.nextGaussian();
}
return m;
}
/** Create column vector with normally distributed random values. */
public static FloatMatrix randn(int len) {
return randn(len, 1);
}
/** Creates a new matrix in which all values are equal 0. */
public static FloatMatrix zeros(int rows, int columns) {
return new FloatMatrix(rows, columns);
}
/** Creates a column vector of given length. */
public static FloatMatrix zeros(int length) {
return zeros(length, 1);
}
/** Creates a new matrix in which all values are equal 1. */
public static FloatMatrix ones(int rows, int columns) {
FloatMatrix m = new FloatMatrix(rows, columns);
for (int i = 0; i < rows * columns; i++) {
m.put(i, 1.0f);
}
return m;
}
/** Creates a column vector with all elements equal to 1. */
public static FloatMatrix ones(int length) {
return ones(length, 1);
}
/** Construct a new n-by-n identity matrix. */
public static FloatMatrix eye(int n) {
FloatMatrix m = new FloatMatrix(n, n);
for (int i = 0; i < n; i++) {
m.put(i, i, 1.0f);
}
return m;
}
/**
* Creates a new matrix where the values of the given vector are the diagonal values of
* the matrix.
*/
public static FloatMatrix diag(FloatMatrix x) {
FloatMatrix m = new FloatMatrix(x.length, x.length);
for (int i = 0; i < x.length; i++) {
m.put(i, i, x.get(i));
}
return m;
}
/**
* Construct a matrix of arbitrary shape and set the diagonal according
* to a passed vector.
*
* length of needs to be smaller than rows or columns.
*
* @param x vector to fill the diagonal with
* @param rows number of rows of the resulting matrix
* @param columns number of columns of the resulting matrix
* @return a matrix with dimensions rows * columns whose diagonal elements are filled by x
*/
public static FloatMatrix diag(FloatMatrix x, int rows, int columns) {
FloatMatrix m = new FloatMatrix(rows, columns);
for (int i = 0; i < x.length; i++) {
m.put(i, i, x.get(i));
}
return m;
}
/**
* Create a 1-by-1 matrix. For many operations, this matrix functions like a
* normal float.
*/
public static FloatMatrix scalar(float s) {
FloatMatrix m = new FloatMatrix(1, 1);
m.put(0, 0, s);
return m;
}
/** Test whether a matrix is scalar. */
public boolean isScalar() {
return length == 1;
}
/** Return the first element of the matrix. */
public float scalar() {
return get(0);
}
/**
* Construct a column vector whose entries are logarithmically spaced points from
* 10^lower to 10^upper using the specified number of steps
*
* @param lower starting exponent
* @param upper ending exponent
* @param size number of steps
* @return a column vector with (10^lower, ... 10^upper) with size many entries.
*/
public static FloatMatrix logspace(float lower, float upper, int size) {
FloatMatrix result = new FloatMatrix(size);
for (int i = 0; i < size; i++) {
float t = (float) i / (size - 1);
float e = lower * (1 - t) + t * upper;
result.put(i, (float) Math.pow(10.0f, e));
}
return result;
}
/**
* Construct a column vector whose entries are linearly spaced points from lower to upper with size
* many steps.
*
* @param lower starting value
* @param upper end value
* @param size number of steps
* @return a column vector of size (lower, ..., upper) with size many entries.
*/
public static FloatMatrix linspace(int lower, int upper, int size) {
FloatMatrix result = new FloatMatrix(size);
for (int i = 0; i < size; i++) {
float t = (float) i / (size - 1);
result.put(i, lower * (1 - t) + t * upper);
}
return result;
}
/**
* Concatenates two matrices horizontally. Matrices must have identical
* numbers of rows.
*/
public static FloatMatrix concatHorizontally(FloatMatrix A, FloatMatrix B) {
if (A.rows != B.rows) {
throw new SizeException("Matrices don't have same number of rows.");
}
FloatMatrix result = new FloatMatrix(A.rows, A.columns + B.columns);
SimpleBlas.copy(A, result);
JavaBlas.rcopy(B.length, B.data, 0, 1, result.data, A.length, 1);
return result;
}
/**
* Concatenates two matrices vertically. Matrices must have identical
* numbers of columns.
*/
public static FloatMatrix concatVertically(FloatMatrix A, FloatMatrix B) {
if (A.columns != B.columns) {
throw new SizeException("Matrices don't have same number of columns (" + A.columns + " != " + B.columns + ".");
}
FloatMatrix result = new FloatMatrix(A.rows + B.rows, A.columns);
for (int i = 0; i < A.columns; i++) {
JavaBlas.rcopy(A.rows, A.data, A.index(0, i), 1, result.data, result.index(0, i), 1);
JavaBlas.rcopy(B.rows, B.data, B.index(0, i), 1, result.data, result.index(A.rows, i), 1);
}
return result;
}
/**************************************************************************
* Working with slices (Man! 30+ methods just to make this a bit flexible...)
*/
/** Get all elements specified by the linear indices. */
public FloatMatrix get(int[] indices) {
FloatMatrix result = new FloatMatrix(indices.length);
for (int i = 0; i < indices.length; i++) {
result.put(i, get(indices[i]));
}
return result;
}
/** Get all elements for a given row and the specified columns. */
public FloatMatrix get(int r, int[] indices) {
FloatMatrix result = new FloatMatrix(1, indices.length);
for (int i = 0; i < indices.length; i++) {
result.put(i, get(r, indices[i]));
}
return result;
}
/** Get all elements for a given column and the specified rows. */
public FloatMatrix get(int[] indices, int c) {
FloatMatrix result = new FloatMatrix(indices.length, 1);
for (int i = 0; i < indices.length; i++) {
result.put(i, get(indices[i], c));
}
return result;
}
/** Get all elements from the specified rows and columns. */
public FloatMatrix get(int[] rindices, int[] cindices) {
FloatMatrix result = new FloatMatrix(rindices.length, cindices.length);
for (int i = 0; i < rindices.length; i++) {
for (int j = 0; j < cindices.length; j++) {
result.put(i, j, get(rindices[i], cindices[j]));
}
}
return result;
}
/** Get elements from specified rows and columns. */
public FloatMatrix get(Range rs, Range cs) {
rs.init(0, rows);
cs.init(0, columns);
FloatMatrix result = new FloatMatrix(rs.length(), cs.length());
for (; rs.hasMore(); rs.next()) {
cs.init(0, columns);
for (; cs.hasMore(); cs.next()) {
result.put(rs.index(), cs.index(), get(rs.value(), cs.value()));
}
}
return result;
}
public FloatMatrix get(Range rs, int c) {
rs.init(0, rows);
FloatMatrix result = new FloatMatrix(rs.length(), 1);
for (; rs.hasMore(); rs.next()) {
result.put(rs.index(), 0, get(rs.value(), c));
}
return result;
}
public FloatMatrix get(int r, Range cs) {
cs.init(0, columns);
FloatMatrix result = new FloatMatrix(1, cs.length());
for (; cs.hasMore(); cs.next()) {
result.put(0, cs.index(), get(r, cs.value()));
}
return result;
}
/** Get elements specified by the non-zero entries of the passed matrix. */
public FloatMatrix get(FloatMatrix indices) {
return get(indices.findIndices());
}
/**
* Get elements from a row and columns as specified by the non-zero entries of
* a matrix.
*/
public FloatMatrix get(int r, FloatMatrix indices) {
return get(r, indices.findIndices());
}
/**
* Get elements from a column and rows as specified by the non-zero entries of
* a matrix.
*/
public FloatMatrix get(FloatMatrix indices, int c) {
return get(indices.findIndices(), c);
}
/**
* Get elements from columns and rows as specified by the non-zero entries of
* the passed matrices.
*/
public FloatMatrix get(FloatMatrix rindices, FloatMatrix cindices) {
return get(rindices.findIndices(), cindices.findIndices());
}
/** Return all elements with linear index a, a + 1, ..., b - 1.*/
public FloatMatrix getRange(int a, int b) {
FloatMatrix result = new FloatMatrix(b - a);
for (int k = 0; k < b - a; k++) {
result.put(k, get(a + k));
}
return result;
}
/** Get elements from a row and columns <tt>a</tt> to <tt>b</tt>. */
public FloatMatrix getColumnRange(int r, int a, int b) {
FloatMatrix result = new FloatMatrix(1, b - a);
for (int k = 0; k < b - a; k++) {
result.put(k, get(r, a + k));
}
return result;
}
/** Get elements from a column and rows <tt>a/tt> to <tt>b</tt>. */
public FloatMatrix getRowRange(int a, int b, int c) {
FloatMatrix result = new FloatMatrix(b - a);
for (int k = 0; k < b - a; k++) {
result.put(k, get(a + k, c));
}
return result;
}
/**
* Get elements from rows <tt>ra</tt> to <tt>rb</tt> and
* columns <tt>ca</tt> to <tt>cb</tt>.
*/
public FloatMatrix getRange(int ra, int rb, int ca, int cb) {
FloatMatrix result = new FloatMatrix(rb - ra, cb - ca);
for (int i = 0; i < rb - ra; i++) {
for (int j = 0; j < cb - ca; j++) {
result.put(i, j, get(ra + i, ca + j));
}
}
return result;
}
/** Get whole rows from the passed indices. */
public FloatMatrix getRows(int[] rindices) {
FloatMatrix result = new FloatMatrix(rindices.length, columns);
for (int i = 0; i < rindices.length; i++) {
JavaBlas.rcopy(columns, data, index(rindices[i], 0), rows, result.data, result.index(i, 0), result.rows);
}
return result;
}
/** Get whole rows as specified by the non-zero entries of a matrix. */
public FloatMatrix getRows(FloatMatrix rindices) {
return getRows(rindices.findIndices());
}
public FloatMatrix getRows(Range indices, FloatMatrix result) {
indices.init(0, rows);
if (result.rows < indices.length()) {
throw new SizeException("Result matrix does not have enough rows (" + result.rows + " < " + indices.length() + ")");
}
result.checkColumns(columns);
indices.init(0, rows);
for (int r = 0; indices.hasMore(); indices.next(), r++) {
for (int c = 0; c < columns; c++) {
result.put(r, c, get(indices.value(), c));
}
}
return result;
}
public FloatMatrix getRows(Range indices) {
indices.init(0, rows);
FloatMatrix result = new FloatMatrix(indices.length(), columns);
return getRows(indices, result);
}
/** Get whole columns from the passed indices. */
public FloatMatrix getColumns(int[] cindices) {
FloatMatrix result = new FloatMatrix(rows, cindices.length);
for (int i = 0; i < cindices.length; i++) {
JavaBlas.rcopy(rows, data, index(0, cindices[i]), 1, result.data, result.index(0, i), 1);
}
return result;
}
/** Get whole columns as specified by the non-zero entries of a matrix. */
public FloatMatrix getColumns(FloatMatrix cindices) {
return getColumns(cindices.findIndices());
}
/** Get whole columns as specified by Range. */
public FloatMatrix getColumns(Range indices, FloatMatrix result) {
indices.init(0, columns);
if (result.columns < indices.length()) {
throw new SizeException("Result matrix does not have enough columns (" + result.columns + " < " + indices.length() + ")");
}
result.checkRows(rows);
indices.init(0, columns);
for (int c = 0; indices.hasMore(); indices.next(), c++) {
for (int r = 0; r < rows; r++) {
result.put(r, c, get(r, indices.value()));
}
}
return result;
}
public FloatMatrix getColumns(Range indices) {
indices.init(0, columns);
FloatMatrix result = new FloatMatrix(rows, indices.length());
return getColumns(indices, result);
}
/**
* Assert that the matrix has a certain length.
* @throws SizeException
*/
public void checkLength(int l) {
if (length != l) {
throw new SizeException("Matrix does not have the necessary length (" + length + " != " + l + ").");
}
}
/**
* Asserts that the matrix has a certain number of rows.
* @throws SizeException
*/
public void checkRows(int r) {
if (rows != r) {
throw new SizeException("Matrix does not have the necessary number of rows (" + rows + " != " + r + ").");
}
}
/**
* Asserts that the amtrix has a certain number of columns.
* @throws SizeException
*/
public void checkColumns(int c) {
if (columns != c) {
throw new SizeException("Matrix does not have the necessary number of columns (" + columns + " != " + c + ").");
}
}
/**
* Set elements in linear ordering in the specified indices.
*
* For example, <code>a.put(new int[]{ 1, 2, 0 }, new FloatMatrix(3, 1, 2.0f, 4.0f, 8.0f)</code>
* does <code>a.put(1, 2.0f), a.put(2, 4.0f), a.put(0, 8.0f)</code>.
*/
public FloatMatrix put(int[] indices, FloatMatrix x) {
if (x.isScalar()) {
return put(indices, x.scalar());
}
x.checkLength(indices.length);
for (int i = 0; i < indices.length; i++) {
put(indices[i], x.get(i));
}
return this;
}
/** Set multiple elements in a row. */
public FloatMatrix put(int r, int[] indices, FloatMatrix x) {
if (x.isScalar()) {
return put(r, indices, x.scalar());
}
x.checkColumns(indices.length);
for (int i = 0; i < indices.length; i++) {
put(r, indices[i], x.get(i));
}
return this;
}
/** Set multiple elements in a row. */
public FloatMatrix put(int[] indices, int c, FloatMatrix x) {
if (x.isScalar()) {
return put(indices, c, x.scalar());
}
x.checkRows(indices.length);
for (int i = 0; i < indices.length; i++) {
put(indices[i], c, x.get(i));
}
return this;
}
/** Put a sub-matrix as specified by the indices. */
public FloatMatrix put(int[] rindices, int[] cindices, FloatMatrix x) {
if (x.isScalar()) {
return put(rindices, cindices, x.scalar());
}
x.checkRows(rindices.length);
x.checkColumns(cindices.length);
for (int i = 0; i < rindices.length; i++) {
for (int j = 0; j < cindices.length; j++) {
put(rindices[i], cindices[j], x.get(i, j));
}
}
return this;
}
/** Put a matrix into specified indices. */
public FloatMatrix put(Range rs, Range cs, FloatMatrix x) {
rs.init(0, rows);
cs.init(0, columns);
x.checkRows(rs.length());
x.checkColumns(cs.length());
for (; rs.hasMore(); rs.next()) {
cs.init(0, columns);
for (; cs.hasMore(); cs.next()) {
put(rs.value(), cs.value(), x.get(rs.index(), cs.index()));
}
}
return this;
}
/** Put a single value into the specified indices (linear adressing). */
public FloatMatrix put(int[] indices, float v) {
for (int i = 0; i < indices.length; i++) {
put(indices[i], v);
}
return this;
}
/** Put a single value into a row and the specified columns. */
public FloatMatrix put(int r, int[] indices, float v) {
for (int i = 0; i < indices.length; i++) {
put(r, indices[i], v);
}
return this;
}
/** Put a single value into the specified rows of a column. */
public FloatMatrix put(int[] indices, int c, float v) {
for (int i = 0; i < indices.length; i++) {
put(indices[i], c, v);
}
return this;
}
/** Put a single value into the specified rows and columns. */
public FloatMatrix put(int[] rindices, int[] cindices, float v) {
for (int i = 0; i < rindices.length; i++) {
for (int j = 0; j < cindices.length; j++) {
put(rindices[i], cindices[j], v);
}
}
return this;
}
/**
* Put a sub-matrix into the indices specified by the non-zero entries
* of <tt>indices</tt> (linear adressing).
*/
public FloatMatrix put(FloatMatrix indices, FloatMatrix v) {
return put(indices.findIndices(), v);
}
/** Put a sub-vector into the specified columns (non-zero entries of <tt>indices</tt>) of a row. */
public FloatMatrix put(int r, FloatMatrix indices, FloatMatrix v) {
return put(r, indices.findIndices(), v);
}
/** Put a sub-vector into the specified rows (non-zero entries of <tt>indices</tt>) of a column. */
public FloatMatrix put(FloatMatrix indices, int c, FloatMatrix v) {
return put(indices.findIndices(), c, v);
}
/**
* Put a sub-matrix into the specified rows and columns (non-zero entries of
* <tt>rindices</tt> and <tt>cindices</tt>.
*/
public FloatMatrix put(FloatMatrix rindices, FloatMatrix cindices, FloatMatrix v) {
return put(rindices.findIndices(), cindices.findIndices(), v);
}
/**
* Put a single value into the elements specified by the non-zero
* entries of <tt>indices</tt> (linear adressing).
*/
public FloatMatrix put(FloatMatrix indices, float v) {
return put(indices.findIndices(), v);
}
/**
* Put a single value into the specified columns (non-zero entries of
* <tt>indices</tt>) of a row.
*/
public FloatMatrix put(int r, FloatMatrix indices, float v) {
return put(r, indices.findIndices(), v);
}
/**
* Put a single value into the specified rows (non-zero entries of
* <tt>indices</tt>) of a column.
*/
public FloatMatrix put(FloatMatrix indices, int c, float v) {
return put(indices.findIndices(), c, v);
}
/**
* Put a single value in the specified rows and columns (non-zero entries
* of <tt>rindices</tt> and <tt>cindices</tt>.
*/
public FloatMatrix put(FloatMatrix rindices, FloatMatrix cindices, float v) {
return put(rindices.findIndices(), cindices.findIndices(), v);
}
/** Find the linear indices of all non-zero elements. */
public int[] findIndices() {
int len = 0;
for (int i = 0; i < length; i++) {
if (get(i) != 0.0f) {
len++;
}
}
int[] indices = new int[len];
int c = 0;
for (int i = 0; i < length; i++) {
if (get(i) != 0.0f) {
indices[c++] = i;
}
}
return indices;
}
/**************************************************************************
* Basic operations (copying, resizing, element access)
*/
/** Return transposed copy of this matrix. */
public FloatMatrix transpose() {
FloatMatrix result = new FloatMatrix(columns, rows);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result.put(j, i, get(i, j));
}
}
return result;
}
/**
* Compare two matrices. Returns true if and only if other is also a
* FloatMatrix which has the same size and the maximal absolute
* difference in matrix elements is smaller than the specified tolerance
*/
public boolean compare(Object o, float tolerance) {
if (!(o instanceof FloatMatrix)) {
return false;
}
FloatMatrix other = (FloatMatrix) o;
if (!sameSize(other)) {
return false;
}
FloatMatrix diff = MatrixFunctions.absi(sub(other));
return diff.max() / (rows * columns) < tolerance;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof FloatMatrix)) {
return false;
}
FloatMatrix other = (FloatMatrix) o;
if (!sameSize(other)) {
return false;
} else {
return Arrays.equals(data, other.data);
}
}
@Override
public int hashCode() {
int hash = 7;
hash = 83 * hash + this.rows;
hash = 83 * hash + this.columns;
hash = 83 * hash + Arrays.hashCode(this.data);
return hash;
}
/** Resize the matrix. All elements will be set to zero. */
public void resize(int newRows, int newColumns) {
rows = newRows;
columns = newColumns;
length = newRows * newColumns;
data = new float[rows * columns];
}
/** Reshape the matrix. Number of elements must not change. */
public FloatMatrix reshape(int newRows, int newColumns) {
if (length != newRows * newColumns) {
throw new IllegalArgumentException(
"Number of elements must not change.");
}
rows = newRows;
columns = newColumns;
return this;
}
/** Generate a new matrix which has the given number of replications of this. */
public FloatMatrix repmat(int rowMult, int columnMult) {
FloatMatrix result = new FloatMatrix(rows * rowMult, columns * columnMult);
for (int c = 0; c < columnMult; c++) {
for (int r = 0; r < rowMult; r++) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result.put(r * rows + i, c * columns + j, get(i, j));
}
}
}
}
return result;
}
/** Checks whether two matrices have the same size. */
public boolean sameSize(FloatMatrix a) {
return rows == a.rows && columns == a.columns;
}
/** Throws SizeException unless two matrices have the same size. */
public void assertSameSize(FloatMatrix a) {
if (!sameSize(a)) {
throw new SizeException("Matrices must have the same size.");
}
}
/** Checks whether two matrices can be multiplied (that is, number of columns of
* this must equal number of rows of a. */
public boolean multipliesWith(FloatMatrix a) {
return columns == a.rows;
}
/** Throws SizeException unless matrices can be multiplied with one another. */
public void assertMultipliesWith(FloatMatrix a) {
if (!multipliesWith(a)) {
throw new SizeException("Number of columns of left matrix must be equal to number of rows of right matrix.");
}
}
/** Checks whether two matrices have the same length. */
public boolean sameLength(FloatMatrix a) {
return length == a.length;
}
/** Throws SizeException unless matrices have the same length. */
public void assertSameLength(FloatMatrix a) {
if (!sameLength(a)) {
throw new SizeException("Matrices must have same length (is: " + length + " and " + a.length + ")");
}
}
/** Copy FloatMatrix a to this. this a is resized if necessary. */
public FloatMatrix copy(FloatMatrix a) {
if (!sameSize(a)) {
resize(a.rows, a.columns);
}
System.arraycopy(a.data, 0, data, 0, length);
return a;
}
/**
* Returns a duplicate of this matrix. Geometry is the same (including offsets, transpose, etc.),
* but the buffer is not shared.
*/
public FloatMatrix dup() {
FloatMatrix out = new FloatMatrix(rows, columns);
JavaBlas.rcopy(length, data, 0, 1, out.data, 0, 1);
return out;
}
/** Swap two columns of a matrix. */
public FloatMatrix swapColumns(int i, int j) {
NativeBlas.sswap(rows, data, index(0, i), 1, data, index(0, j), 1);
return this;
}
/** Swap two rows of a matrix. */
public FloatMatrix swapRows(int i, int j) {
NativeBlas.sswap(columns, data, index(i, 0), rows, data, index(j, 0), rows);
return this;
}
/** Set matrix element */
public FloatMatrix put(int rowIndex, int columnIndex, float value) {
data[index(rowIndex, columnIndex)] = value;
return this;
}
/** Retrieve matrix element */
public float get(int rowIndex, int columnIndex) {
return data[index(rowIndex, columnIndex)];
}
/** Get index of an element */
public int index(int rowIndex, int columnIndex) {
return rowIndex + rows * columnIndex;
}
/** Compute the row index of a linear index. */
public int indexRows(int i) {
return i - indexColumns(i) * rows;
}
/** Compute the column index of a linear index. */
public int indexColumns(int i) {
return i / rows;
}
/** Get a matrix element (linear indexing). */
public float get(int i) {
return data[i];
}
/** Set a matrix element (linear indexing). */
public FloatMatrix put(int i, float v) {
data[i] = v;
return this;
}
/** Set all elements to a value. */
public FloatMatrix fill(float value) {
for (int i = 0; i < length; i++) {
put(i, value);
}
return this;
}
/** Get number of rows. */
public int getRows() {
return rows;
}
/** Get number of columns. */
public int getColumns() {
return columns;
}
/** Get total number of elements. */
public int getLength() {
return length;
}
/** Checks whether the matrix is empty. */
public boolean isEmpty() {
return columns == 0 || rows == 0;
}
/** Checks whether the matrix is square. */
public boolean isSquare() {
return columns == rows;
}
/** Throw SizeException unless matrix is square. */
public void assertSquare() {
if (!isSquare()) {
throw new SizeException("Matrix must be square!");
}
}
/** Checks whether the matrix is a vector. */
public boolean isVector() {
return columns == 1 || rows == 1;
}
/** Checks whether the matrix is a row vector. */
public boolean isRowVector() {
return rows == 1;
}
/** Checks whether the matrix is a column vector. */
public boolean isColumnVector() {
return columns == 1;
}
/** Returns the diagonal of the matrix. */
public FloatMatrix diag() {
assertSquare();
FloatMatrix d = new FloatMatrix(rows);
JavaBlas.rcopy(rows, data, 0, rows + 1, d.data, 0, 1);
return d;
}
/** Pretty-print this matrix to <tt>System.out</tt>. */
public void print() {
System.out.println(toString());
}
/** Generate string representation of the matrix. */
@Override
public String toString() {
return toString("%f");
}
/**
* Generate string representation of the matrix, with specified
* format for the entries. For example, <code>x.toString("%.1f")</code>
* generates a string representations having only one position after the
* decimal point.
*/
public String toString(String fmt) {
return toString(fmt, "[", "]", ", ", "; ");
}
/**
* Generate string representation of the matrix, with specified
* format for the entries, and delimiters.
*
* @param fmt entry format (passed to String.format())
* @param open opening parenthesis
* @param close closing parenthesis
* @param colSep separator between columns
* @param rowSep separator between rows
*/
public String toString(String fmt, String open, String close, String colSep, String rowSep) {
StringWriter s = new StringWriter();
PrintWriter p = new PrintWriter(s);
p.print(open);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
p.printf(fmt, get(r, c));
if (c < columns - 1) {
p.print(colSep);
}
}
if (r < rows - 1) {
p.print(rowSep);
}
}
p.print(close);
return s.toString();
}
/** Converts the matrix to a one-dimensional array of floats. */
public float[] toArray() {
float[] array = new float[length];
System.arraycopy(data, 0, array, 0, length);
return array;
}
/** Converts the matrix to a two-dimensional array of floats. */
public float[][] toArray2() {
float[][] array = new float[rows][columns];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
array[r][c] = get(r, c);
}
}
return array;
}
/** Converts the matrix to a one-dimensional array of integers. */
public int[] toIntArray() {
int[] array = new int[length];
for (int i = 0; i < length; i++) {
array[i] = (int) Math.rint(get(i));
}
return array;
}
/** Convert the matrix to a two-dimensional array of integers. */
public int[][] toIntArray2() {
int[][] array = new int[rows][columns];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
array[r][c] = (int) Math.rint(get(r, c));
}
}
return array;
}
/** Convert the matrix to a one-dimensional array of boolean values. */
public boolean[] toBooleanArray() {
boolean[] array = new boolean[length];
for (int i = 0; i < length; i++) {
array[i] = get(i) != 0.0f;
}
return array;
}
/** Convert the matrix to a two-dimensional array of boolean values. */
public boolean[][] toBooleanArray2() {
boolean[][] array = new boolean[rows][columns];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
array[r][c] = get(r, c) != 0.0f;
}
}
return array;
}
public FloatMatrix toFloat() {
FloatMatrix result = new FloatMatrix(rows, columns);
for (int i = 0; i < length; i++) {
result.put(i, (float) get(i));
}
return result;
}
/**
* A wrapper which allows to view a matrix as a List of Doubles (read-only!).
* Also implements the {@link ConvertsToFloatMatrix} interface.
*/
public class ElementsAsListView extends AbstractList<Float> implements ConvertsToFloatMatrix {
private final FloatMatrix me;
public ElementsAsListView(FloatMatrix me) {
this.me = me;
}
@Override
public Float get(int index) {
return me.get(index);
}
@Override
public int size() {
return me.length;
}
public FloatMatrix convertToFloatMatrix() {
return me;
}
}
public class RowsAsListView extends AbstractList<FloatMatrix> implements ConvertsToFloatMatrix {
private final FloatMatrix me;
public RowsAsListView(FloatMatrix me) {
this.me = me;
}
@Override
public FloatMatrix get(int index) {
return getRow(index);
}
@Override
public int size() {
return rows;
}
public FloatMatrix convertToFloatMatrix() {
return me;
}
}
public class ColumnsAsListView extends AbstractList<FloatMatrix> implements ConvertsToFloatMatrix {
private final FloatMatrix me;
public ColumnsAsListView(FloatMatrix me) {
this.me = me;
}
@Override
public FloatMatrix get(int index) {
return getColumn(index);
}
@Override
public int size() {
return columns;
}
public FloatMatrix convertToFloatMatrix() {
return me;
}
}
public List<Float> elementsAsList() {
return new ElementsAsListView(this);
}
public List<FloatMatrix> rowsAsList() {
return new RowsAsListView(this);
}
public List<FloatMatrix> columnsAsList() {
return new ColumnsAsListView(this);
}
/**************************************************************************
* Arithmetic Operations
*/
/**
* Ensures that the result vector has the same length as this. If not,
* resizing result is tried, which fails if result == this or result == other.
*/
private void ensureResultLength(FloatMatrix other, FloatMatrix result) {
if (!sameLength(result)) {
if (result == this || result == other) {
throw new SizeException("Cannot resize result matrix because it is used in-place.");
}
result.resize(rows, columns);
}
}
/** Add two matrices (in-place). */
public FloatMatrix addi(FloatMatrix other, FloatMatrix result) {
if (other.isScalar()) {
return addi(other.scalar(), result);
}
if (isScalar()) {
return other.addi(scalar(), result);
}
assertSameLength(other);
ensureResultLength(other, result);
if (result == this) {
SimpleBlas.axpy(1.0f, other, result);
} else if (result == other) {
SimpleBlas.axpy(1.0f, this, result);
} else {
/*SimpleBlas.copy(this, result);
SimpleBlas.axpy(1.0f, other, result);*/
JavaBlas.rzgxpy(length, result.data, data, other.data);
}
return result;
}
/** Add a scalar to a matrix (in-place). */
public FloatMatrix addi(float v, FloatMatrix result) {
ensureResultLength(null, result);
for (int i = 0; i < length; i++) {
result.put(i, get(i) + v);
}
return result;
}
/** Subtract two matrices (in-place). */
public FloatMatrix subi(FloatMatrix other, FloatMatrix result) {
if (other.isScalar()) {
return subi(other.scalar(), result);
}
if (isScalar()) {
return other.rsubi(scalar(), result);
}
assertSameLength(other);
ensureResultLength(other, result);
if (result == this) {
SimpleBlas.axpy(-1.0f, other, result);
} else if (result == other) {
SimpleBlas.scal(-1.0f, result);
SimpleBlas.axpy(1.0f, this, result);
} else {
SimpleBlas.copy(this, result);
SimpleBlas.axpy(-1.0f, other, result);
}
return result;
}
/** Subtract a scalar from a matrix (in-place). */
public FloatMatrix subi(float v, FloatMatrix result) {
ensureResultLength(null, result);
for (int i = 0; i < length; i++) {
result.put(i, get(i) - v);
}
return result;
}
/**
* Subtract two matrices, but subtract first from second matrix, that is,
* compute <em>result = other - this</em> (in-place).
* */
public FloatMatrix rsubi(FloatMatrix other, FloatMatrix result) {
return other.subi(this, result);
}
/** Subtract a matrix from a scalar (in-place). */
public FloatMatrix rsubi(float a, FloatMatrix result) {
ensureResultLength(null, result);
for (int i = 0; i < length; i++) {
result.put(i, a - get(i));
}
return result;
}
/** Elementwise multiplication (in-place). */
public FloatMatrix muli(FloatMatrix other, FloatMatrix result) {
if (other.isScalar()) {
return muli(other.scalar(), result);
}
if (isScalar()) {
return other.muli(scalar(), result);
}
assertSameLength(other);
ensureResultLength(other, result);
for (int i = 0; i < length; i++) {
result.put(i, get(i) * other.get(i));
}
return result;
}
/** Elementwise multiplication with a scalar (in-place). */
public FloatMatrix muli(float v, FloatMatrix result) {
ensureResultLength(null, result);
for (int i = 0; i < length; i++) {
result.put(i, get(i) * v);
}
return result;
}
/** Matrix-matrix multiplication (in-place). */
public FloatMatrix mmuli(FloatMatrix other, FloatMatrix result) {
if (other.isScalar()) {
return muli(other.scalar(), result);
}
if (isScalar()) {
return other.muli(scalar(), result);
}
/* check sizes and resize if necessary */
assertMultipliesWith(other);
if (result.rows != rows || result.columns != other.columns) {
if (result != this && result != other) {
result.resize(rows, other.columns);
} else {
throw new SizeException("Cannot resize result matrix because it is used in-place.");
}
}
if (result == this || result == other) {
/* actually, blas cannot do multiplications in-place. Therefore, we will fake by
* allocating a temporary object on the side and copy the result later.
*/
FloatMatrix temp = new FloatMatrix(result.rows, result.columns);
if (other.columns == 1) {
SimpleBlas.gemv(1.0f, this, other, 0.0f, temp);
} else {
SimpleBlas.gemm(1.0f, this, other, 0.0f, temp);
}
SimpleBlas.copy(temp, result);
} else {
if (other.columns == 1) {
SimpleBlas.gemv(1.0f, this, other, 0.0f, result);
} else {
SimpleBlas.gemm(1.0f, this, other, 0.0f, result);
}
}
return result;
}
/** Matrix-matrix multiplication with a scalar (for symmetry, does the
* same as <code>muli(scalar)</code> (in-place).
*/
public FloatMatrix mmuli(float v, FloatMatrix result) {
return muli(v, result);
}
/** Elementwise division (in-place). */
public FloatMatrix divi(FloatMatrix other, FloatMatrix result) {
if (other.isScalar()) {
return divi(other.scalar(), result);
}
if (isScalar()) {
return other.rdivi(scalar(), result);
}
assertSameLength(other);
ensureResultLength(other, result);
for (int i = 0; i < length; i++) {
result.put(i, get(i) / other.get(i));
}
return result;
}
/** Elementwise division with a scalar (in-place). */
public FloatMatrix divi(float a, FloatMatrix result) {
ensureResultLength(null, result);
for (int i = 0; i < length; i++) {
result.put(i, get(i) / a);
}
return result;
}
/**
* Elementwise division, with operands switched. Computes
* <code>result = other / this</code> (in-place). */
public FloatMatrix rdivi(FloatMatrix other, FloatMatrix result) {
return other.divi(this, result);
}
/** (Elementwise) division with a scalar, with operands switched. Computes
* <code>result = a / this</code> (in-place). */
public FloatMatrix rdivi(float a, FloatMatrix result) {
ensureResultLength(null, result);
for (int i = 0; i < length; i++) {
result.put(i, a / get(i));
}
return result;
}
/** Negate each element (in-place). */
public FloatMatrix negi() {
for (int i = 0; i < length; i++) {
put(i, -get(i));
}
return this;
}
/** Negate each element. */
public FloatMatrix neg() {
return dup().negi();
}
/** Maps zero to 1.0f and all non-zero values to 0.0f (in-place). */
public FloatMatrix noti() {
for (int i = 0; i < length; i++) {
put(i, get(i) == 0.0f ? 1.0f : 0.0f);
}
return this;
}
/** Maps zero to 1.0f and all non-zero values to 0.0f. */
public FloatMatrix not() {
return dup().noti();
}
/** Maps zero to 0.0f and all non-zero values to 1.0f (in-place). */
public FloatMatrix truthi() {
for (int i = 0; i < length; i++) {
put(i, get(i) == 0.0f ? 0.0f : 1.0f);
}
return this;
}
/** Maps zero to 0.0f and all non-zero values to 1.0f. */
public FloatMatrix truth() {
return dup().truthi();
}
public FloatMatrix isNaNi() {
for (int i = 0; i < length; i++) {
put(i, Float.isNaN(get(i)) ? 1.0f : 0.0f);
}
return this;
}
public FloatMatrix isNaN() {
return dup().isNaNi();
}
public FloatMatrix isInfinitei() {
for (int i = 0; i < length; i++) {
put(i, Float.isInfinite(get(i)) ? 1.0f : 0.0f);
}
return this;
}
public FloatMatrix isInfinite() {
return dup().isInfinitei();
}
/** Checks whether all entries (i, j) with i >= j are zero. */
public boolean isLowerTriangular() {
for (int i = 0; i < rows; i++)
for (int j = i+1; j < columns; j++) {
if (get(i, j) != 0.0f)
return false;
}
return true;
}
/**
* Checks whether all entries (i, j) with i <= j are zero.
*/
public boolean isUpperTriangular() {
for (int i = 0; i < rows; i++)
for (int j = 0; j < i && j < columns; j++) {
if (get(i, j) != 0.0f)
return false;
}
return true;
}
public FloatMatrix selecti(FloatMatrix where) {
checkLength(where.length);
for (int i = 0; i < length; i++) {
if (where.get(i) == 0.0f) {
put(i, 0.0f);
}
}
return this;
}
public FloatMatrix select(FloatMatrix where) {
return dup().selecti(where);
}
/****************************************************************
* Rank one-updates
*/
/** Computes a rank-1-update A = A + alpha * x * y'. */
public FloatMatrix rankOneUpdate(float alpha, FloatMatrix x, FloatMatrix y) {
if (rows != x.length) {
throw new SizeException("Vector x has wrong length (" + x.length + " != " + rows + ").");
}
if (columns != y.length) {
throw new SizeException("Vector y has wrong length (" + x.length + " != " + columns + ").");
}
SimpleBlas.ger(alpha, x, y, this);
return this;
}
/** Computes a rank-1-update A = A + alpha * x * x'. */
public FloatMatrix rankOneUpdate(float alpha, FloatMatrix x) {
return rankOneUpdate(alpha, x, x);
}
/** Computes a rank-1-update A = A + x * x'. */
public FloatMatrix rankOneUpdate(FloatMatrix x) {
return rankOneUpdate(1.0f, x, x);
}
/** Computes a rank-1-update A = A + x * y'. */
public FloatMatrix rankOneUpdate(FloatMatrix x, FloatMatrix y) {
return rankOneUpdate(1.0f, x, y);
}
/****************************************************************
* Logical operations
*/
/** Returns the minimal element of the matrix. */
public float min() {
if (isEmpty()) {
return Float.POSITIVE_INFINITY;
}
float v = Float.POSITIVE_INFINITY;
for (int i = 0; i < length; i++) {
if (!Float.isNaN(get(i)) && get(i) < v) {
v = get(i);
}
}
return v;
}
/**
* Returns the linear index of the minimal element. If there are
* more than one elements with this value, the first one is returned.
*/
public int argmin() {
if (isEmpty()) {
return -1;
}
float v = Float.POSITIVE_INFINITY;
int a = -1;
for (int i = 0; i < length; i++) {
if (!Float.isNaN(get(i)) && get(i) < v) {
v = get(i);
a = i;
}
}
return a;
}
/**
* Computes the minimum between two matrices. Returns the smaller of the
* corresponding elements in the matrix (in-place).
*/
public FloatMatrix mini(FloatMatrix other, FloatMatrix result) {
if (result == this) {
for (int i = 0; i < length; i++) {
if (get(i) > other.get(i)) {
put(i, other.get(i));
}
}
} else {
for (int i = 0; i < length; i++) {
if (get(i) > other.get(i)) {
result.put(i, other.get(i));
} else {
result.put(i, get(i));
}
}
}
return result;
}
/**
* Computes the minimum between two matrices. Returns the smaller of the
* corresponding elements in the matrix (in-place on this).
*/
public FloatMatrix mini(FloatMatrix other) {
return mini(other, this);
}
/**
* Computes the minimum between two matrices. Returns the smaller of the
* corresponding elements in the matrix (in-place on this).
*/
public FloatMatrix min(FloatMatrix other) {
return mini(other, new FloatMatrix(rows, columns));
}
public FloatMatrix mini(float v, FloatMatrix result) {
if (result == this) {
for (int i = 0; i < length; i++) {
if (get(i) > v) {
result.put(i, v);
}
}
} else {
for (int i = 0; i < length; i++) {
if (get(i) > v) {
result.put(i, v);
} else {
result.put(i, get(i));
}
}
}
return result;
}
public FloatMatrix mini(float v) {
return mini(v, this);
}
public FloatMatrix min(float v) {
return mini(v, new FloatMatrix(rows, columns));
}
/** Returns the maximal element of the matrix. */
public float max() {
if (isEmpty()) {
return Float.NEGATIVE_INFINITY;
}
float v = Float.NEGATIVE_INFINITY;
for (int i = 0; i < length; i++) {
if (!Float.isNaN(get(i)) && get(i) > v) {
v = get(i);
}
}
return v;
}
/**
* Returns the linear index of the maximal element of the matrix. If
* there are more than one elements with this value, the first one
* is returned.
*/
public int argmax() {
if (isEmpty()) {
return -1;
}
float v = Float.NEGATIVE_INFINITY;
int a = -1;
for (int i = 0; i < length; i++) {
if (!Float.isNaN(get(i)) && get(i) > v) {
v = get(i);
a = i;
}
}
return a;
}
/**
* Computes the maximum between two matrices. Returns the larger of the
* corresponding elements in the matrix (in-place).
*/
public FloatMatrix maxi(FloatMatrix other, FloatMatrix result) {
if (result == this) {
for (int i = 0; i < length; i++) {
if (get(i) < other.get(i)) {
put(i, other.get(i));
}
}
} else {
for (int i = 0; i < length; i++) {
if (get(i) < other.get(i)) {
result.put(i, other.get(i));
} else {
result.put(i, get(i));
}
}
}
return result;
}
/**
* Computes the maximum between two matrices. Returns the smaller of the
* corresponding elements in the matrix (in-place on this).
*/
public FloatMatrix maxi(FloatMatrix other) {
return maxi(other, this);
}
/**
* Computes the maximum between two matrices. Returns the larger of the
* corresponding elements in the matrix (in-place on this).
*/
public FloatMatrix max(FloatMatrix other) {
return maxi(other, new FloatMatrix(rows, columns));
}
public FloatMatrix maxi(float v, FloatMatrix result) {
if (result == this) {
for (int i = 0; i < length; i++) {
if (get(i) < v) {
result.put(i, v);
}
}
} else {
for (int i = 0; i < length; i++) {
if (get(i) < v) {
result.put(i, v);
} else {
result.put(i, get(i));
}
}
}
return result;
}
public FloatMatrix maxi(float v) {
return maxi(v, this);
}
public FloatMatrix max(float v) {
return maxi(v, new FloatMatrix(rows, columns));
}
/** Computes the sum of all elements of the matrix. */
public float sum() {
float s = 0.0f;
for (int i = 0; i < length; i++) {
s += get(i);
}
return s;
}
/** Computes the product of all elements of the matrix */
public float prod() {
float p = 1.0f;
for (int i = 0; i < length; i++) {
p *= get(i);
}
return p;
}
/**
* Computes the mean value of all elements in the matrix,
* that is, <code>x.sum() / x.length</code>.
*/
public float mean() {
return sum() / length;
}
/**
* Computes the cumulative sum, that is, the sum of all elements
* of the matrix up to a given index in linear addressing (in-place).
*/
public FloatMatrix cumulativeSumi() {
float s = 0.0f;
for (int i = 0; i < length; i++) {
s += get(i);
put(i, s);
}
return this;
}
/**
* Computes the cumulative sum, that is, the sum of all elements
* of the matrix up to a given index in linear addressing.
*/
public FloatMatrix cumulativeSum() {
return dup().cumulativeSumi();
}
/** The scalar product of this with other. */
public float dot(FloatMatrix other) {
return SimpleBlas.dot(this, other);
}
/**
* Computes the projection coefficient of other on this.
*
* The returned scalar times <tt>this</tt> is the orthogonal projection
* of <tt>other</tt> on <tt>this</tt>.
*/
public float project(FloatMatrix other) {
other.checkLength(length);
float norm = 0, dot = 0;
for (int i = 0; i < this.length; i++) {
float x = get(i);
norm += x * x;
dot += x * other.get(i);
}
return dot / norm;
}
/**
* The Euclidean norm of the matrix as vector, also the Frobenius
* norm of the matrix.
*/
public float norm2() {
float norm = 0.0f;
for (int i = 0; i < length; i++) {
norm += get(i) * get(i);
}
return (float) Math.sqrt(norm);
}
/**
* The maximum norm of the matrix (maximal absolute value of the elements).
*/
public float normmax() {
float max = 0.0f;
for (int i = 0; i < length; i++) {
float a = Math.abs(get(i));
if (a > max) {
max = a;
}
}
return max;
}
/**
* The 1-norm of the matrix as vector (sum of absolute values of elements).
*/
public float norm1() {
float norm = 0.0f;
for (int i = 0; i < length; i++) {
norm += Math.abs(get(i));
}
return norm;
}
/**
* Returns the squared (Euclidean) distance.
*/
public float squaredDistance(FloatMatrix other) {
other.checkLength(length);
float sd = 0.0f;
for (int i = 0; i < length; i++) {
float d = get(i) - other.get(i);
sd += d * d;
}
return sd;
}
/**
* Returns the (euclidean) distance.
*/
public float distance2(FloatMatrix other) {
return (float) Math.sqrt(squaredDistance(other));
}
/**
* Returns the (1-norm) distance.
*/
public float distance1(FloatMatrix other) {
other.checkLength(length);
float d = 0.0f;
for (int i = 0; i < length; i++) {
d += Math.abs(get(i) - other.get(i));
}
return d;
}
/**
* Return a new matrix with all elements sorted.
*/
public FloatMatrix sort() {
float array[] = toArray();
java.util.Arrays.sort(array);
return new FloatMatrix(rows, columns, array);
}
/**
* Sort elements in-place.
*/
public FloatMatrix sorti() {
Arrays.sort(data);
return this;
}
/**
* Get the sorting permutation.
*
* @return an int[] array such that which indexes the elements in sorted
* order.
*/
public int[] sortingPermutation() {
Integer[] indices = new Integer[length];
for (int i = 0; i < length; i++) {
indices[i] = i;
}
final float[] array = data;
Arrays.sort(indices, new Comparator() {
public int compare(Object o1, Object o2) {
int i = (Integer) o1;
int j = (Integer) o2;
if (array[i] < array[j]) {
return -1;
} else if (array[i] == array[j]) {
return 0;
} else {
return 1;
}
}
});
int[] result = new int[length];
for (int i = 0; i < length; i++) {
result[i] = indices[i];
}
return result;
}
/**
* Sort columns (in-place).
*/
public FloatMatrix sortColumnsi() {
for (int i = 0; i < length; i += rows) {
Arrays.sort(data, i, i + rows);
}
return this;
}
/** Sort columns. */
public FloatMatrix sortColumns() {
return dup().sortColumnsi();
}
/** Return matrix of indices which sort all columns. */
public int[][] columnSortingPermutations() {
int[][] result = new int[columns][];
FloatMatrix temp = new FloatMatrix(rows);
for (int c = 0; c < columns; c++) {
result[c] = getColumn(c, temp).sortingPermutation();
}
return result;
}
/** Sort rows (in-place). */
public FloatMatrix sortRowsi() {
// actually, this is much harder because the data is not consecutive
// in memory...
FloatMatrix temp = new FloatMatrix(columns);
for (int r = 0; r < rows; r++) {
putRow(r, getRow(r, temp).sorti());
}
return this;
}
/** Sort rows. */
public FloatMatrix sortRows() {
return dup().sortRowsi();
}
/** Return matrix of indices which sort all columns. */
public int[][] rowSortingPermutations() {
int[][] result = new int[rows][];
FloatMatrix temp = new FloatMatrix(columns);
for (int r = 0; r < rows; r++) {
result[r] = getRow(r, temp).sortingPermutation();
}
return result;
}
/** Return a vector containing the sums of the columns (having number of columns many entries) */
public FloatMatrix columnSums() {
if (rows == 1) {
return dup();
} else {
FloatMatrix v = new FloatMatrix(1, columns);
for (int c = 0; c < columns; c++) {
for (int r = 0; r < rows; r++) {
v.put(c, v.get(c) + get(r, c));
}
}
return v;
}
}
/** Return a vector containing the means of all columns. */
public FloatMatrix columnMeans() {
return columnSums().divi(rows);
}
/** Return a vector containing the sum of the rows. */
public FloatMatrix rowSums() {
if (columns == 1) {
return dup();
} else {
FloatMatrix v = new FloatMatrix(rows);
for (int c = 0; c < columns; c++) {
for (int r = 0; r < rows; r++) {
v.put(r, v.get(r) + get(r, c));
}
}
return v;
}
}
/** Return a vector containing the means of the rows. */
public FloatMatrix rowMeans() {
return rowSums().divi(columns);
}
/************************************************************************
* Column and rows access.
*/
/** Get a copy of a column. */
public FloatMatrix getColumn(int c) {
return getColumn(c, new FloatMatrix(rows, 1));
}
/** Copy a column to the given vector. */
public FloatMatrix getColumn(int c, FloatMatrix result) {
result.checkLength(rows);
JavaBlas.rcopy(rows, data, index(0, c), 1, result.data, 0, 1);
return result;
}
/** Copy a column back into the matrix. */
public void putColumn(int c, FloatMatrix v) {
JavaBlas.rcopy(rows, v.data, 0, 1, data, index(0, c), 1);
}
/** Get a copy of a row. */
public FloatMatrix getRow(int r) {
return getRow(r, new FloatMatrix(1, columns));
}
/** Copy a row to a given vector. */
public FloatMatrix getRow(int r, FloatMatrix result) {
result.checkLength(columns);
JavaBlas.rcopy(columns, data, index(r, 0), rows, result.data, 0, 1);
return result;
}
/** Copy a row back into the matrix. */
public void putRow(int r, FloatMatrix v) {
JavaBlas.rcopy(columns, v.data, 0, 1, data, index(r, 0), rows);
}
/** Return column-wise minimums. */
public FloatMatrix columnMins() {
FloatMatrix mins = new FloatMatrix(1, columns);
for (int c = 0; c < columns; c++) {
mins.put(c, getColumn(c).min());
}
return mins;
}
/** Return index of minimal element per column. */
public int[] columnArgmins() {
int[] argmins = new int[columns];
for (int c = 0; c < columns; c++) {
argmins[c] = getColumn(c).argmin();
}
return argmins;
}
/** Return column-wise maximums. */
public FloatMatrix columnMaxs() {
FloatMatrix maxs = new FloatMatrix(1, columns);
for (int c = 0; c < columns; c++) {
maxs.put(c, getColumn(c).max());
}
return maxs;
}
/** Return index of minimal element per column. */
public int[] columnArgmaxs() {
int[] argmaxs = new int[columns];
for (int c = 0; c < columns; c++) {
argmaxs[c] = getColumn(c).argmax();
}
return argmaxs;
}
/** Return row-wise minimums. */
public FloatMatrix rowMins() {
FloatMatrix mins = new FloatMatrix(rows);
for (int c = 0; c < rows; c++) {
mins.put(c, getRow(c).min());
}
return mins;
}
/** Return index of minimal element per row. */
public int[] rowArgmins() {
int[] argmins = new int[rows];
for (int c = 0; c < rows; c++) {
argmins[c] = getRow(c).argmin();
}
return argmins;
}
/** Return row-wise maximums. */
public FloatMatrix rowMaxs() {
FloatMatrix maxs = new FloatMatrix(rows);
for (int c = 0; c < rows; c++) {
maxs.put(c, getRow(c).max());
}
return maxs;
}
/** Return index of maximum element per row. */
public int[] rowArgmaxs() {
int[] argmaxs = new int[rows];
for (int c = 0; c < rows; c++) {
argmaxs[c] = getRow(c).argmax();
}
return argmaxs;
}
/**************************************************************************
* Elementwise Functions
*/
/** Add a row vector to all rows of the matrix (in place). */
public FloatMatrix addiRowVector(FloatMatrix x) {
x.checkLength(columns);
for (int c = 0; c < columns; c++) {
for (int r = 0; r < rows; r++) {
put(r, c, get(r, c) + x.get(c));
}
}
return this;
}
/** Add a row to all rows of the matrix. */
public FloatMatrix addRowVector(FloatMatrix x) {
return dup().addiRowVector(x);
}
/** Add a vector to all columns of the matrix (in-place). */
public FloatMatrix addiColumnVector(FloatMatrix x) {
x.checkLength(rows);
for (int c = 0; c < columns; c++) {
for (int r = 0; r < rows; r++) {
put(r, c, get(r, c) + x.get(r));
}
}
return this;
}
/** Add a vector to all columns of the matrix. */
public FloatMatrix addColumnVector(FloatMatrix x) {
return dup().addiColumnVector(x);
}
/** Subtract a row vector from all rows of the matrix (in-place). */
public FloatMatrix subiRowVector(FloatMatrix x) {
// This is a bit crazy, but a row vector must have as length as the columns of the matrix.
x.checkLength(columns);
for (int c = 0; c < columns; c++) {
for (int r = 0; r < rows; r++) {
put(r, c, get(r, c) - x.get(c));
}
}
return this;
}
/** Subtract a row vector from all rows of the matrix. */
public FloatMatrix subRowVector(FloatMatrix x) {
return dup().subiRowVector(x);
}
/** Subtract a column vector from all columns of the matrix (in-place). */
public FloatMatrix subiColumnVector(FloatMatrix x) {
x.checkLength(rows);
for (int c = 0; c < columns; c++) {
for (int r = 0; r < rows; r++) {
put(r, c, get(r, c) - x.get(r));
}
}
return this;
}
/** Subtract a vector from all columns of the matrix. */
public FloatMatrix subColumnVector(FloatMatrix x) {
return dup().subiColumnVector(x);
}
/** Multiply a row by a scalar. */
public FloatMatrix mulRow(int r, float scale) {
NativeBlas.sscal(columns, scale, data, index(r, 0), rows);
return this;
}
/** Multiply a column by a scalar. */
public FloatMatrix mulColumn(int c, float scale) {
NativeBlas.sscal(rows, scale, data, index(0, c), 1);
return this;
}
/** Multiply all columns with a column vector (in-place). */
public FloatMatrix muliColumnVector(FloatMatrix x) {
x.checkLength(rows);
for (int c = 0; c < columns; c++) {
for (int r = 0; r < rows; r++) {
put(r, c, get(r, c) * x.get(r));
}
}
return this;
}
/** Multiply all columns with a column vector. */
public FloatMatrix mulColumnVector(FloatMatrix x) {
return dup().muliColumnVector(x);
}
/** Multiply all rows with a row vector (in-place). */
public FloatMatrix muliRowVector(FloatMatrix x) {
x.checkLength(columns);
for (int c = 0; c < columns; c++) {
for (int r = 0; r < rows; r++) {
put(r, c, get(r, c) * x.get(c));
}
}
return this;
}
/** Multiply all rows with a row vector. */
public FloatMatrix mulRowVector(FloatMatrix x) {
return dup().muliRowVector(x);
}
public FloatMatrix diviRowVector(FloatMatrix x) {
x.checkLength(columns);
for (int c = 0; c < columns; c++) {
for (int r = 0; r < rows; r++) {
put(r, c, get(r, c) / x.get(c));
}
}
return this;
}
public FloatMatrix divRowVector(FloatMatrix x) {
return dup().diviRowVector(x);
}
public FloatMatrix diviColumnVector(FloatMatrix x) {
x.checkLength(rows);
for (int c = 0; c < columns; c++) {
for (int r = 0; r < rows; r++) {
put(r, c, get(r, c) / x.get(r));
}
}
return this;
}
public FloatMatrix divColumnVector(FloatMatrix x) {
return dup().diviColumnVector(x);
}
/**
* Writes out this matrix to the given data stream.
* @param dos the data output stream to write to.
* @throws IOException
*/
public void out(DataOutputStream dos) throws IOException {
dos.writeUTF("float");
dos.writeInt(columns);
dos.writeInt(rows);
dos.writeInt(data.length);
for (int i = 0; i < data.length; i++) {
dos.writeFloat(data[i]);
}
}
/**
* Reads in a matrix from the given data stream. Note
* that the old data of this matrix will be discarded.
* @param dis the data input stream to read from.
* @throws IOException
*/
public void in(DataInputStream dis) throws IOException {
if (!dis.readUTF().equals("float")) {
throw new IllegalStateException("The matrix in the specified file is not of the correct type!");
}
this.columns = dis.readInt();
this.rows = dis.readInt();
final int MAX = dis.readInt();
data = new float[MAX];
for (int i = 0; i < MAX; i++) {
data[i] = dis.readFloat();
}
}
/**
* Saves this matrix to the specified file.
* @param filename the file to write the matrix in.
* @throws IOException thrown on errors while writing the matrix to the file
*/
public void save(String filename) throws IOException {
FileOutputStream fos = new FileOutputStream(filename, false);
DataOutputStream dos = new DataOutputStream(fos);
try {
this.out(dos);
} finally {
dos.close();
fos.close();
}
}
/**
* Loads a matrix from a file into this matrix. Note that the old data
* of this matrix will be discarded.
* @param filename the file to read the matrix from
* @throws IOException thrown on errors while reading the matrix
*/
public void load(String filename) throws IOException {
FileInputStream fis = new FileInputStream(filename);
DataInputStream dis = new DataInputStream(fis);
try {
this.in(dis);
}
finally {
dis.close();
fis.close();
}
}
public static FloatMatrix loadAsciiFile(String filename) throws IOException {
BufferedReader is = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
// Go through file and count columns and rows. What makes this endeavour a bit difficult is
// that files can have leading or trailing spaces leading to spurious fields
// after String.split().
String line;
int rows = 0;
int columns = -1;
while ((line = is.readLine()) != null) {
String[] elements = WHITESPACES.split(line);
int numElements = elements.length;
if (elements[0].length() == 0) {
numElements--;
}
if (elements[elements.length - 1].length() == 0) {
numElements--;
}
if (columns == -1) {
columns = numElements;
} else {
if (columns != numElements) {
throw new IOException("Number of elements changes in line " + line + ".");
}
}
rows++;
}
is.close();
FileInputStream fis = new FileInputStream(filename);
try {
// Go through file a second time process the actual data.
is = new BufferedReader(new InputStreamReader(fis));
FloatMatrix result = new FloatMatrix(rows, columns);
int r = 0;
while ((line = is.readLine()) != null) {
String[] elements = WHITESPACES.split(line);
int firstElement = (elements[0].length() == 0) ? 1 : 0;
for (int c = 0, cc = firstElement; c < columns; c++, cc++) {
result.put(r, c, Float.valueOf(elements[cc]));
}
r++;
}
return result;
} finally {
fis.close();
}
}
public static FloatMatrix loadCSVFile(String filename) throws IOException {
BufferedReader is = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
List<FloatMatrix> rows = new LinkedList<FloatMatrix>();
String line;
int columns = -1;
while ((line = is.readLine()) != null) {
String[] elements = COMMA.split(line);
int numElements = elements.length;
if (elements[0].length() == 0) {
numElements--;
}
if (elements[elements.length - 1].length() == 0) {
numElements--;
}
if (columns == -1) {
columns = numElements;
} else {
if (columns != numElements) {
throw new IOException("Number of elements changes in line " + line + ".");
}
}
FloatMatrix row = new FloatMatrix(columns);
for (int c = 0; c < columns; c++) {
row.put(c, Float.valueOf(elements[c]));
}
rows.add(row);
}
is.close();
System.out.println("Done reading file");
FloatMatrix result = new FloatMatrix(rows.size(), columns);
int r = 0;
Iterator<FloatMatrix> ri = rows.iterator();
while (ri.hasNext()) {
result.putRow(r, ri.next());
r++;
}
return result;
}
/****************************************************************
* Autogenerated code
*/
/***** Code for operators ***************************************/
/* Overloads for the usual arithmetic operations */
/*#
def gen_overloads(base, result_rows, result_cols, verb=''); <<-EOS
#{doc verb.capitalize + " a matrix (in place)."}
public FloatMatrix #{base}i(FloatMatrix other) {
return #{base}i(other, this);
}
#{doc verb.capitalize + " a matrix."}
public FloatMatrix #{base}(FloatMatrix other) {
return #{base}i(other, new FloatMatrix(#{result_rows}, #{result_cols}));
}
#{doc verb.capitalize + " a scalar (in place)."}
public FloatMatrix #{base}i(float v) {
return #{base}i(v, this);
}
#{doc verb.capitalize + " a scalar."}
public FloatMatrix #{base}(float v) {
return #{base}i(v, new FloatMatrix(rows, columns));
}
EOS
end
#*/
/* Generating code for logical operators. This not only generates the stubs
* but really all of the code.
*/
/*#
def gen_compare(name, op, cmp); <<-EOS
#{doc 'Test for ' + cmp + ' (in-place).'}
public FloatMatrix #{name}i(FloatMatrix other, FloatMatrix result) {
if (other.isScalar())
return #{name}i(other.scalar(), result);
assertSameLength(other);
ensureResultLength(other, result);
for (int i = 0; i < length; i++)
result.put(i, get(i) #{op} other.get(i) ? 1.0f : 0.0f);
return result;
}
#{doc 'Test for ' + cmp + ' (in-place).'}
public FloatMatrix #{name}i(FloatMatrix other) {
return #{name}i(other, this);
}
#{doc 'Test for ' + cmp + '.'}
public FloatMatrix #{name}(FloatMatrix other) {
return #{name}i(other, new FloatMatrix(rows, columns));
}
#{doc 'Test for ' + cmp + ' against a scalar (in-place).'}
public FloatMatrix #{name}i(float value, FloatMatrix result) {
ensureResultLength(null, result);
for (int i = 0; i < length; i++)
result.put(i, get(i) #{op} value ? 1.0f : 0.0f);
return result;
}
#{doc 'Test for ' + cmp + ' against a scalar (in-place).'}
public FloatMatrix #{name}i(float value) {
return #{name}i(value, this);
}
#{doc 'test for ' + cmp + ' against a scalar.'}
public FloatMatrix #{name}(float value) {
return #{name}i(value, new FloatMatrix(rows, columns));
}
EOS
end
#*/
/*#
def gen_logical(name, op, cmp); <<-EOS
#{doc 'Compute elementwise ' + cmp + ' (in-place).'}
public FloatMatrix #{name}i(FloatMatrix other, FloatMatrix result) {
assertSameLength(other);
ensureResultLength(other, result);
for (int i = 0; i < length; i++)
result.put(i, (get(i) != 0.0f) #{op} (other.get(i) != 0.0f) ? 1.0f : 0.0f);
return result;
}
#{doc 'Compute elementwise ' + cmp + ' (in-place).'}
public FloatMatrix #{name}i(FloatMatrix other) {
return #{name}i(other, this);
}
#{doc 'Compute elementwise ' + cmp + '.'}
public FloatMatrix #{name}(FloatMatrix other) {
return #{name}i(other, new FloatMatrix(rows, columns));
}
#{doc 'Compute elementwise ' + cmp + ' against a scalar (in-place).'}
public FloatMatrix #{name}i(float value, FloatMatrix result) {
ensureResultLength(null, result);
boolean val = (value != 0.0f);
for (int i = 0; i < length; i++)
result.put(i, (get(i) != 0.0f) #{op} val ? 1.0f : 0.0f);
return result;
}
#{doc 'Compute elementwise ' + cmp + ' against a scalar (in-place).'}
public FloatMatrix #{name}i(float value) {
return #{name}i(value, this);
}
#{doc 'Compute elementwise ' + cmp + ' against a scalar.'}
public FloatMatrix #{name}(float value) {
return #{name}i(value, new FloatMatrix(rows, columns));
}
EOS
end
#*/
/*# collect(gen_overloads('add', 'rows', 'columns', 'add'),
gen_overloads('sub', 'rows', 'columns', 'subtract'),
gen_overloads('rsub', 'rows', 'columns', '(right-)subtract'),
gen_overloads('div', 'rows', 'columns', 'elementwise divide by'),
gen_overloads('rdiv', 'rows', 'columns', '(right-)elementwise divide by'),
gen_overloads('mul', 'rows', 'columns', 'elementwise multiply by'),
gen_overloads('mmul', 'rows', 'other.columns', 'matrix-multiply by'),
gen_compare('lt', '<', '"less than"'),
gen_compare('gt', '>', '"greater than"'),
gen_compare('le', '<=', '"less than or equal"'),
gen_compare('ge', '>=', '"greater than or equal"'),
gen_compare('eq', '==', 'equality'),
gen_compare('ne', '!=', 'inequality'),
gen_logical('and', '&', 'logical and'),
gen_logical('or', '|', 'logical or'),
gen_logical('xor', '^', 'logical xor'))
#*/
//RJPP-BEGIN------------------------------------------------------------
/** Add a matrix (in place). */
public FloatMatrix addi(FloatMatrix other) {
return addi(other, this);
}
/** Add a matrix. */
public FloatMatrix add(FloatMatrix other) {
return addi(other, new FloatMatrix(rows, columns));
}
/** Add a scalar (in place). */
public FloatMatrix addi(float v) {
return addi(v, this);
}
/** Add a scalar. */
public FloatMatrix add(float v) {
return addi(v, new FloatMatrix(rows, columns));
}
/** Subtract a matrix (in place). */
public FloatMatrix subi(FloatMatrix other) {
return subi(other, this);
}
/** Subtract a matrix. */
public FloatMatrix sub(FloatMatrix other) {
return subi(other, new FloatMatrix(rows, columns));
}
/** Subtract a scalar (in place). */
public FloatMatrix subi(float v) {
return subi(v, this);
}
/** Subtract a scalar. */
public FloatMatrix sub(float v) {
return subi(v, new FloatMatrix(rows, columns));
}
/** (right-)subtract a matrix (in place). */
public FloatMatrix rsubi(FloatMatrix other) {
return rsubi(other, this);
}
/** (right-)subtract a matrix. */
public FloatMatrix rsub(FloatMatrix other) {
return rsubi(other, new FloatMatrix(rows, columns));
}
/** (right-)subtract a scalar (in place). */
public FloatMatrix rsubi(float v) {
return rsubi(v, this);
}
/** (right-)subtract a scalar. */
public FloatMatrix rsub(float v) {
return rsubi(v, new FloatMatrix(rows, columns));
}
/** Elementwise divide by a matrix (in place). */
public FloatMatrix divi(FloatMatrix other) {
return divi(other, this);
}
/** Elementwise divide by a matrix. */
public FloatMatrix div(FloatMatrix other) {
return divi(other, new FloatMatrix(rows, columns));
}
/** Elementwise divide by a scalar (in place). */
public FloatMatrix divi(float v) {
return divi(v, this);
}
/** Elementwise divide by a scalar. */
public FloatMatrix div(float v) {
return divi(v, new FloatMatrix(rows, columns));
}
/** (right-)elementwise divide by a matrix (in place). */
public FloatMatrix rdivi(FloatMatrix other) {
return rdivi(other, this);
}
/** (right-)elementwise divide by a matrix. */
public FloatMatrix rdiv(FloatMatrix other) {
return rdivi(other, new FloatMatrix(rows, columns));
}
/** (right-)elementwise divide by a scalar (in place). */
public FloatMatrix rdivi(float v) {
return rdivi(v, this);
}
/** (right-)elementwise divide by a scalar. */
public FloatMatrix rdiv(float v) {
return rdivi(v, new FloatMatrix(rows, columns));
}
/** Elementwise multiply by a matrix (in place). */
public FloatMatrix muli(FloatMatrix other) {
return muli(other, this);
}
/** Elementwise multiply by a matrix. */
public FloatMatrix mul(FloatMatrix other) {
return muli(other, new FloatMatrix(rows, columns));
}
/** Elementwise multiply by a scalar (in place). */
public FloatMatrix muli(float v) {
return muli(v, this);
}
/** Elementwise multiply by a scalar. */
public FloatMatrix mul(float v) {
return muli(v, new FloatMatrix(rows, columns));
}
/** Matrix-multiply by a matrix (in place). */
public FloatMatrix mmuli(FloatMatrix other) {
return mmuli(other, this);
}
/** Matrix-multiply by a matrix. */
public FloatMatrix mmul(FloatMatrix other) {
return mmuli(other, new FloatMatrix(rows, other.columns));
}
/** Matrix-multiply by a scalar (in place). */
public FloatMatrix mmuli(float v) {
return mmuli(v, this);
}
/** Matrix-multiply by a scalar. */
public FloatMatrix mmul(float v) {
return mmuli(v, new FloatMatrix(rows, columns));
}
/** Test for "less than" (in-place). */
public FloatMatrix lti(FloatMatrix other, FloatMatrix result) {
if (other.isScalar())
return lti(other.scalar(), result);
assertSameLength(other);
ensureResultLength(other, result);
for (int i = 0; i < length; i++)
result.put(i, get(i) < other.get(i) ? 1.0f : 0.0f);
return result;
}
/** Test for "less than" (in-place). */
public FloatMatrix lti(FloatMatrix other) {
return lti(other, this);
}
/** Test for "less than". */
public FloatMatrix lt(FloatMatrix other) {
return lti(other, new FloatMatrix(rows, columns));
}
/** Test for "less than" against a scalar (in-place). */
public FloatMatrix lti(float value, FloatMatrix result) {
ensureResultLength(null, result);
for (int i = 0; i < length; i++)
result.put(i, get(i) < value ? 1.0f : 0.0f);
return result;
}
/** Test for "less than" against a scalar (in-place). */
public FloatMatrix lti(float value) {
return lti(value, this);
}
/** test for "less than" against a scalar. */
public FloatMatrix lt(float value) {
return lti(value, new FloatMatrix(rows, columns));
}
/** Test for "greater than" (in-place). */
public FloatMatrix gti(FloatMatrix other, FloatMatrix result) {
if (other.isScalar())
return gti(other.scalar(), result);
assertSameLength(other);
ensureResultLength(other, result);
for (int i = 0; i < length; i++)
result.put(i, get(i) > other.get(i) ? 1.0f : 0.0f);
return result;
}
/** Test for "greater than" (in-place). */
public FloatMatrix gti(FloatMatrix other) {
return gti(other, this);
}
/** Test for "greater than". */
public FloatMatrix gt(FloatMatrix other) {
return gti(other, new FloatMatrix(rows, columns));
}
/** Test for "greater than" against a scalar (in-place). */
public FloatMatrix gti(float value, FloatMatrix result) {
ensureResultLength(null, result);
for (int i = 0; i < length; i++)
result.put(i, get(i) > value ? 1.0f : 0.0f);
return result;
}
/** Test for "greater than" against a scalar (in-place). */
public FloatMatrix gti(float value) {
return gti(value, this);
}
/** test for "greater than" against a scalar. */
public FloatMatrix gt(float value) {
return gti(value, new FloatMatrix(rows, columns));
}
/** Test for "less than or equal" (in-place). */
public FloatMatrix lei(FloatMatrix other, FloatMatrix result) {
if (other.isScalar())
return lei(other.scalar(), result);
assertSameLength(other);
ensureResultLength(other, result);
for (int i = 0; i < length; i++)
result.put(i, get(i) <= other.get(i) ? 1.0f : 0.0f);
return result;
}
/** Test for "less than or equal" (in-place). */
public FloatMatrix lei(FloatMatrix other) {
return lei(other, this);
}
/** Test for "less than or equal". */
public FloatMatrix le(FloatMatrix other) {
return lei(other, new FloatMatrix(rows, columns));
}
/** Test for "less than or equal" against a scalar (in-place). */
public FloatMatrix lei(float value, FloatMatrix result) {
ensureResultLength(null, result);
for (int i = 0; i < length; i++)
result.put(i, get(i) <= value ? 1.0f : 0.0f);
return result;
}
/** Test for "less than or equal" against a scalar (in-place). */
public FloatMatrix lei(float value) {
return lei(value, this);
}
/** test for "less than or equal" against a scalar. */
public FloatMatrix le(float value) {
return lei(value, new FloatMatrix(rows, columns));
}
/** Test for "greater than or equal" (in-place). */
public FloatMatrix gei(FloatMatrix other, FloatMatrix result) {
if (other.isScalar())
return gei(other.scalar(), result);
assertSameLength(other);
ensureResultLength(other, result);
for (int i = 0; i < length; i++)
result.put(i, get(i) >= other.get(i) ? 1.0f : 0.0f);
return result;
}
/** Test for "greater than or equal" (in-place). */
public FloatMatrix gei(FloatMatrix other) {
return gei(other, this);
}
/** Test for "greater than or equal". */
public FloatMatrix ge(FloatMatrix other) {
return gei(other, new FloatMatrix(rows, columns));
}
/** Test for "greater than or equal" against a scalar (in-place). */
public FloatMatrix gei(float value, FloatMatrix result) {
ensureResultLength(null, result);
for (int i = 0; i < length; i++)
result.put(i, get(i) >= value ? 1.0f : 0.0f);
return result;
}
/** Test for "greater than or equal" against a scalar (in-place). */
public FloatMatrix gei(float value) {
return gei(value, this);
}
/** test for "greater than or equal" against a scalar. */
public FloatMatrix ge(float value) {
return gei(value, new FloatMatrix(rows, columns));
}
/** Test for equality (in-place). */
public FloatMatrix eqi(FloatMatrix other, FloatMatrix result) {
if (other.isScalar())
return eqi(other.scalar(), result);
assertSameLength(other);
ensureResultLength(other, result);
for (int i = 0; i < length; i++)
result.put(i, get(i) == other.get(i) ? 1.0f : 0.0f);
return result;
}
/** Test for equality (in-place). */
public FloatMatrix eqi(FloatMatrix other) {
return eqi(other, this);
}
/** Test for equality. */
public FloatMatrix eq(FloatMatrix other) {
return eqi(other, new FloatMatrix(rows, columns));
}
/** Test for equality against a scalar (in-place). */
public FloatMatrix eqi(float value, FloatMatrix result) {
ensureResultLength(null, result);
for (int i = 0; i < length; i++)
result.put(i, get(i) == value ? 1.0f : 0.0f);
return result;
}
/** Test for equality against a scalar (in-place). */
public FloatMatrix eqi(float value) {
return eqi(value, this);
}
/** test for equality against a scalar. */
public FloatMatrix eq(float value) {
return eqi(value, new FloatMatrix(rows, columns));
}
/** Test for inequality (in-place). */
public FloatMatrix nei(FloatMatrix other, FloatMatrix result) {
if (other.isScalar())
return nei(other.scalar(), result);
assertSameLength(other);
ensureResultLength(other, result);
for (int i = 0; i < length; i++)
result.put(i, get(i) != other.get(i) ? 1.0f : 0.0f);
return result;
}
/** Test for inequality (in-place). */
public FloatMatrix nei(FloatMatrix other) {
return nei(other, this);
}
/** Test for inequality. */
public FloatMatrix ne(FloatMatrix other) {
return nei(other, new FloatMatrix(rows, columns));
}
/** Test for inequality against a scalar (in-place). */
public FloatMatrix nei(float value, FloatMatrix result) {
ensureResultLength(null, result);
for (int i = 0; i < length; i++)
result.put(i, get(i) != value ? 1.0f : 0.0f);
return result;
}
/** Test for inequality against a scalar (in-place). */
public FloatMatrix nei(float value) {
return nei(value, this);
}
/** test for inequality against a scalar. */
public FloatMatrix ne(float value) {
return nei(value, new FloatMatrix(rows, columns));
}
/** Compute elementwise logical and (in-place). */
public FloatMatrix andi(FloatMatrix other, FloatMatrix result) {
assertSameLength(other);
ensureResultLength(other, result);
for (int i = 0; i < length; i++)
result.put(i, (get(i) != 0.0f) & (other.get(i) != 0.0f) ? 1.0f : 0.0f);
return result;
}
/** Compute elementwise logical and (in-place). */
public FloatMatrix andi(FloatMatrix other) {
return andi(other, this);
}
/** Compute elementwise logical and. */
public FloatMatrix and(FloatMatrix other) {
return andi(other, new FloatMatrix(rows, columns));
}
/** Compute elementwise logical and against a scalar (in-place). */
public FloatMatrix andi(float value, FloatMatrix result) {
ensureResultLength(null, result);
boolean val = (value != 0.0f);
for (int i = 0; i < length; i++)
result.put(i, (get(i) != 0.0f) & val ? 1.0f : 0.0f);
return result;
}
/** Compute elementwise logical and against a scalar (in-place). */
public FloatMatrix andi(float value) {
return andi(value, this);
}
/** Compute elementwise logical and against a scalar. */
public FloatMatrix and(float value) {
return andi(value, new FloatMatrix(rows, columns));
}
/** Compute elementwise logical or (in-place). */
public FloatMatrix ori(FloatMatrix other, FloatMatrix result) {
assertSameLength(other);
ensureResultLength(other, result);
for (int i = 0; i < length; i++)
result.put(i, (get(i) != 0.0f) | (other.get(i) != 0.0f) ? 1.0f : 0.0f);
return result;
}
/** Compute elementwise logical or (in-place). */
public FloatMatrix ori(FloatMatrix other) {
return ori(other, this);
}
/** Compute elementwise logical or. */
public FloatMatrix or(FloatMatrix other) {
return ori(other, new FloatMatrix(rows, columns));
}
/** Compute elementwise logical or against a scalar (in-place). */
public FloatMatrix ori(float value, FloatMatrix result) {
ensureResultLength(null, result);
boolean val = (value != 0.0f);
for (int i = 0; i < length; i++)
result.put(i, (get(i) != 0.0f) | val ? 1.0f : 0.0f);
return result;
}
/** Compute elementwise logical or against a scalar (in-place). */
public FloatMatrix ori(float value) {
return ori(value, this);
}
/** Compute elementwise logical or against a scalar. */
public FloatMatrix or(float value) {
return ori(value, new FloatMatrix(rows, columns));
}
/** Compute elementwise logical xor (in-place). */
public FloatMatrix xori(FloatMatrix other, FloatMatrix result) {
assertSameLength(other);
ensureResultLength(other, result);
for (int i = 0; i < length; i++)
result.put(i, (get(i) != 0.0f) ^ (other.get(i) != 0.0f) ? 1.0f : 0.0f);
return result;
}
/** Compute elementwise logical xor (in-place). */
public FloatMatrix xori(FloatMatrix other) {
return xori(other, this);
}
/** Compute elementwise logical xor. */
public FloatMatrix xor(FloatMatrix other) {
return xori(other, new FloatMatrix(rows, columns));
}
/** Compute elementwise logical xor against a scalar (in-place). */
public FloatMatrix xori(float value, FloatMatrix result) {
ensureResultLength(null, result);
boolean val = (value != 0.0f);
for (int i = 0; i < length; i++)
result.put(i, (get(i) != 0.0f) ^ val ? 1.0f : 0.0f);
return result;
}
/** Compute elementwise logical xor against a scalar (in-place). */
public FloatMatrix xori(float value) {
return xori(value, this);
}
/** Compute elementwise logical xor against a scalar. */
public FloatMatrix xor(float value) {
return xori(value, new FloatMatrix(rows, columns));
}
//RJPP-END--------------------------------------------------------------
public ComplexFloatMatrix toComplex() {
return new ComplexFloatMatrix(this);
}
} | bsd-3-clause |
TeamCohen/MinorThird | src/main/java/iitb/CRF/Util.java | 214 | package iitb.CRF;
/**
*
* @author Sunita Sarawagi
*
*/
public class Util {
public static boolean debug=true;
static public void printDbg(String msg) {
if (debug) System.out.println(msg);
}
};
| bsd-3-clause |
DweebsUnited/CodeMonkey | java/CodeMonkey/HEMesh/wblut/hemesh/HE_BoundaryHalfedgeOuterRevCirculator.java | 1273 | /*
* HE_Mesh Frederik Vanhoutte - www.wblut.com
*
* https://github.com/wblut/HE_Mesh
* A Processing/Java library for for creating and manipulating polygonal meshes.
*
* Public Domain: http://creativecommons.org/publicdomain/zero/1.0/
*/
package wblut.hemesh;
import java.util.Iterator;
/**
*
*/
public class HE_BoundaryHalfedgeOuterRevCirculator implements Iterator<HE_Halfedge> {
/**
*
*/
private final HE_Halfedge _start;
/**
*
*/
private HE_Halfedge _current;
/**
*
*
* @param f
*/
HE_BoundaryHalfedgeOuterRevCirculator(final HE_Boundary f) {
_start = f.getHalfedge();
_current = null;
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#hasNext()
*/
@Override
public boolean hasNext() {
if (_start == null) {
return false;
}
return (_current == null || _current.getNextInFace() != _start) && _start != null;
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#next()
*/
@Override
public HE_Halfedge next() {
if (_current == null) {
_current = _start;
} else {
_current = _current.getNextInFace();
}
return _current.getPair();
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#remove()
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}
} | bsd-3-clause |
Caleydo/org.caleydo.view.domino | src/main/java/org/caleydo/view/domino/internal/undo/MoveBlockCmd.java | 1257 | /*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
*******************************************************************************/
package org.caleydo.view.domino.internal.undo;
import gleem.linalg.Vec2f;
import java.util.Set;
import org.caleydo.view.domino.internal.Block;
import org.caleydo.view.domino.internal.Domino;
/**
* @author Samuel Gratzl
*
*/
public class MoveBlockCmd implements IMergeAbleCmd {
private final Set<Block> blocks;
private final Vec2f shift;
public MoveBlockCmd(Set<Block> blocks, Vec2f shift) {
this.blocks = blocks;
this.shift = shift;
}
@Override
public String getLabel() {
return "Move Block";
}
@Override
public ICmd run(Domino domino) {
domino.moveBlocks(blocks, shift);
return new MoveBlockCmd(blocks, shift.times(-1));
}
@Override
public boolean merge(ICmd cmd) {
if (cmd instanceof MoveBlockCmd) {
final MoveBlockCmd m = (MoveBlockCmd) cmd;
if (m.blocks.equals(blocks)) {
shift.add(m.shift);
return true;
}
}
return false;
}
}
| bsd-3-clause |
egonw/openchemlib | src/com/actelion/research/chem/reaction/ReactionArrow.java | 9160 | /*
* Copyright (c) 1997 - 2015
* Actelion Pharmaceuticals Ltd.
* Gewerbestrasse 16
* CH-4123 Allschwil, Switzerland
*
* 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.
* 3. Neither the name of the the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package com.actelion.research.chem.reaction;
import java.awt.*;
import java.awt.geom.*;
import com.actelion.research.chem.AbstractDrawingObject;
import com.actelion.research.chem.DepictorTransformation;
import com.actelion.research.chem.Molecule;
public class ReactionArrow extends AbstractDrawingObject {
public static final String TYPE_STRING = "arrow";
private static final int PART_NONE = 0;
private static final int PART_ARROW_START = 1;
private static final int PART_ARROW_END = 2;
private static final int PART_ARROW = 3;
int mHiliteStatus;
public ReactionArrow() {
mPoint = new Point2D.Float[2];
mPoint[0] = new Point2D.Float();
mPoint[1] = new Point2D.Float();
mHiliteStatus = PART_NONE;
}
public ReactionArrow(String descriptorDetail) {
this();
int index1 = 0;
while (index1 != -1) {
// text="this is a test"
// 012345678901234567890
int index2 = descriptorDetail.indexOf("=\"", index1);
if (index2 == -1)
break; // should never happen
String key = descriptorDetail.substring(index1+1, index2);
index1 = descriptorDetail.indexOf("\"", index2+2);
String value = (index1 == -1) ? descriptorDetail.substring(index2+1)
: descriptorDetail.substring(index2+1, index1);
if (key.equals("x1"))
try { mPoint[0].x = Float.parseFloat(value); } catch (NumberFormatException nfe) {}
else if (key.equals("y1"))
try { mPoint[0].y = Float.parseFloat(value); } catch (NumberFormatException nfe) {}
else if (key.equals("x2"))
try { mPoint[1].x = Float.parseFloat(value); } catch (NumberFormatException nfe) {}
else if (key.equals("y2"))
try { mPoint[1].y = Float.parseFloat(value); } catch (NumberFormatException nfe) {}
}
}
public String getTypeString() {
return TYPE_STRING;
}
public String getDescriptorDetail() {
StringBuilder detail = new StringBuilder();
detail.append(" x1=\""+mPoint[0].x + "\"");
detail.append(" y1=\""+mPoint[0].y + "\"");
detail.append(" x2=\""+mPoint[1].x + "\"");
detail.append(" y2=\""+mPoint[1].y + "\"");
return detail.toString();
}
public AbstractDrawingObject clone() {
ReactionArrow arrow = new ReactionArrow();
arrow.mPoint[0].x = this.mPoint[0].x;
arrow.mPoint[0].y = this.mPoint[0].y;
arrow.mPoint[1].x = this.mPoint[1].x;
arrow.mPoint[1].y = this.mPoint[1].y;
arrow.mIsSelected = this.mIsSelected;
return arrow;
}
public float getLength() {
int dx = (int)(mPoint[1].x - mPoint[0].x);
int dy = (int)(mPoint[1].y - mPoint[0].y);
return (float)Math.sqrt(dx*dx+dy*dy);
}
public void setCoordinates(float x1, float y1, float x2, float y2) {
mPoint[0].x = x1;
mPoint[0].y = y1;
mPoint[1].x = x2;
mPoint[1].y = y2;
}
public void translate(float x, float y) {
switch (mHiliteStatus) {
case PART_ARROW_START:
mPoint[0].x = mTransformationValue1[0] + x - mTransformationReferenceX;
mPoint[0].y = mTransformationValue2[0] + y - mTransformationReferenceY;
break;
case PART_ARROW_END:
mPoint[1].x = mTransformationValue1[1] + x - mTransformationReferenceX;
mPoint[1].y = mTransformationValue2[1] + y - mTransformationReferenceY;
break;
default:
super.translate(x, y);
break;
}
}
public void draw(Graphics g, DepictorTransformation t) {
g.setColor(mIsSelected ? Color.red : Color.black);
float x1 = (t == null) ? mPoint[0].x : t.transformX(mPoint[0].x);
float y1 = (t == null) ? mPoint[0].y : t.transformY(mPoint[0].y);
float x2 = (t == null) ? mPoint[1].x : t.transformX(mPoint[1].x);
float y2 = (t == null) ? mPoint[1].y : t.transformY(mPoint[1].y);
g.drawLine((int)x1, (int)y1, (int)x2, (int)y2);
int dx = (int)(x2 - x1);
int dy = (int)(y2 - y1);
int[] px = new int[4];
int[] py = new int[4];
px[0] = (int)x2;
py[0] = (int)y2;
px[1] = (int)(x2 - dx/5 + dy/10);
py[1] = (int)(y2 - dy/5 - dx/10);
px[2] = (int)(x2 - dx/15);
py[2] = (int)(y2 - dy/15);
px[3] = (int)(x2 - dx/5 - dy/10);
py[3] = (int)(y2 - dy/5 + dx/10);
g.fillPolygon(px, py, 4);
}
public void hilite(Graphics g) {
g.setColor(SELECTION_COLOR);
switch (mHiliteStatus) {
case PART_ARROW_START:
g.fillOval((int)mPoint[0].x-8, (int)mPoint[0].y-8, 16, 16);
break;
case PART_ARROW_END:
g.fillOval((int)mPoint[1].x-8, (int)mPoint[1].y-8, 16, 16);
break;
case PART_ARROW:
float length = getLength();
float f = Math.max(length/8.0f, 3.0f);
float angle = Molecule.getAngle(mPoint[0].x, mPoint[0].y, mPoint[1].x, mPoint[1].y);
int dx = (int)(f * Math.cos(angle));
int dy = -(int)(f * Math.sin(angle));
int x[] = new int[4];
int y[] = new int[4];
x[0] = (int)(mPoint[0].x + dx);
y[0] = (int)(mPoint[0].y + dy);
x[1] = (int)(mPoint[1].x + dx);
y[1] = (int)(mPoint[1].y + dy);
x[2] = (int)(mPoint[1].x - dx);
y[2] = (int)(mPoint[1].y - dy);
x[3] = (int)(mPoint[0].x - dx);
y[3] = (int)(mPoint[0].y - dy);
g.fillPolygon(x, y, 4);
break;
}
}
public void draw2D(Graphics2D g, DepictorTransformation t) {
draw(g, t);
}
public boolean contains(float x, float y) {
return (findPart(x, y) != PART_NONE);
}
public boolean checkHiliting(float x, float y) {
mHiliteStatus = findPart(x, y);
return (mHiliteStatus != PART_NONE);
}
public void clearHiliting() {
mHiliteStatus = PART_NONE;
}
private int findPart(float x, float y) {
float distanceToStart = (float)Math.sqrt((mPoint[0].x-x)*(mPoint[0].x-x)+(mPoint[0].y-y)*(mPoint[0].y-y));
if (distanceToStart < 8.0)
return PART_ARROW_START;
float distanceToEnd = (float)Math.sqrt((mPoint[1].x-x)*(mPoint[1].x-x)+(mPoint[1].y-y)*(mPoint[1].y-y));
if (distanceToEnd < 8.0)
return PART_ARROW_END;
float arrowLength = (float)Math.sqrt((mPoint[1].x-mPoint[0].x)*(mPoint[1].x-mPoint[0].x)+(mPoint[1].y-mPoint[0].y)*(mPoint[1].y-mPoint[0].y));
if (distanceToStart + distanceToEnd < arrowLength + 5)
return PART_ARROW;
return PART_NONE;
}
public Rectangle2D.Float getBoundingRect() {
float length = getLength();
float f = Math.max(length/8.0f, 3.0f);
float angle = Molecule.getAngle(mPoint[0].x, mPoint[0].y, mPoint[1].x, mPoint[1].y);
float dx = Math.abs(f * (float)Math.cos(angle));
float dy = Math.abs(f * (float)Math.sin(angle));
Rectangle2D.Float bounds = new Rectangle2D.Float();
if (mPoint[0].x < mPoint[1].x) {
bounds.x = mPoint[0].x - dx;
bounds.width = mPoint[1].x - mPoint[0].x + 2*dx;
}
else {
bounds.x = mPoint[1].x - dx;
bounds.width = mPoint[0].x - mPoint[1].x + 2*dx;
}
if (mPoint[0].y < mPoint[1].y) {
bounds.y = mPoint[0].y - dy;
bounds.height = mPoint[1].y - mPoint[0].y + 2*dy;
}
else {
bounds.y = mPoint[1].y - dy;
bounds.height = mPoint[0].y - mPoint[1].y + 2*dy;
}
return bounds;
}
public boolean isOnProductSide(float x, float y) {
float dx = mPoint[1].x - mPoint[0].x;
float dy = mPoint[1].y - mPoint[0].y;
float mx = (mPoint[0].x + mPoint[1].x) / 2.0f;
float my = (mPoint[0].y + mPoint[1].y) / 2.0f;
if (dx == 0.0)
return (dy < 0.0) ^ (y > my);
if (dy == 0.0)
return (dx < 0.0) ^ (x > mx);
float m = -dx/dy; // m of orthogonal line through S
float sx = (mPoint[0].x + m*m*x - m*y + m*mPoint[0].y) / (1 + m*m);
return (dx < 0.0) ^ (sx > mx);
}
}
| bsd-3-clause |
att/AAF | authz/authz-cmd/src/main/java/com/att/cmd/user/ListActivity.java | 1724 | /*******************************************************************************
* Copyright (c) 2016 AT&T Intellectual Property. All rights reserved.
*******************************************************************************/
package com.att.cmd.user;
import com.att.cadi.CadiException;
import com.att.cadi.LocatorException;
import com.att.cadi.client.Future;
import com.att.cadi.client.Rcli;
import com.att.cadi.client.Retryable;
import com.att.cmd.AAFcli;
import com.att.cmd.Cmd;
import com.att.cmd.Param;
import com.att.cssa.rserv.HttpMethods;
import com.att.inno.env.APIException;
import aaf.v2_0.History;
/**
*
*/
public class ListActivity extends Cmd {
private static final String HEADER = "List Activity of User";
public ListActivity(List parent) {
super(parent,"activity",
new Param("user",true));
}
@Override
public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException {
int idx = _idx;
String user = args[idx++];
String realm = getOrgRealm();
final String fullUser = (user.indexOf('@') < 0 && realm != null)?user + '@' + realm:user;
return same(new Retryable<Integer>() {
@Override
public Integer code(Rcli<?> client) throws CadiException, APIException {
Future<History> fp = client.read(
"/authz/hist/user/"+fullUser,
getDF(History.class)
);
if(fp.get(AAFcli.timeout())) {
activity(fp.value,HEADER + " [ " + fullUser + " ]");
} else {
error(fp);
}
return fp.code();
}
});
}
@Override
public void detailedHelp(int indent, StringBuilder sb) {
detailLine(sb,indent,HEADER);
api(sb,indent,HttpMethods.GET,"authz/hist/user/<user>",History.class,true);
}
}
| bsd-3-clause |
bill-baumgartner/datasource | datasource-fileparsers/src/main/java/edu/ucdenver/ccp/datasource/fileparsers/pharmgkb/PharmGkbRelationFileParser.java | 8749 | package edu.ucdenver.ccp.datasource.fileparsers.pharmgkb;
/*
* #%L
* Colorado Computational Pharmacology's datasource
* project
* %%
* Copyright (C) 2012 - 2016 Regents of the University of Colorado
* %%
* 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.
*
* 3. Neither the name of the Regents of the University of Colorado nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT 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.
* #L%
*/
/*
* Colorado Computational Pharmacology's common module
*
* Copyright (C) 2012 - 2015 Regents of the University of Colorado
*
* 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.
*
* 3. Neither the name of the Regents of the University of Colorado nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.apache.log4j.Logger;
import edu.ucdenver.ccp.common.file.CharacterEncoding;
import edu.ucdenver.ccp.common.file.reader.Line;
import edu.ucdenver.ccp.common.string.RegExPatterns;
import edu.ucdenver.ccp.common.string.StringConstants;
import edu.ucdenver.ccp.common.string.StringUtil;
import edu.ucdenver.ccp.common.string.StringUtil.RemoveFieldEnclosures;
import edu.ucdenver.ccp.datasource.fileparsers.SingleLineFileRecordReader;
import edu.ucdenver.ccp.datasource.identifiers.DataSourceIdentifier;
import edu.ucdenver.ccp.datasource.identifiers.UnknownDataSourceIdentifier;
import edu.ucdenver.ccp.datasource.identifiers.ncbi.RefSnpID;
import edu.ucdenver.ccp.datasource.identifiers.pharmgkb.PharmGkbHaplotypeId;
import edu.ucdenver.ccp.datasource.identifiers.pharmgkb.PharmGkbID;
import edu.ucdenver.ccp.datasource.identifiers.pharmgkb.PharmGkbVariantLocationId;
import edu.ucdenver.ccp.identifier.publication.PubMedID;
public class PharmGkbRelationFileParser extends SingleLineFileRecordReader<PharmGkbRelationFileRecord> {
private static final Logger logger = Logger.getLogger(PharmGkbRelationFileParser.class);
private static final String HEADER = "Entity1_id\tEntity1_name\tEntity1_type\tEntity2_id\tEntity2_name\tEntity2_type\tEvidence\tAssociation\tPK\tPD\tPMIDs";
private static final CharacterEncoding ENCODING = CharacterEncoding.US_ASCII;
private static final String PHARMGKB_ID_PREFIX = "PA";
private static final String REFSNP_ID_PATTERN = "rs\\d+";
private static final Object ENTITY_TYPE_HAPLOTYPE = "Haplotype";
private static final Object ENTITY_TYPE_VARIANT_LOCATION = "VariantLocation";
public PharmGkbRelationFileParser(File dataFile, CharacterEncoding encoding) throws IOException {
super(dataFile, encoding, null);
}
@Override
protected String getFileHeader() throws IOException {
return readLine().getText();
}
@Override
protected String getExpectedFileHeader() throws IOException {
return HEADER;
}
@Override
protected PharmGkbRelationFileRecord parseRecordFromLine(Line line) {
String[] toks = line.getText().split(RegExPatterns.TAB, -1);
String entity1Name = toks[1];
String entity1Type = toks[2];
Set<DataSourceIdentifier<?>> entity1Id = resolveEntityId(toks[0], entity1Type);
String entity2Name = toks[4];
String entity2Type = toks[5];
Set<DataSourceIdentifier<?>> entity2Id = resolveEntityId(toks[3], entity2Type);
Set<String> evidence = new HashSet<String>(StringUtil.delimitAndTrim(toks[6], StringConstants.COMMA, null,
RemoveFieldEnclosures.FALSE));
String association = toks[7];
String pk = toks[8];
String pd = toks[9];
Collection<PubMedID> pmids = getPmids(toks[10]);
return new PharmGkbRelationFileRecord(entity1Id, entity1Name, entity1Type, entity2Id, entity2Name, entity2Type,
evidence, association, pk, pd, pmids, line.getByteOffset(), line.getLineNumber());
}
/**
* entities in the relationships.tsv file can be PharmGkb accession IDs (e.g. PA450626), RefSnp
* IDs (e.g. rs10209881), Haplotypes (e.g. CYP2A6*1B10), chromosome positions (e.g.
* chr20:48184659 (hg19))
*
* @param string
* @return
*/
private Set<DataSourceIdentifier<?>> resolveEntityId(String idStr, String entityType) {
Set<DataSourceIdentifier<?>> ids = new HashSet<DataSourceIdentifier<?>>();
String[] toks = idStr.split(",");
for (String id : toks) {
if (idStr.startsWith(PHARMGKB_ID_PREFIX)) {
ids.add(new PharmGkbID(id));
} else if (idStr.matches(REFSNP_ID_PATTERN)) {
ids.add(new RefSnpID(id));
} else if (entityType.equals(ENTITY_TYPE_HAPLOTYPE)) {
ids.add(new PharmGkbHaplotypeId(id));
} else if (entityType.equals(ENTITY_TYPE_VARIANT_LOCATION)) {
ids.add(new PharmGkbVariantLocationId(id));
} else {
ids.add(new UnknownDataSourceIdentifier(id));
}
}
return ids;
}
/**
* @param string
* @return
*/
private Collection<PubMedID> getPmids(String pmidStr) {
Collection<PubMedID> pmids = new ArrayList<PubMedID>();
if (!pmidStr.isEmpty()) {
for (String pmid : pmidStr.split(StringConstants.SEMICOLON)) {
if (pmid.startsWith(StringConstants.COLON)) {
// there are some PMIDs prefixed by a colon in the relationships.tsv file, e.g.
// ":17522595". Here we remove the leading colon if it is present.
pmid = StringUtil.removePrefix(pmid, StringConstants.COLON);
}
if (pmid.startsWith(StringConstants.LEFT_SQUARE_BRACKET)) {
// there are some PMIDs prefixed by a [ in the relationships.tsv file, e.g.
// "[11866883". Here we remove the leading [ if it is present.
pmid = StringUtil.removePrefix(pmid, StringConstants.LEFT_SQUARE_BRACKET);
}
if (pmid.endsWith(StringConstants.RIGHT_SQUARE_BRACKET)) {
// there are some PMIDs suffixed by a } in the relationships.tsv file, e.g.
// "22020825]". Here we remove the trailing ] if it is present.
pmid = StringUtil.removeSuffix(pmid, StringConstants.RIGHT_SQUARE_BRACKET);
}
if (pmid.matches(RegExPatterns.HAS_NUMBERS_ONLY)) {
pmids.add(new PubMedID(pmid));
} else {
logger.warn("Unhandled PMID format: " + pmid);
}
}
}
return pmids;
}
}
| bsd-3-clause |
metafora-project/Development | src/de/kuei/metafora/gwt/smack/server/mysql/ServerDescription.java | 1248 | package de.kuei.metafora.gwt.smack.server.mysql;
import java.net.MalformedURLException;
import java.net.URL;
public class ServerDescription {
private String serverUrl;
private String user;
private String password;
private String device;
private String modul;
private String connectionname;
public ServerDescription(String serverUrl, String user, String password,
String device, String modul, String connectionname) {
this.serverUrl = serverUrl;
this.user = user;
this.password = password;
this.device = device;
this.modul = modul;
this.connectionname = connectionname;
}
public boolean requiresLogin() {
if (user != null) {
return true;
}
return false;
}
public String getServer() {
return serverUrl;
}
public URL getServerUrl() {
URL url = null;
try {
url = new URL(serverUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}
public String getUser() {
return user;
}
public String getPassword() {
return password;
}
public String getDevice() {
return device;
}
public String getModul() {
return modul;
}
public String getConnectionName() {
return connectionname;
}
}
| bsd-3-clause |
fengshao0907/grpc-java | okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientStream.java | 7290 | /*
* Copyright 2014, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.grpc.transport.okhttp;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.squareup.okhttp.internal.spdy.ErrorCode;
import com.squareup.okhttp.internal.spdy.Header;
import io.grpc.MethodDescriptor.MethodType;
import io.grpc.Status;
import io.grpc.transport.ClientStreamListener;
import io.grpc.transport.Http2ClientStream;
import io.grpc.transport.WritableBuffer;
import okio.Buffer;
import java.util.List;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/**
* Client stream for the okhttp transport.
*/
class OkHttpClientStream extends Http2ClientStream {
private static int WINDOW_UPDATE_THRESHOLD = Utils.DEFAULT_WINDOW_SIZE / 2;
private static final Buffer EMPTY_BUFFER = new Buffer();
private final MethodType type;
/**
* Construct a new client stream.
*/
static OkHttpClientStream newStream(ClientStreamListener listener,
AsyncFrameWriter frameWriter,
OkHttpClientTransport transport,
OutboundFlowController outboundFlow,
MethodType type, Object lock) {
return new OkHttpClientStream(listener, frameWriter, transport, outboundFlow, type, lock);
}
@GuardedBy("lock")
private int window = Utils.DEFAULT_WINDOW_SIZE;
@GuardedBy("lock")
private int processedWindow = Utils.DEFAULT_WINDOW_SIZE;
private final AsyncFrameWriter frameWriter;
private final OutboundFlowController outboundFlow;
private final OkHttpClientTransport transport;
private final Object lock;
private Object outboundFlowState;
private volatile Integer id;
private OkHttpClientStream(ClientStreamListener listener,
AsyncFrameWriter frameWriter,
OkHttpClientTransport transport,
OutboundFlowController outboundFlow,
MethodType type,
Object lock) {
super(new OkHttpWritableBufferAllocator(), listener);
this.frameWriter = frameWriter;
this.transport = transport;
this.outboundFlow = outboundFlow;
this.type = type;
this.lock = lock;
}
/**
* Returns the type of this stream.
*/
public MethodType getType() {
return type;
}
@Override
public void request(final int numMessages) {
synchronized (lock) {
requestMessagesFromDeframer(numMessages);
}
}
@Override
@Nullable
public Integer id() {
return id;
}
/**
* Set the internal ID for this stream.
*/
public void id(Integer id) {
checkNotNull(id, "id");
checkState(this.id == null, "Can only set id once");
this.id = id;
}
/**
* Notification that this stream was allocated for the connection. This means the stream has
* passed through any delay caused by MAX_CONCURRENT_STREAMS.
*/
public void allocated() {
// Now that the stream has actually been initialized, call the listener's onReady callback if
// appropriate.
onStreamAllocated();
}
void onStreamSentBytes(int numBytes) {
onSentBytes(numBytes);
}
/**
* Must be called with holding the transport lock.
*/
public void transportHeadersReceived(List<Header> headers, boolean endOfStream) {
if (endOfStream) {
transportTrailersReceived(Utils.convertTrailers(headers));
} else {
transportHeadersReceived(Utils.convertHeaders(headers));
}
}
/**
* Must be called with holding the transport lock.
*/
public void transportDataReceived(okio.Buffer frame, boolean endOfStream) {
long length = frame.size();
window -= length;
if (window < 0) {
frameWriter.rstStream(id(), ErrorCode.FLOW_CONTROL_ERROR);
transport.finishStream(id(), Status.INTERNAL.withDescription(
"Received data size exceeded our receiving window size"), null);
return;
}
super.transportDataReceived(new OkHttpReadableBuffer(frame), endOfStream);
}
@Override
protected void sendFrame(WritableBuffer frame, boolean endOfStream, boolean flush) {
checkState(id() != 0, "streamId should be set");
Buffer buffer;
if (frame == null) {
buffer = EMPTY_BUFFER;
} else {
buffer = ((OkHttpWritableBuffer) frame).buffer();
int size = (int) buffer.size();
if (size > 0) {
onSendingBytes(size);
}
}
// If buffer > frameWriter.maxDataLength() the flow-controller will ensure that it is
// properly chunked.
outboundFlow.data(endOfStream, id(), buffer, flush);
}
@Override
protected void returnProcessedBytes(int processedBytes) {
synchronized (lock) {
processedWindow -= processedBytes;
if (processedWindow <= WINDOW_UPDATE_THRESHOLD) {
int delta = Utils.DEFAULT_WINDOW_SIZE - processedWindow;
window += delta;
processedWindow += delta;
frameWriter.windowUpdate(id(), delta);
}
}
}
@Override
protected void sendCancel(Status reason) {
transport.finishStream(id(), reason, ErrorCode.CANCEL);
}
@Override
public void remoteEndClosed() {
super.remoteEndClosed();
if (canSend()) {
// If server's end-of-stream is received before client sends end-of-stream, we just send a
// reset to server to fully close the server side stream.
frameWriter.rstStream(id(), ErrorCode.CANCEL);
}
transport.finishStream(id(), null, null);
}
void setOutboundFlowState(Object outboundFlowState) {
this.outboundFlowState = outboundFlowState;
}
Object getOutboundFlowState() {
return outboundFlowState;
}
}
| bsd-3-clause |
davidi2/mopar | src/net/scapeemulator/game/model/player/inventory/InventoryAppearanceListener.java | 690 | package net.scapeemulator.game.model.player.inventory;
import net.scapeemulator.game.model.player.Item;
import net.scapeemulator.game.model.player.Player;
public final class InventoryAppearanceListener implements InventoryListener {
private final Player player;
public InventoryAppearanceListener(Player player) {
this.player = player;
}
@Override
public void itemChanged(Inventory inventory, int slot, Item item, Item oldItem) {
player.setAppearance(player.getAppearance());
}
@Override
public void itemsChanged(Inventory inventory) {
player.setAppearance(player.getAppearance());
}
@Override
public void capacityExceeded(Inventory inventory) {
/* empty */
}
}
| isc |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2019_09_01/src/main/java/com/microsoft/azure/management/network/v2019_09_01/ContainerNetworkInterfaceConfiguration.java | 4675 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_09_01;
import java.util.List;
import com.microsoft.azure.SubResource;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
/**
* Container network interface configuration child resource.
*/
@JsonFlatten
public class ContainerNetworkInterfaceConfiguration extends SubResource {
/**
* A list of ip configurations of the container network interface
* configuration.
*/
@JsonProperty(value = "properties.ipConfigurations")
private List<IPConfigurationProfile> ipConfigurations;
/**
* A list of container network interfaces created from this container
* network interface configuration.
*/
@JsonProperty(value = "properties.containerNetworkInterfaces")
private List<SubResource> containerNetworkInterfaces;
/**
* The provisioning state of the container network interface configuration
* resource. Possible values include: 'Succeeded', 'Updating', 'Deleting',
* 'Failed'.
*/
@JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY)
private ProvisioningState provisioningState;
/**
* The name of the resource. This name can be used to access the resource.
*/
@JsonProperty(value = "name")
private String name;
/**
* Sub Resource type.
*/
@JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY)
private String type;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
@JsonProperty(value = "etag", access = JsonProperty.Access.WRITE_ONLY)
private String etag;
/**
* Get a list of ip configurations of the container network interface configuration.
*
* @return the ipConfigurations value
*/
public List<IPConfigurationProfile> ipConfigurations() {
return this.ipConfigurations;
}
/**
* Set a list of ip configurations of the container network interface configuration.
*
* @param ipConfigurations the ipConfigurations value to set
* @return the ContainerNetworkInterfaceConfiguration object itself.
*/
public ContainerNetworkInterfaceConfiguration withIpConfigurations(List<IPConfigurationProfile> ipConfigurations) {
this.ipConfigurations = ipConfigurations;
return this;
}
/**
* Get a list of container network interfaces created from this container network interface configuration.
*
* @return the containerNetworkInterfaces value
*/
public List<SubResource> containerNetworkInterfaces() {
return this.containerNetworkInterfaces;
}
/**
* Set a list of container network interfaces created from this container network interface configuration.
*
* @param containerNetworkInterfaces the containerNetworkInterfaces value to set
* @return the ContainerNetworkInterfaceConfiguration object itself.
*/
public ContainerNetworkInterfaceConfiguration withContainerNetworkInterfaces(List<SubResource> containerNetworkInterfaces) {
this.containerNetworkInterfaces = containerNetworkInterfaces;
return this;
}
/**
* Get the provisioning state of the container network interface configuration resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'.
*
* @return the provisioningState value
*/
public ProvisioningState provisioningState() {
return this.provisioningState;
}
/**
* Get the name of the resource. This name can be used to access the resource.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Set the name of the resource. This name can be used to access the resource.
*
* @param name the name value to set
* @return the ContainerNetworkInterfaceConfiguration object itself.
*/
public ContainerNetworkInterfaceConfiguration withName(String name) {
this.name = name;
return this;
}
/**
* Get sub Resource type.
*
* @return the type value
*/
public String type() {
return this.type;
}
/**
* Get a unique read-only string that changes whenever the resource is updated.
*
* @return the etag value
*/
public String etag() {
return this.etag;
}
}
| mit |
kaituo/sedge | trunk/test/org/apache/pig/parser/TestErrorHandling.java | 11207 | /*
* 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.pig.parser;
import java.io.IOException;
import java.util.Properties;
import junit.framework.Assert;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.impl.logicalLayer.validators.TypeCheckerException;
import org.junit.Before;
import org.junit.Test;
public class TestErrorHandling {
private PigServer pig = null;
@Before
public void setUp() throws Exception{
pig = new PigServer(ExecType.LOCAL, new Properties());
pig.setValidateEachStatement(true);
}
@Test // Error from SchemaAliasVisitor
public void tesNegative1() {
String query = "A = load 'x' as ( u:int, v:long, u:chararray, w:bytearray );";
try {
pig.registerQuery( query );
} catch(Exception ex) {
System.out.println( ex.getMessage() );
Assert.assertTrue( ex.getMessage().contains( "line 1, column 33" ) );
return;
}
Assert.fail( "Testcase should fail" );
}
@Test // Error from ColumnAliasConversionVisitor
public void tesNegative2() {
String query = "A = load 'x' as ( u:int, v:long, w );\n" +
"B = foreach A generate $5;";
try {
pig.registerQuery( query );
} catch(Exception ex) {
System.out.println( ex.getMessage() );
Assert.assertTrue( ex.getMessage().contains( "line 2, column 23" ) );
return;
}
Assert.fail( "Testcase should fail" );
}
@Test // Error from ASTValidator
public void tesNegative3() throws IOException {
String query = "A = load 'x';\n" +
"C = limit B 100;";
try {
pig.registerQuery( query );
} catch(Exception ex) {
System.out.println( ex.getMessage() );
Assert.assertTrue( ex.getMessage().contains( "line 2, column 10" ) );
return;
}
Assert.fail( "Testcase should fail" );
}
@Test // Type checking error
public void tesNegative4() throws IOException {
String query = "A = load 'x' as ( u:int, v:chararray );\n" +
"C = foreach A generate u + v;";
try {
pig.registerQuery( query );
} catch(TypeCheckerException ex) {
System.out.println( ex.getCause().getMessage() );
Assert.assertTrue( ex.getCause().getMessage().contains( "line 2, column 25" ) );
return;
}
Assert.fail( "Testcase should fail" );
}
@Test // Type checking lineage error message
public void tesNegative5() throws IOException {
String query = "a = load 'a' using PigStorage('a') as (field1, field2: float, field3: chararray );\n" +
"b = load 'b' using PigStorage('b') as (field4, field5, field6: chararray );\n" +
"c = cogroup a by *, b by * ;\n" +
"d = foreach c generate group, flatten($1), flatten($2);\n" +
"e = foreach d generate group + 1, field1 + 1, field4 + 2.0;";
try {
pig.registerQuery( query );
} catch(TypeCheckerException ex) {
System.out.println( ex.getCause().getMessage() );
Assert.assertTrue( ex.getCause().getMessage().contains( "line 5, column 29" ) );
return;
}
Assert.fail( "Testcase should fail" );
}
@Test // Error from ScalarAliasVisitor
public void tesNegative6() {
String query = "A = load 'x';\n" +
"B = load 'y' as ( u : int, v : chararray );\n" +
"C = foreach A generate B.w, $0;\n" +
"D = store C into 'output';\n";
try {
pig.registerQuery( query );
} catch(Exception ex) {
System.out.println( ex.getMessage() );
Assert.assertTrue( ex.getMessage().contains( "line 3, column 23" ) );
return;
}
Assert.fail( "Testcase should fail" );
}
@Test // Error from InputOutputFileVisitor
public void tesNegative7() throws IOException {
String query = "A = load 'x';\n" +
"store A into 'fs2you://output';\n";
try {
pig.registerQuery( query );
} catch(FrontendException ex) {
System.out.println( ex.getCause().getMessage() );
Assert.assertTrue( ex.getCause().getMessage().contains( "line 2, column 0" ) );
return;
}
Assert.fail( "Testcase should fail" );
}
@Test // Error from InputOutputFileVisitor
public void tesNegative8() throws IOException {
String query = "A = load 'x' as ( a : bag{ T:tuple(u, v) }, c : int, d : long );\n" +
"B = foreach A { S = c * 2; T = limit S 100; generate T; };\n" +
"store B into 'y';";
try {
pig.registerQuery( query );
} catch(FrontendException ex) {
System.out.println( ex.getMessage() );
Assert.assertTrue( ex.getMessage().contains( "line 2, column 37" ) );
return;
}
Assert.fail( "Testcase should fail" );
}
@Test // PIG-1956, 1957
public void tesNegative9() throws IOException {
pig.registerQuery("a = load 'temp' as (a0:int, a1:int);\n");
pig.registerQuery("b = group a by a0;\n");
try {
pig.registerQuery("c = foreach b { " +
" c1 = foreach a { " +
" c11 = filter a by a1 > 0; " +
" generate c11; " +
" } " +
" generate c1; " +
" }\n");
} catch (FrontendException ex) {
String msg = ex.getMessage();
Assert.assertTrue( msg.contains( "line 5, column 32" ) );
Assert.assertTrue( msg.contains( "mismatched input '{' expecting GENERATE"));
return;
}
Assert.fail( "Testcase should fail" );
}
@Test
public void tesNegative10() throws IOException {
String query = "A = load 'x' as (u :int, v: chararray);\n" +
"B = load 'y';\n" +
"C = union onschema A, B;";
try {
pig.registerQuery( query );
} catch(FrontendException ex) {
System.out.println( ex.getMessage() );
Assert.assertTrue( ex.getMessage().contains( "line 3, column 4" ) );
Assert.assertTrue( ex.getMessage().contains(
"UNION ONSCHEMA cannot be used with relations that have null schema" ) );
return;
}
Assert.fail( "Testcase should fail" );
}
@Test // PIG-1961
public void tesNegative11() throws IOException {
String query = "A = load ^ 'x' as (name, age, gpa);\n";
try {
pig.registerQuery( query );
} catch(FrontendException ex) {
String msg = ex.getMessage();
System.out.println( msg );
Assert.assertFalse( msg.contains( "file null" ) );
Assert.assertTrue( msg.contains( "Unexpected character" ) );
return;
}
Assert.fail( "Testcase should fail" );
}
@Test // PIG-1961
public void tesNegative12() throws IOException {
String query = "A = loadd 'x' as (name, age, gpa);\n";
try {
pig.registerQuery( query );
} catch(FrontendException ex) {
String msg = ex.getMessage();
System.out.println( msg );
Assert.assertFalse( msg.contains( "file null" ) );
Assert.assertTrue( msg.contains( "mismatched input ''x'' expecting LEFT_PAREN" ) );
return;
}
Assert.fail( "Testcase should fail" );
}
@Test // PIG-1921
public void tesNegative13() throws IOException {
String query = "A = load 'x' as (u:int, v);\n" +
"B = load 'y';\n" +
"C = join A by u, B by w;";
try {
pig.registerQuery( query );
} catch(FrontendException ex) {
String msg = ex.getMessage();
System.out.println( msg );
Assert.assertTrue( !msg.contains( "null") );
Assert.assertTrue( msg.contains( "Projected field [w] does not exist.") );
return;
}
Assert.fail( "Testcase should fail" );
}
@Test //pig-2267
public void testAutomaticallyGivenSchemaName1() throws IOException{
String query = "a = load 'x' as (int,val_0);";
String failMsg = "Duplicated alias in schema";
shouldFailWithMessage(query,failMsg);
}
@Test //pig-2267
public void testAutomaticallyGivenSchemaName2() throws IOException{
String query = "a = load 'x' as ((int,int),tuple_0:tuple(int,int));";
String failMsg = "Duplicated alias in schema";
shouldFailWithMessage(query,failMsg);
}
@Test //pig-2267
public void testAutomaticallyGivenSchemaName3() throws IOException{
String query = "a = load 'x' as (tuple_0:tuple(int,int),(int,int));";
String failMsg = "Duplicated alias in schema";
shouldFailWithMessage(query,failMsg);
}
@Test //pig-2267
public void testAutomaticallyGivenSchemaName4() throws IOException{
String query = "a = load 'x' as (bag_0:bag{},{});";
String failMsg = "Duplicated alias in schema";
shouldFailWithMessage(query,failMsg);
}
@Test //pig-2267
public void testAutomaticallyGivenSchemaName5() throws IOException{
String query = "a = load 'x' as ([],map_0:map[]);";
String failMsg = "Duplicated alias in schema";
shouldFailWithMessage(query,failMsg);
}
@Test //pig-2267
public void testAutomaticallyGivenSchemaName6() throws IOException{
String query = "a = load 'x' as (int,int,int,val_3,val_2);";
String failMsg = "Duplicated alias in schema";
shouldFailWithMessage(query,failMsg);
}
public void shouldFailWithMessage(String query, String... messages) throws IOException {
try {
pig.registerQuery(query);
} catch (Exception e) {
String msg = e.getMessage();
System.out.println(msg);
for (String message : messages) {
Assert.assertTrue(msg.contains(message));
}
return;
}
Assert.fail("Testcase should fail");
}
}
| mit |
hpe-idol/haven-search-components | idol/src/test/java/com/hp/autonomy/searchcomponents/idol/search/IdolDocumentsServiceTest.java | 8085 | /*
* (c) Copyright 2015-2017 Micro Focus or one of its affiliates.
*
* Licensed under the MIT License (the "License"); you may not use this file
* except in compliance with the License.
*
* The only warranties for products and services of Micro Focus and its affiliates
* and licensors ("Micro Focus") are as may be set forth in the express warranty
* statements accompanying such products and services. Nothing herein should be
* construed as constituting an additional warranty. Micro Focus shall not be
* liable for technical or editorial errors or omissions contained herein. The
* information contained herein is subject to change without notice.
*/
package com.hp.autonomy.searchcomponents.idol.search;
import com.autonomy.aci.client.util.AciParameters;
import com.hp.autonomy.searchcomponents.core.search.QueryRequest;
import com.hp.autonomy.searchcomponents.core.search.StateTokenAndResultCount;
import com.hp.autonomy.types.idol.responses.Hit;
import com.hp.autonomy.types.idol.responses.QueryResponseData;
import com.hp.autonomy.types.idol.responses.SuggestResponseData;
import com.hp.autonomy.types.requests.Documents;
import com.hp.autonomy.types.requests.idol.actions.query.params.PrintParam;
import com.hp.autonomy.types.requests.idol.actions.query.params.SummaryParam;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Collections;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.hamcrest.core.Is.is;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@SuppressWarnings("WeakerAccess")
@RunWith(MockitoJUnitRunner.class)
public class IdolDocumentsServiceTest {
private static final String MOCK_STATE_TOKEN = "mock-state-token";
private static final int MOCK_TOTAL_HITS = 42;
@Mock
private HavenSearchAciParameterHandler parameterHandler;
@Mock
private QueryExecutor queryExecutor;
@Mock
private QueryResponseParser queryResponseParser;
@Mock
private IdolQueryRestrictions queryRestrictions;
@Mock
private IdolQueryRequest queryRequest;
@Mock
private IdolSuggestRequest suggestRequest;
@Mock
private IdolGetContentRequest getContentRequest;
@Mock
private IdolGetContentRequestIndex getContentRequestIndex;
private IdolDocumentsService idolDocumentsService;
@Before
public void setUp() {
idolDocumentsService = new IdolDocumentsServiceImpl(parameterHandler, queryExecutor, queryResponseParser);
}
@Test
public void queryContent() {
when(queryExecutor.performQuery(any())).thenReturn(true);
final QueryResponseData responseData = new QueryResponseData();
when(queryExecutor.executeQuery(any(), any())).thenReturn(responseData);
idolDocumentsService.queryTextIndex(mockQueryParams(QueryRequest.QueryType.RAW));
verify(queryResponseParser).parseQueryResults(any(), any(AciParameters.class), eq(responseData), any());
}
@Test
public void queryQms() {
when(queryExecutor.performQuery(any())).thenReturn(true);
final QueryResponseData responseData = new QueryResponseData();
when(queryExecutor.executeQuery(any(), any())).thenReturn(responseData);
idolDocumentsService.queryTextIndex(mockQueryParams(QueryRequest.QueryType.MODIFIED));
verify(queryResponseParser).parseQueryResults(any(), any(AciParameters.class), eq(responseData), any());
}
@Test
public void queryContentForPromotions() {
final Documents<IdolSearchResult> results = idolDocumentsService.queryTextIndex(mockQueryParams(QueryRequest.QueryType.PROMOTIONS));
assertThat(results.getDocuments(), is(empty()));
}
@Test
public void queryQmsForPromotions() {
when(queryExecutor.performQuery(any())).thenReturn(true);
final QueryResponseData responseData = new QueryResponseData();
when(queryExecutor.executeQuery(any(), any())).thenReturn(responseData);
idolDocumentsService.queryTextIndex(mockQueryParams(QueryRequest.QueryType.PROMOTIONS));
verify(queryResponseParser).parseQueryResults(any(), any(AciParameters.class), eq(responseData), any());
}
@Test
public void findSimilar() {
final SuggestResponseData responseData = new SuggestResponseData();
responseData.setTotalhits(1);
final Hit hit = new Hit();
responseData.getHits().add(hit);
when(queryExecutor.executeSuggest(any(), any())).thenReturn(responseData);
when(suggestRequest.getReference()).thenReturn("Some reference");
when(suggestRequest.getQueryRestrictions()).thenReturn(queryRestrictions);
idolDocumentsService.findSimilar(suggestRequest);
verify(queryResponseParser).parseQueryHits(responseData.getHits());
}
@Test
public void getContent() {
final QueryResponseData responseData = new QueryResponseData();
responseData.setTotalhits(1);
final Hit hit = new Hit();
responseData.getHits().add(hit);
when(queryExecutor.executeQuery(any(), any())).thenReturn(responseData);
when(getContentRequestIndex.getIndex()).thenReturn("Database1");
when(getContentRequestIndex.getReferences()).thenReturn(Collections.singleton("Some reference"));
when(getContentRequest.getIndexesAndReferences()).thenReturn(Collections.singleton(getContentRequestIndex));
when(getContentRequest.getPrint()).thenReturn(PrintParam.Fields);
idolDocumentsService.getDocumentContent(getContentRequest);
verify(queryResponseParser).parseQueryHits(responseData.getHits());
}
@Test
public void getStateToken() {
when(queryExecutor.executeQuery(any(), any())).thenReturn(mockStateTokenResponse());
final String stateToken = idolDocumentsService.getStateToken(mockQueryParams(QueryRequest.QueryType.RAW).getQueryRestrictions(), 3, false);
assertThat(stateToken, is(MOCK_STATE_TOKEN));
}
@Test
public void getStateTokenAndResultCount() {
when(queryExecutor.executeQuery(any(), any())).thenReturn(mockStateTokenResponse());
final StateTokenAndResultCount stateTokenAndResultCount = idolDocumentsService.getStateTokenAndResultCount(mockQueryParams(QueryRequest.QueryType.RAW).getQueryRestrictions(), 3, false);
assertThat(stateTokenAndResultCount.getTypedStateToken().getStateToken(), is(MOCK_STATE_TOKEN));
assertThat(stateTokenAndResultCount.getResultCount(), is((long)MOCK_TOTAL_HITS));
}
private IdolQueryRequest mockQueryParams(final QueryRequest.QueryType queryType) {
when(queryRestrictions.getQueryText()).thenReturn("*");
when(queryRestrictions.getDatabases()).thenReturn(Arrays.asList("Database1", "Database2"));
when(queryRestrictions.getMaxDate()).thenReturn(ZonedDateTime.now());
when(queryRequest.getQueryRestrictions()).thenReturn(queryRestrictions);
when(queryRequest.getStart()).thenReturn(1);
when(queryRequest.getMaxResults()).thenReturn(50);
when(queryRequest.getSummary()).thenReturn(SummaryParam.Concept.name());
when(queryRequest.getSummaryCharacters()).thenReturn(250);
when(queryRequest.isHighlight()).thenReturn(true);
when(queryRequest.isAutoCorrect()).thenReturn(true);
when(queryRequest.getPrint()).thenReturn(PrintParam.Fields.name());
when(queryRequest.getQueryType()).thenReturn(queryType);
return queryRequest;
}
private QueryResponseData mockStateTokenResponse() {
final QueryResponseData responseData = new QueryResponseData();
responseData.setState(MOCK_STATE_TOKEN);
responseData.setTotalhits(MOCK_TOTAL_HITS);
return responseData;
}
}
| mit |