hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
4bee67ce37d43cd42644c4ede9180acedf8554f1
1,523
package org.eatsy.appservice.service; import org.eatsy.appservice.model.RecipeModel; import java.util.List; /** * Interface for interacting with recipes */ public interface RecipeFactory { /** * Retrieves all recipe model objects. * * @return The list of all recipe model objects that exist. */ List<RecipeModel> retrieveAllRecipes(); /** * Creates a new recipe model object * * @param recipeModel the recipe model that will be used to create a recipe domain object * @return a recipe model object containing the data from the newly created recipe domain object */ RecipeModel createRecipe(RecipeModel recipeModel); /** * Deletes the requested recipeModel * * @param recipeKey the ID for the recipe model that will be deleted from the recipe book * @return the list of existing recipe models that will have been updated to remove recipeKey */ List<RecipeModel> deleteRecipe(String recipeKey); /** * Replaces the existing recipe with the updated version supplied. * * @param recipeModelWithUpdates the recipe model with the updated changes to be persisted. * @param recipeKey the unique ID of the recipe. This will allow the recipe that needs to be * updated to be identified. * @return the updated recipeModel with the new updates/changes applied. */ RecipeModel updateRecipe(String recipeKey, RecipeModel recipeModelWithUpdates); }
33.108696
109
0.688772
632c60988a0383e51e006cfd31aa380cef168c7d
4,193
package me.sam.czxing; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import me.devilsen.czxing.code.BarcodeReader; import me.devilsen.czxing.code.BarcodeWriter; import me.devilsen.czxing.code.CodeResult; import me.devilsen.czxing.util.BarCodeUtil; /** * desc : 生成二维码演示 * date : 2019-07-22 18:25 * * @author : dongSen */ public class WriteQRCodeActivity extends AppCompatActivity implements View.OnClickListener { private EditText textEdit; private ImageView qrcodeImage; private BarcodeWriter writer; private BarcodeReader reader; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_write_code_2); textEdit = findViewById(R.id.edit_write_qr_code); Button writeBtn = findViewById(R.id.button_write_qr_code); qrcodeImage = findViewById(R.id.image_view_write_qr_code); writer = new BarcodeWriter(); reader = BarcodeReader.getInstance(); writeBtn.setOnClickListener(this); qrcodeImage.setOnClickListener(this); onWrite(); } public void onWrite() { String text = textEdit.getText().toString(); writeAsync(text, qrcodeImage); } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.button_write_qr_code) { onWrite(); } else if (id == R.id.image_view_write_qr_code) { BitmapDrawable drawable = (BitmapDrawable) qrcodeImage.getDrawable(); Bitmap bitmap = drawable.getBitmap(); read(bitmap); } } public void read(Bitmap bitmap) { CodeResult result = null; for (int i = 0; i < 400; i++) { result = reader.read(bitmap); } if (result != null) { Toast.makeText(this, result.getText(), Toast.LENGTH_SHORT).show(); } } /** * 生成二维码 * <p> * 生成二维码是耗时操作,请务必放在子线程中执行 * * @param text 文本 * @param imageView 生成图片 */ private void writeAsync(final String text, final ImageView imageView) { if (TextUtils.isEmpty(text)) { return; } Observable .create(new ObservableOnSubscribe<Bitmap>() { @Override public void subscribe(ObservableEmitter<Bitmap> emitter) { Bitmap bitmap = writer.write(text, BarCodeUtil.dp2px(WriteQRCodeActivity.this, 200), Color.BLACK); if (bitmap != null) { emitter.onNext(bitmap); } emitter.onComplete(); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Bitmap>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Bitmap bitmap) { imageView.setImageBitmap(bitmap); } @Override public void onError(Throwable e) { Log.e("Write", "生成失败"); } @Override public void onComplete() { } }); } }
29.95
92
0.5886
1de63ea6b0dbf0a7125f91f55bb321c576fe211d
1,686
/* * 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.aliyuncs.objectdet.transform.v20191230; import com.aliyuncs.objectdet.model.v20191230.DetectMainBodyResponse; import com.aliyuncs.objectdet.model.v20191230.DetectMainBodyResponse.Data; import com.aliyuncs.objectdet.model.v20191230.DetectMainBodyResponse.Data.Location; import com.aliyuncs.transform.UnmarshallerContext; public class DetectMainBodyResponseUnmarshaller { public static DetectMainBodyResponse unmarshall(DetectMainBodyResponse detectMainBodyResponse, UnmarshallerContext _ctx) { detectMainBodyResponse.setRequestId(_ctx.stringValue("DetectMainBodyResponse.RequestId")); Data data = new Data(); Location location = new Location(); location.setWidth(_ctx.integerValue("DetectMainBodyResponse.Data.Location.Width")); location.setHeight(_ctx.integerValue("DetectMainBodyResponse.Data.Location.Height")); location.setY(_ctx.integerValue("DetectMainBodyResponse.Data.Location.Y")); location.setX(_ctx.integerValue("DetectMainBodyResponse.Data.Location.X")); data.setLocation(location); detectMainBodyResponse.setData(data); return detectMainBodyResponse; } }
41.121951
123
0.794781
58fd62c74c113edea921a86b9edef7627cf1c1db
320
package com.example.system; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; /** * @Auther: Administrator * @Date: 2018/10/24 15:49 * @Description: */ @Component public class PreDestory { @PreDestroy public void destory(){ System.out.println("程序退出"); } }
15.238095
48
0.6875
40dda4adec952d4e9c2cb631fd34942361e4c11d
3,656
package cn.compose.admin.entity; import java.io.Serializable; import java.util.Date; public class Source implements Serializable { private Long id; private Long sourceGroupId; private String sign; private String name; private Integer partitionNumber; private Integer replicationFactor; private String hashKey; private String keyTypeMapping; private Date lastInputTime; private String remark; private Date createTime; private Date updateTime; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getSourceGroupId() { return sourceGroupId; } public void setSourceGroupId(Long sourceGroupId) { this.sourceGroupId = sourceGroupId; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign == null ? null : sign.trim(); } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public Integer getPartitionNumber() { return partitionNumber; } public void setPartitionNumber(Integer partitionNumber) { this.partitionNumber = partitionNumber; } public Integer getReplicationFactor() { return replicationFactor; } public void setReplicationFactor(Integer replicationFactor) { this.replicationFactor = replicationFactor; } public String getHashKey() { return hashKey; } public void setHashKey(String hashKey) { this.hashKey = hashKey == null ? null : hashKey.trim(); } public String getKeyTypeMapping() { return keyTypeMapping; } public void setKeyTypeMapping(String keyTypeMapping) { this.keyTypeMapping = keyTypeMapping == null ? null : keyTypeMapping.trim(); } public Date getLastInputTime() { return lastInputTime; } public void setLastInputTime(Date lastInputTime) { this.lastInputTime = lastInputTime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", sourceGroupId=").append(sourceGroupId); sb.append(", sign=").append(sign); sb.append(", name=").append(name); sb.append(", partitionNumber=").append(partitionNumber); sb.append(", replicationFactor=").append(replicationFactor); sb.append(", hashKey=").append(hashKey); sb.append(", keyTypeMapping=").append(keyTypeMapping); sb.append(", lastInputTime=").append(lastInputTime); sb.append(", remark=").append(remark); sb.append(", createTime=").append(createTime); sb.append(", updateTime=").append(updateTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
24.211921
84
0.628556
08c86dd1e56d9da6d00d98ac177949bd21f63453
80,790
/* * 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.ambari.server.controller.internal; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileInputStream; import java.lang.reflect.Field; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.ambari.server.AmbariException; import org.apache.ambari.server.H2DatabaseCleaner; import org.apache.ambari.server.Role; import org.apache.ambari.server.RoleCommand; import org.apache.ambari.server.actionmanager.ActionManager; import org.apache.ambari.server.actionmanager.ExecutionCommandWrapper; import org.apache.ambari.server.actionmanager.HostRoleCommand; import org.apache.ambari.server.actionmanager.HostRoleStatus; import org.apache.ambari.server.actionmanager.Stage; import org.apache.ambari.server.agent.ExecutionCommand; import org.apache.ambari.server.agent.ExecutionCommand.KeyNames; import org.apache.ambari.server.audit.AuditLogger; import org.apache.ambari.server.configuration.Configuration; import org.apache.ambari.server.controller.AmbariManagementController; import org.apache.ambari.server.controller.AmbariServer; import org.apache.ambari.server.controller.ResourceProviderFactory; import org.apache.ambari.server.controller.spi.Predicate; import org.apache.ambari.server.controller.spi.Request; import org.apache.ambari.server.controller.spi.RequestStatus; import org.apache.ambari.server.controller.spi.Resource; import org.apache.ambari.server.controller.spi.Resource.Type; import org.apache.ambari.server.controller.spi.ResourceProvider; import org.apache.ambari.server.controller.spi.SystemException; import org.apache.ambari.server.controller.utilities.PredicateBuilder; import org.apache.ambari.server.controller.utilities.PropertyHelper; import org.apache.ambari.server.events.publishers.AmbariEventPublisher; import org.apache.ambari.server.orm.GuiceJpaInitializer; import org.apache.ambari.server.orm.InMemoryDefaultTestModule; import org.apache.ambari.server.orm.dao.HostRoleCommandDAO; import org.apache.ambari.server.orm.dao.RepositoryVersionDAO; import org.apache.ambari.server.orm.dao.RequestDAO; import org.apache.ambari.server.orm.dao.StackDAO; import org.apache.ambari.server.orm.dao.StageDAO; import org.apache.ambari.server.orm.dao.UpgradeDAO; import org.apache.ambari.server.orm.entities.HostRoleCommandEntity; import org.apache.ambari.server.orm.entities.RepositoryVersionEntity; import org.apache.ambari.server.orm.entities.RequestEntity; import org.apache.ambari.server.orm.entities.StackEntity; import org.apache.ambari.server.orm.entities.StageEntity; import org.apache.ambari.server.orm.entities.UpgradeEntity; import org.apache.ambari.server.orm.entities.UpgradeGroupEntity; import org.apache.ambari.server.orm.entities.UpgradeHistoryEntity; import org.apache.ambari.server.orm.entities.UpgradeItemEntity; import org.apache.ambari.server.security.TestAuthenticationFactory; import org.apache.ambari.server.serveraction.upgrades.AutoSkipFailedSummaryAction; import org.apache.ambari.server.state.Cluster; import org.apache.ambari.server.state.Clusters; import org.apache.ambari.server.state.Config; import org.apache.ambari.server.state.ConfigFactory; import org.apache.ambari.server.state.ConfigHelper; import org.apache.ambari.server.state.Host; import org.apache.ambari.server.state.HostState; import org.apache.ambari.server.state.RepositoryType; import org.apache.ambari.server.state.Service; import org.apache.ambari.server.state.ServiceComponent; import org.apache.ambari.server.state.ServiceComponentHost; import org.apache.ambari.server.state.StackId; import org.apache.ambari.server.state.UpgradeContext; import org.apache.ambari.server.state.UpgradeHelper; import org.apache.ambari.server.state.UpgradeState; import org.apache.ambari.server.state.stack.upgrade.Direction; import org.apache.ambari.server.state.stack.upgrade.UpgradeType; import org.apache.ambari.server.topology.TopologyManager; import org.apache.ambari.server.utils.StageUtils; import org.apache.ambari.server.view.ViewRegistry; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.easymock.EasyMock; import org.easymock.EasyMockSupport; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.security.core.context.SecurityContextHolder; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.util.Modules; /** * UpgradeResourceDefinition tests. */ public class UpgradeResourceProviderTest extends EasyMockSupport { private UpgradeDAO upgradeDao = null; private RequestDAO requestDao = null; private RepositoryVersionDAO repoVersionDao = null; private Injector injector; private Clusters clusters; private AmbariManagementController amc; private ConfigHelper configHelper; private StackDAO stackDAO; private TopologyManager topologyManager; private ConfigFactory configFactory; private HostRoleCommandDAO hrcDAO; RepositoryVersionEntity repoVersionEntity2110; RepositoryVersionEntity repoVersionEntity2111; RepositoryVersionEntity repoVersionEntity2112; RepositoryVersionEntity repoVersionEntity2200; /** * Creates a single host cluster with ZOOKEEPER_SERVER and ZOOKEEPER_CLIENT on * {@link #repoVersionEntity2110}. * * @throws Exception */ @Before public void before() throws Exception { SecurityContextHolder.getContext().setAuthentication( TestAuthenticationFactory.createAdministrator()); // setup the config helper for placeholder resolution configHelper = EasyMock.createNiceMock(ConfigHelper.class); expect( configHelper.getPlaceholderValueFromDesiredConfigurations( EasyMock.anyObject(Cluster.class), EasyMock.eq("{{foo/bar}}"))).andReturn( "placeholder-rendered-properly").anyTimes(); expect( configHelper.getDefaultProperties(EasyMock.anyObject(StackId.class), EasyMock.anyString())).andReturn( new HashMap<String, Map<String, String>>()).anyTimes(); replay(configHelper); InMemoryDefaultTestModule module = new InMemoryDefaultTestModule(); // create an injector which will inject the mocks injector = Guice.createInjector( Modules.override(module).with(new MockModule())); H2DatabaseCleaner.resetSequences(injector); injector.getInstance(GuiceJpaInitializer.class); amc = injector.getInstance(AmbariManagementController.class); configFactory = injector.getInstance(ConfigFactory.class); Field field = AmbariServer.class.getDeclaredField("clusterController"); field.setAccessible(true); field.set(null, amc); stackDAO = injector.getInstance(StackDAO.class); upgradeDao = injector.getInstance(UpgradeDAO.class); requestDao = injector.getInstance(RequestDAO.class); repoVersionDao = injector.getInstance(RepositoryVersionDAO.class); hrcDAO = injector.getInstance(HostRoleCommandDAO.class); AmbariEventPublisher publisher = EasyMock.createNiceMock(AmbariEventPublisher.class); replay(publisher); ViewRegistry.initInstance(new ViewRegistry(publisher)); // TODO AMARI-12698, this file is attempting to check RU on version 2.1.1, which doesn't support it // because it has no upgrade packs. We should use correct versions that have stacks. // For now, Ignore the tests that fail. StackEntity stackEntity211 = stackDAO.find("HDP", "2.1.1"); StackEntity stackEntity220 = stackDAO.find("HDP", "2.2.0"); StackId stack211 = new StackId(stackEntity211); repoVersionEntity2110 = new RepositoryVersionEntity(); repoVersionEntity2110.setDisplayName("My New Version 1"); repoVersionEntity2110.setOperatingSystems(""); repoVersionEntity2110.setStack(stackEntity211); repoVersionEntity2110.setVersion("2.1.1.0"); repoVersionDao.create(repoVersionEntity2110); repoVersionEntity2111 = new RepositoryVersionEntity(); repoVersionEntity2111.setDisplayName("My New Version 2 for minor upgrade"); repoVersionEntity2111.setOperatingSystems(""); repoVersionEntity2111.setStack(stackEntity211); repoVersionEntity2111.setVersion("2.1.1.1"); repoVersionDao.create(repoVersionEntity2111); repoVersionEntity2112 = new RepositoryVersionEntity(); repoVersionEntity2112.setDisplayName("My New Version 3 for patch upgrade"); repoVersionEntity2112.setOperatingSystems(""); repoVersionEntity2112.setStack(stackEntity211); repoVersionEntity2112.setVersion("2.1.1.2"); repoVersionEntity2112.setType(RepositoryType.PATCH); repoVersionEntity2112.setVersionXml(""); repoVersionDao.create(repoVersionEntity2112); repoVersionEntity2200 = new RepositoryVersionEntity(); repoVersionEntity2200.setDisplayName("My New Version 4 for major upgrade"); repoVersionEntity2200.setOperatingSystems(""); repoVersionEntity2200.setStack(stackEntity220); repoVersionEntity2200.setVersion("2.2.0.0"); repoVersionDao.create(repoVersionEntity2200); clusters = injector.getInstance(Clusters.class); clusters.addCluster("c1", stack211); Cluster cluster = clusters.getCluster("c1"); clusters.addHost("h1"); Host host = clusters.getHost("h1"); Map<String, String> hostAttributes = new HashMap<>(); hostAttributes.put("os_family", "redhat"); hostAttributes.put("os_release_version", "6.3"); host.setHostAttributes(hostAttributes); host.setState(HostState.HEALTHY); clusters.mapHostToCluster("h1", "c1"); // add a single ZK server and client on 2.1.1.0 Service service = cluster.addService("ZOOKEEPER", repoVersionEntity2110); ServiceComponent component = service.addServiceComponent("ZOOKEEPER_SERVER"); ServiceComponentHost sch = component.addServiceComponentHost("h1"); sch.setVersion("2.1.1.0"); component = service.addServiceComponent("ZOOKEEPER_CLIENT"); sch = component.addServiceComponentHost("h1"); sch.setVersion("2.1.1.0"); Configuration configuration = injector.getInstance(Configuration.class); configuration.setProperty("upgrade.parameter.zk-server.timeout", "824"); topologyManager = injector.getInstance(TopologyManager.class); StageUtils.setTopologyManager(topologyManager); StageUtils.setConfiguration(configuration); ActionManager.setTopologyManager(topologyManager); EasyMock.replay(injector.getInstance(AuditLogger.class)); } @After public void after() throws AmbariException, SQLException { H2DatabaseCleaner.clearDatabaseAndStopPersistenceService(injector); EasyMock.reset(injector.getInstance(AuditLogger.class)); injector = null; } /** * Obtain request id from the {@code RequestStatus} * @param requestStatus reqult of the {@code createResources} * @return id of the request */ private long getRequestId(RequestStatus requestStatus){ assertEquals(1, requestStatus.getAssociatedResources().size()); Resource r = requestStatus.getAssociatedResources().iterator().next(); String id = r.getPropertyValue("Upgrade/request_id").toString(); return Long.parseLong(id); } @Test public void testCreateResourcesWithAutoSkipFailures() throws Exception { Cluster cluster = clusters.getCluster("c1"); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2200.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_TYPE, UpgradeType.ROLLING.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_FAILURES, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_SC_FAILURES, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_MANUAL_VERIFICATION, Boolean.FALSE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); upgradeResourceProvider.createResources(request); List<UpgradeEntity> upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(1, upgrades.size()); UpgradeEntity entity = upgrades.get(0); assertEquals(cluster.getClusterId(), entity.getClusterId().longValue()); List<UpgradeGroupEntity> upgradeGroups = entity.getUpgradeGroups(); assertEquals(3, upgradeGroups.size()); UpgradeGroupEntity preClusterGroup = upgradeGroups.get(0); assertEquals("PRE_CLUSTER", preClusterGroup.getName()); List<UpgradeItemEntity> preClusterUpgradeItems = preClusterGroup.getItems(); assertEquals(2, preClusterUpgradeItems.size()); assertEquals("Foo", parseSingleMessage(preClusterUpgradeItems.get(0).getText())); assertEquals("Foo", parseSingleMessage(preClusterUpgradeItems.get(1).getText())); UpgradeGroupEntity zookeeperGroup = upgradeGroups.get(1); assertEquals("ZOOKEEPER", zookeeperGroup.getName()); List<UpgradeItemEntity> zookeeperUpgradeItems = zookeeperGroup.getItems(); assertEquals(5, zookeeperUpgradeItems.size()); assertEquals("This is a manual task with a placeholder of placeholder-rendered-properly", parseSingleMessage(zookeeperUpgradeItems.get(0).getText())); assertEquals("Restarting ZooKeeper Server on h1", zookeeperUpgradeItems.get(1).getText()); assertEquals("Updating configuration zookeeper-newconfig", zookeeperUpgradeItems.get(2).getText()); assertEquals("Service Check ZooKeeper", zookeeperUpgradeItems.get(3).getText()); assertTrue(zookeeperUpgradeItems.get(4).getText().contains("There are failures that were automatically skipped")); // the last upgrade item is the skipped failure check UpgradeItemEntity skippedFailureCheck = zookeeperUpgradeItems.get(zookeeperUpgradeItems.size() - 1); skippedFailureCheck.getTasks().contains(AutoSkipFailedSummaryAction.class.getName()); UpgradeGroupEntity postClusterGroup = upgradeGroups.get(2); assertEquals("POST_CLUSTER", postClusterGroup.getName()); List<UpgradeItemEntity> postClusterUpgradeItems = postClusterGroup.getItems(); assertEquals(2, postClusterUpgradeItems.size()); assertEquals("Please confirm you are ready to finalize", parseSingleMessage(postClusterUpgradeItems.get(0).getText())); assertEquals("Save Cluster State", postClusterUpgradeItems.get(1).getText()); } @Test public void testCreateResourcesWithAutoSkipManualVerification() throws Exception { Cluster cluster = clusters.getCluster("c1"); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2200.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_TYPE, UpgradeType.ROLLING.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_MANUAL_VERIFICATION, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); upgradeResourceProvider.createResources(request); List<UpgradeEntity> upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(1, upgrades.size()); UpgradeEntity entity = upgrades.get(0); assertEquals(cluster.getClusterId(), entity.getClusterId().longValue()); List<UpgradeGroupEntity> upgradeGroups = entity.getUpgradeGroups(); assertEquals(2, upgradeGroups.size()); UpgradeGroupEntity zookeeperGroup = upgradeGroups.get(0); assertEquals("ZOOKEEPER", zookeeperGroup.getName()); List<UpgradeItemEntity> zookeeperUpgradeItems = zookeeperGroup.getItems(); assertEquals(3, zookeeperUpgradeItems.size()); assertEquals("Restarting ZooKeeper Server on h1", zookeeperUpgradeItems.get(0).getText()); assertEquals("Updating configuration zookeeper-newconfig", zookeeperUpgradeItems.get(1).getText()); assertEquals("Service Check ZooKeeper", zookeeperUpgradeItems.get(2).getText()); UpgradeGroupEntity postClusterGroup = upgradeGroups.get(1); assertEquals("POST_CLUSTER", postClusterGroup.getName()); List<UpgradeItemEntity> postClusterUpgradeItems = postClusterGroup.getItems(); assertEquals(1, postClusterUpgradeItems.size()); assertEquals("Save Cluster State", postClusterUpgradeItems.get(0).getText()); } @Test public void testCreateResourcesWithAutoSkipAll() throws Exception { Cluster cluster = clusters.getCluster("c1"); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2200.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_TYPE, UpgradeType.ROLLING.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_FAILURES, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_SC_FAILURES, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_MANUAL_VERIFICATION, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); upgradeResourceProvider.createResources(request); List<UpgradeEntity> upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(1, upgrades.size()); UpgradeEntity entity = upgrades.get(0); assertEquals(cluster.getClusterId(), entity.getClusterId().longValue()); List<UpgradeGroupEntity> upgradeGroups = entity.getUpgradeGroups(); assertEquals(2, upgradeGroups.size()); UpgradeGroupEntity zookeeperGroup = upgradeGroups.get(0); assertEquals("ZOOKEEPER", zookeeperGroup.getName()); List<UpgradeItemEntity> zookeeperUpgradeItems = zookeeperGroup.getItems(); assertEquals(4, zookeeperUpgradeItems.size()); assertEquals("Restarting ZooKeeper Server on h1", zookeeperUpgradeItems.get(0).getText()); assertEquals("Updating configuration zookeeper-newconfig", zookeeperUpgradeItems.get(1).getText()); assertEquals("Service Check ZooKeeper", zookeeperUpgradeItems.get(2).getText()); assertTrue(zookeeperUpgradeItems.get(3).getText().contains("There are failures that were automatically skipped")); // the last upgrade item is the skipped failure check UpgradeItemEntity skippedFailureCheck = zookeeperUpgradeItems.get(zookeeperUpgradeItems.size() - 1); skippedFailureCheck.getTasks().contains(AutoSkipFailedSummaryAction.class.getName()); UpgradeGroupEntity postClusterGroup = upgradeGroups.get(1); assertEquals("POST_CLUSTER", postClusterGroup.getName()); List<UpgradeItemEntity> postClusterUpgradeItems = postClusterGroup.getItems(); assertEquals(1, postClusterUpgradeItems.size()); assertEquals("Save Cluster State", postClusterUpgradeItems.get(0).getText()); } @Test public void testGetResources() throws Exception { RequestStatus status = testCreateResources(); Set<Resource> createdResources = status.getAssociatedResources(); assertEquals(1, createdResources.size()); Resource res = createdResources.iterator().next(); Long id = (Long) res.getPropertyValue("Upgrade/request_id"); assertNotNull(id); assertEquals(Long.valueOf(1), id); // upgrade Set<String> propertyIds = new HashSet<>(); propertyIds.add("Upgrade"); Predicate predicate = new PredicateBuilder() .property(UpgradeResourceProvider.UPGRADE_REQUEST_ID).equals("1").and() .property(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME).equals("c1") .toPredicate(); Request request = PropertyHelper.getReadRequest(propertyIds); ResourceProvider upgradeResourceProvider = createProvider(amc); Set<Resource> resources = upgradeResourceProvider.getResources(request, predicate); assertEquals(1, resources.size()); res = resources.iterator().next(); assertNotNull(res.getPropertyValue("Upgrade/progress_percent")); assertNotNull(res.getPropertyValue(UpgradeResourceProvider.UPGRADE_DIRECTION)); assertEquals(Direction.UPGRADE, res.getPropertyValue(UpgradeResourceProvider.UPGRADE_DIRECTION)); assertEquals(false, res.getPropertyValue(UpgradeResourceProvider.UPGRADE_SKIP_FAILURES)); assertEquals(false, res.getPropertyValue(UpgradeResourceProvider.UPGRADE_SKIP_SC_FAILURES)); assertEquals(UpgradeType.ROLLING, res.getPropertyValue(UpgradeResourceProvider.UPGRADE_TYPE)); // upgrade groups propertyIds.clear(); propertyIds.add("UpgradeGroup"); predicate = new PredicateBuilder() .property(UpgradeGroupResourceProvider.UPGRADE_REQUEST_ID).equals("1").and() .property(UpgradeGroupResourceProvider.UPGRADE_CLUSTER_NAME).equals("c1") .toPredicate(); request = PropertyHelper.getReadRequest(propertyIds); ResourceProvider upgradeGroupResourceProvider = new UpgradeGroupResourceProvider(amc); resources = upgradeGroupResourceProvider.getResources(request, predicate); assertEquals(3, resources.size()); res = resources.iterator().next(); assertNotNull(res.getPropertyValue("UpgradeGroup/status")); assertNotNull(res.getPropertyValue("UpgradeGroup/group_id")); assertNotNull(res.getPropertyValue("UpgradeGroup/total_task_count")); assertNotNull(res.getPropertyValue("UpgradeGroup/in_progress_task_count")); assertNotNull(res.getPropertyValue("UpgradeGroup/completed_task_count")); // upgrade items propertyIds.clear(); propertyIds.add("UpgradeItem"); predicate = new PredicateBuilder() .property(UpgradeItemResourceProvider.UPGRADE_GROUP_ID).equals("1").and() .property(UpgradeItemResourceProvider.UPGRADE_REQUEST_ID).equals("1").and() .property(UpgradeItemResourceProvider.UPGRADE_CLUSTER_NAME).equals("c1") .toPredicate(); request = PropertyHelper.getReadRequest(propertyIds); ResourceProvider upgradeItemResourceProvider = new UpgradeItemResourceProvider(amc); resources = upgradeItemResourceProvider.getResources(request, predicate); assertEquals(2, resources.size()); res = resources.iterator().next(); assertNotNull(res.getPropertyValue("UpgradeItem/status")); // !!! check for manual stage vs item text propertyIds.clear(); propertyIds.add("UpgradeItem"); predicate = new PredicateBuilder() .property(UpgradeItemResourceProvider.UPGRADE_GROUP_ID).equals("3").and() .property(UpgradeItemResourceProvider.UPGRADE_REQUEST_ID).equals("1").and() .property(UpgradeItemResourceProvider.UPGRADE_CLUSTER_NAME).equals("c1") .toPredicate(); request = PropertyHelper.getReadRequest(propertyIds); upgradeItemResourceProvider = new UpgradeItemResourceProvider(amc); resources = upgradeItemResourceProvider.getResources(request, predicate); assertEquals(2, resources.size()); res = resources.iterator().next(); assertEquals("Confirm Finalize", res.getPropertyValue("UpgradeItem/context")); String msgStr = res.getPropertyValue("UpgradeItem/text").toString(); JsonParser parser = new JsonParser(); JsonArray msgArray = (JsonArray) parser.parse(msgStr); JsonObject msg = (JsonObject) msgArray.get(0); assertTrue(msg.get("message").getAsString().startsWith("Please confirm")); } /** * Tests that retrieving an upgrade correctly populates less common upgrade * options correctly. */ @Test public void testGetResourcesWithSpecialOptions() throws Exception { Cluster cluster = clusters.getCluster("c1"); List<UpgradeEntity> upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(0, upgrades.size()); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2111.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); // tests skipping SC failure options requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_FAILURES, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_SC_FAILURES, "true"); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); RequestStatus status = upgradeResourceProvider.createResources(request); assertNotNull(status); // upgrade Set<String> propertyIds = new HashSet<>(); propertyIds.add("Upgrade"); Predicate predicate = new PredicateBuilder() .property(UpgradeResourceProvider.UPGRADE_REQUEST_ID).equals("1").and() .property(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME).equals("c1") .toPredicate(); request = PropertyHelper.getReadRequest(propertyIds); Set<Resource> resources = upgradeResourceProvider.getResources(request, predicate); assertEquals(1, resources.size()); Resource resource = resources.iterator().next(); assertEquals(true, resource.getPropertyValue(UpgradeResourceProvider.UPGRADE_SKIP_FAILURES)); assertEquals(true, resource.getPropertyValue(UpgradeResourceProvider.UPGRADE_SKIP_SC_FAILURES)); } @Test public void testCreatePartialDowngrade() throws Exception { clusters.addHost("h2"); Host host = clusters.getHost("h2"); Map<String, String> hostAttributes = new HashMap<>(); hostAttributes.put("os_family", "redhat"); hostAttributes.put("os_release_version", "6.3"); host.setHostAttributes(hostAttributes); clusters.mapHostToCluster("h2", "c1"); Cluster cluster = clusters.getCluster("c1"); Service service = cluster.getService("ZOOKEEPER"); // start out with 0 (sanity check) List<UpgradeEntity> upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(0, upgrades.size()); // a downgrade MUST have an upgrade to come from, so populate an upgrade in // the DB RequestEntity requestEntity = new RequestEntity(); requestEntity.setRequestId(2L); requestEntity.setClusterId(cluster.getClusterId()); requestEntity.setStages(new ArrayList<StageEntity>()); requestDao.create(requestEntity); UpgradeEntity upgradeEntity = new UpgradeEntity(); upgradeEntity.setClusterId(cluster.getClusterId()); upgradeEntity.setDirection(Direction.UPGRADE); upgradeEntity.setRepositoryVersion(repoVersionEntity2200); upgradeEntity.setUpgradePackage("upgrade_test"); upgradeEntity.setUpgradeType(UpgradeType.ROLLING); upgradeEntity.setRequestEntity(requestEntity); UpgradeHistoryEntity history = new UpgradeHistoryEntity(); history.setUpgrade(upgradeEntity); history.setFromRepositoryVersion(service.getDesiredRepositoryVersion()); history.setTargetRepositoryVersion(repoVersionEntity2200); history.setServiceName(service.getName()); history.setComponentName("ZOKKEEPER_SERVER"); upgradeEntity.addHistory(history); history = new UpgradeHistoryEntity(); history.setUpgrade(upgradeEntity); history.setFromRepositoryVersion(service.getDesiredRepositoryVersion()); history.setTargetRepositoryVersion(repoVersionEntity2200); history.setServiceName(service.getName()); history.setComponentName("ZOKKEEPER_CLIENT"); upgradeEntity.addHistory(history); upgradeDao.create(upgradeEntity); upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(1, upgrades.size()); // push a ZK server foward to the new repo version, leaving the old one on // the old version ServiceComponent component = service.getServiceComponent("ZOOKEEPER_SERVER"); ServiceComponentHost sch = component.addServiceComponentHost("h2"); sch.setVersion(repoVersionEntity2200.getVersion()); UpgradeEntity lastUpgrade = upgradeDao.findLastUpgradeForCluster(cluster.getClusterId(), Direction.UPGRADE); assertNotNull(lastUpgrade); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.DOWNGRADE.name()); Map<String, String> requestInfoProperties = new HashMap<>(); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), requestInfoProperties); upgradeResourceProvider.createResources(request); upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(2, upgrades.size()); UpgradeEntity downgrade = upgrades.get(1); assertEquals(cluster.getClusterId(), downgrade.getClusterId().longValue()); List<UpgradeGroupEntity> upgradeGroups = downgrade.getUpgradeGroups(); assertEquals(3, upgradeGroups.size()); // the ZK restart group should only have 3 entries since the ZK server on h1 // didn't get upgraded UpgradeGroupEntity group = upgradeGroups.get(1); assertEquals("ZOOKEEPER", group.getName()); assertEquals(3, group.getItems().size()); } @Test public void testDowngradeToBase() throws Exception { Cluster cluster = clusters.getCluster("c1"); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2111.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); upgradeResourceProvider.createResources(request); List<UpgradeEntity> upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(1, upgrades.size()); UpgradeEntity upgrade = upgrades.get(0); // now abort the upgrade so another can be created abortUpgrade(upgrade.getRequestId()); // create another upgrade which should fail requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, "9999"); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); try { upgradeResourceProvider.createResources(request); Assert.fail("Expected an exception going downgrade with no upgrade pack"); } catch (Exception e) { // !!! expected } // fix the properties and try again requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.DOWNGRADE.name()); Map<String, String> requestInfoProperties = new HashMap<>(); request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), requestInfoProperties); RequestStatus status = upgradeResourceProvider.createResources(request); assertEquals(1, status.getAssociatedResources().size()); Resource r = status.getAssociatedResources().iterator().next(); String id = r.getPropertyValue("Upgrade/request_id").toString(); UpgradeEntity entity = upgradeDao.findUpgrade(Long.parseLong(id)); assertNotNull(entity); assertEquals(Direction.DOWNGRADE, entity.getDirection()); // associated version is the FROM on DOWNGRADE assertEquals(repoVersionEntity2111.getVersion(), entity.getRepositoryVersion().getVersion()); // target is by service assertEquals(repoVersionEntity2110.getVersion(), entity.getHistory().iterator().next().getTargetVersion()); StageDAO dao = injector.getInstance(StageDAO.class); List<StageEntity> stages = dao.findByRequestId(entity.getRequestId()); Gson gson = new Gson(); for (StageEntity se : stages) { Map<String, String> map = gson.<Map<String, String>>fromJson(se.getCommandParamsStage(), Map.class); assertTrue(map.containsKey("upgrade_direction")); assertEquals("downgrade", map.get("upgrade_direction")); } } /** * Test Downgrade from the partially completed upgrade */ @Test public void testNotFullDowngrade() throws Exception { Cluster cluster = clusters.getCluster("c1"); // add additional service for the test Service service = cluster.addService("HIVE", repoVersionEntity2110); ServiceComponent component = service.addServiceComponent("HIVE_SERVER"); ServiceComponentHost sch = component.addServiceComponentHost("h1"); sch.setVersion("2.1.1.0"); // create upgrade request Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2200.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_nonrolling_new_stack"); requestProps.put(UpgradeResourceProvider.UPGRADE_TYPE, "NON_ROLLING"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); upgradeResourceProvider.createResources(request); // check that upgrade was created and groups for the tested services are on place List<UpgradeEntity> upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(1, upgrades.size()); UpgradeEntity upgrade = upgrades.get(0); List<UpgradeGroupEntity> groups = upgrade.getUpgradeGroups(); boolean isHiveGroupFound = false; boolean isZKGroupFound = false; // look only for testing groups for (UpgradeGroupEntity group: groups) { if (group.getName().equalsIgnoreCase("hive")) { isHiveGroupFound = true; } else if (group.getName().equalsIgnoreCase("zookeeper")){ isZKGroupFound = true; } } assertTrue(isHiveGroupFound); assertTrue(isZKGroupFound); isHiveGroupFound = false; isZKGroupFound = false; sch.setVersion("2.2.0.0"); // now abort the upgrade so another can be created abortUpgrade(upgrade.getRequestId()); // create downgrade with one upgraded service service.setDesiredRepositoryVersion(repoVersionEntity2200); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_nonrolling_new_stack"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.DOWNGRADE.name()); Map<String, String> requestInfoProperties = new HashMap<>(); request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), requestInfoProperties); RequestStatus status = upgradeResourceProvider.createResources(request); UpgradeEntity upgradeEntity = upgradeDao.findUpgradeByRequestId(getRequestId(status)); for (UpgradeGroupEntity group: upgradeEntity.getUpgradeGroups()) { if (group.getName().equalsIgnoreCase("hive")) { isHiveGroupFound = true; } else if (group.getName().equalsIgnoreCase("zookeeper")){ isZKGroupFound = true; } } // as services not updated, nothing to downgrade assertTrue(isHiveGroupFound); assertFalse(isZKGroupFound); } @Test public void testAbort() throws Exception { RequestStatus status = testCreateResources(); Set<Resource> createdResources = status.getAssociatedResources(); assertEquals(1, createdResources.size()); Resource res = createdResources.iterator().next(); Long id = (Long) res.getPropertyValue("Upgrade/request_id"); assertNotNull(id); assertEquals(Long.valueOf(1), id); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_REQUEST_ID, id.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REQUEST_STATUS, "ABORTED"); requestProps.put(UpgradeResourceProvider.UPGRADE_SUSPENDED, "true"); UpgradeResourceProvider urp = createProvider(amc); // !!! make sure we can. actual abort is tested elsewhere Request req = PropertyHelper.getUpdateRequest(requestProps, null); urp.updateResources(req, null); } @Test public void testRetry() throws Exception { RequestStatus status = testCreateResources(); Set<Resource> createdResources = status.getAssociatedResources(); assertEquals(1, createdResources.size()); Resource res = createdResources.iterator().next(); Long id = (Long) res.getPropertyValue("Upgrade/request_id"); assertNotNull(id); assertEquals(Long.valueOf(1), id); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_REQUEST_ID, id.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REQUEST_STATUS, "ABORTED"); requestProps.put(UpgradeResourceProvider.UPGRADE_SUSPENDED, "true"); UpgradeResourceProvider urp = createProvider(amc); // !!! make sure we can. actual abort is tested elsewhere Request req = PropertyHelper.getUpdateRequest(requestProps, null); urp.updateResources(req, null); ActionManager am = injector.getInstance(ActionManager.class); List<HostRoleCommand> commands = am.getRequestTasks(id); boolean foundOne = false; for (HostRoleCommand hrc : commands) { if (hrc.getRole().equals(Role.AMBARI_SERVER_ACTION)) { assertEquals(-1L, hrc.getHostId()); assertNull(hrc.getHostName()); foundOne = true; } } assertTrue("Expected at least one server-side action", foundOne); HostRoleCommand cmd = commands.get(commands.size()-1); HostRoleCommandDAO dao = injector.getInstance(HostRoleCommandDAO.class); HostRoleCommandEntity entity = dao.findByPK(cmd.getTaskId()); entity.setStatus(HostRoleStatus.ABORTED); dao.merge(entity); requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_REQUEST_ID, id.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_REQUEST_STATUS, "PENDING"); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_SUSPENDED, "false"); // !!! make sure we can. actual reset is tested elsewhere req = PropertyHelper.getUpdateRequest(requestProps, null); urp.updateResources(req, null); } @Test(expected = IllegalArgumentException.class) public void testAbortWithoutSuspendFlag() throws Exception { RequestStatus status = testCreateResources(); Set<Resource> createdResources = status.getAssociatedResources(); assertEquals(1, createdResources.size()); Resource res = createdResources.iterator().next(); Long id = (Long) res.getPropertyValue("Upgrade/request_id"); assertNotNull(id); assertEquals(Long.valueOf(1), id); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_REQUEST_ID, id.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REQUEST_STATUS, "ABORTED"); UpgradeResourceProvider urp = createProvider(amc); Request req = PropertyHelper.getUpdateRequest(requestProps, null); urp.updateResources(req, null); } @Test public void testDirectionUpgrade() throws Exception { Cluster cluster = clusters.getCluster("c1"); StackEntity stackEntity = stackDAO.find("HDP", "2.1.1"); RepositoryVersionEntity repoVersionEntity = new RepositoryVersionEntity(); repoVersionEntity.setDisplayName("My New Version 3"); repoVersionEntity.setOperatingSystems(""); repoVersionEntity.setStack(stackEntity); repoVersionEntity.setVersion("2.2.2.3"); repoVersionDao.create(repoVersionEntity); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_direction"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); upgradeResourceProvider.createResources(request); List<UpgradeEntity> upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(1, upgrades.size()); UpgradeEntity upgrade = upgrades.get(0); Long id = upgrade.getRequestId(); assertEquals(3, upgrade.getUpgradeGroups().size()); // Ensure that there are no items related to downgrade in the upgrade direction UpgradeGroupEntity group = upgrade.getUpgradeGroups().get(2); Assert.assertEquals("POST_CLUSTER", group.getName()); Assert.assertTrue(!group.getItems().isEmpty()); for (UpgradeItemEntity item : group.getItems()) { Assert.assertFalse(item.getText().toLowerCase().contains("downgrade")); } // now abort the upgrade so another can be created abortUpgrade(upgrade.getRequestId()); requestProps.clear(); // Now perform a downgrade requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_direction"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.DOWNGRADE.name()); request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); upgradeResourceProvider.createResources(request); upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(2, upgrades.size()); upgrade = null; for (UpgradeEntity u : upgrades) { if (!u.getRequestId().equals(id)) { upgrade = u; } } assertNotNull(upgrade); List<UpgradeGroupEntity> groups = upgrade.getUpgradeGroups(); assertEquals("Downgrade groups reduced from 3 to 2", 1, groups.size()); group = upgrade.getUpgradeGroups().get(0); assertEquals("Execution items increased from 1 to 2", 2, group.getItems().size()); } @Test public void testPercents() throws Exception { RequestStatus status = testCreateResources(); Set<Resource> createdResources = status.getAssociatedResources(); assertEquals(1, createdResources.size()); Resource res = createdResources.iterator().next(); Long id = (Long) res.getPropertyValue("Upgrade/request_id"); assertNotNull(id); assertEquals(Long.valueOf(1), id); StageDAO stageDao = injector.getInstance(StageDAO.class); HostRoleCommandDAO hrcDao = injector.getInstance(HostRoleCommandDAO.class); List<StageEntity> stages = stageDao.findByRequestId(id); List<HostRoleCommandEntity> tasks = hrcDao.findByRequest(id); Set<Long> stageIds = new HashSet<>(); for (StageEntity se : stages) { stageIds.add(se.getStageId()); } CalculatedStatus calc = null; int i = 0; for (HostRoleCommandEntity hrce : tasks) { hrce.setStatus(HostRoleStatus.IN_PROGRESS); hrcDao.merge(hrce); calc = CalculatedStatus.statusFromStageSummary(hrcDao.findAggregateCounts(id), stageIds); assertEquals(((i++) + 1) * 4.375d, calc.getPercent(), 0.01d); assertEquals(HostRoleStatus.IN_PROGRESS, calc.getStatus()); } i = 0; for (HostRoleCommandEntity hrce : tasks) { hrce.setStatus(HostRoleStatus.COMPLETED); hrcDao.merge(hrce); calc = CalculatedStatus.statusFromStageSummary(hrcDao.findAggregateCounts(id), stageIds); assertEquals(35 + (((i++) + 1) * 8.125), calc.getPercent(), 0.01d); if (i < 8) { assertEquals(HostRoleStatus.IN_PROGRESS, calc.getStatus()); } } calc = CalculatedStatus.statusFromStageSummary(hrcDao.findAggregateCounts(id), stageIds); assertEquals(HostRoleStatus.COMPLETED, calc.getStatus()); assertEquals(100d, calc.getPercent(), 0.01d); } @Test public void testCreateCrossStackUpgrade() throws Exception { Cluster cluster = clusters.getCluster("c1"); StackId oldStack = repoVersionEntity2110.getStackId(); for (Service s : cluster.getServices().values()) { assertEquals(oldStack, s.getDesiredStackId()); for (ServiceComponent sc : s.getServiceComponents().values()) { assertEquals(oldStack, sc.getDesiredStackId()); for (ServiceComponentHost sch : sc.getServiceComponentHosts().values()) { assertEquals(repoVersionEntity2110.getVersion(), sch.getVersion()); } } } Config config = configFactory.createNew(cluster, "zoo.cfg", "abcdefg", Collections.singletonMap("a", "b"), null); cluster.addDesiredConfig("admin", Collections.singleton(config)); // create the upgrade across major versions Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2200.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); upgradeResourceProvider.createResources(request); List<UpgradeEntity> upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(1, upgrades.size()); UpgradeEntity upgrade = upgrades.get(0); assertEquals(3, upgrade.getUpgradeGroups().size()); UpgradeGroupEntity group = upgrade.getUpgradeGroups().get(2); assertEquals(2, group.getItems().size()); group = upgrade.getUpgradeGroups().get(0); assertEquals(2, group.getItems().size()); assertTrue(cluster.getDesiredConfigs().containsKey("zoo.cfg")); for (Service s : cluster.getServices().values()) { assertEquals(repoVersionEntity2200, s.getDesiredRepositoryVersion()); for (ServiceComponent sc : s.getServiceComponents().values()) { assertEquals(repoVersionEntity2200, sc.getDesiredRepositoryVersion()); } } } /** * @param amc * @return the provider */ private UpgradeResourceProvider createProvider(AmbariManagementController amc) { ResourceProviderFactory factory = injector.getInstance(ResourceProviderFactory.class); AbstractControllerResourceProvider.init(factory); Resource.Type type = Type.Upgrade; return (UpgradeResourceProvider) AbstractControllerResourceProvider.getResourceProvider(type, PropertyHelper.getPropertyIds(type), PropertyHelper.getKeyPropertyIds(type), amc); } private RequestStatus testCreateResources() throws Exception { Cluster cluster = clusters.getCluster("c1"); List<UpgradeEntity> upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(0, upgrades.size()); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2111.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); RequestStatus status = upgradeResourceProvider.createResources(request); upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(1, upgrades.size()); UpgradeEntity entity = upgrades.get(0); assertEquals(cluster.getClusterId(), entity.getClusterId().longValue()); assertEquals(UpgradeType.ROLLING, entity.getUpgradeType()); StageDAO stageDAO = injector.getInstance(StageDAO.class); List<StageEntity> stageEntities = stageDAO.findByRequestId(entity.getRequestId()); Gson gson = new Gson(); for (StageEntity se : stageEntities) { Map<String, String> map = gson.<Map<String, String>> fromJson(se.getCommandParamsStage(),Map.class); assertTrue(map.containsKey("upgrade_direction")); assertEquals("upgrade", map.get("upgrade_direction")); if(map.containsKey("upgrade_type")){ assertEquals("rolling_upgrade", map.get("upgrade_type")); } } List<UpgradeGroupEntity> upgradeGroups = entity.getUpgradeGroups(); assertEquals(3, upgradeGroups.size()); UpgradeGroupEntity group = upgradeGroups.get(1); assertEquals(4, group.getItems().size()); assertTrue( group.getItems().get(0).getText().contains("placeholder of placeholder-rendered-properly")); assertTrue(group.getItems().get(1).getText().contains("Restarting")); assertTrue(group.getItems().get(2).getText().contains("Updating")); assertTrue(group.getItems().get(3).getText().contains("Service Check")); ActionManager am = injector.getInstance(ActionManager.class); List<Long> requests = am.getRequestsByStatus( org.apache.ambari.server.actionmanager.RequestStatus.IN_PROGRESS, 100, true); assertEquals(1, requests.size()); assertEquals(requests.get(0), entity.getRequestId()); List<Stage> stages = am.getRequestStatus(requests.get(0).longValue()); assertEquals(8, stages.size()); List<HostRoleCommand> tasks = am.getRequestTasks(requests.get(0).longValue()); // same number of tasks as stages here assertEquals(8, tasks.size()); Set<Long> slaveStageIds = new HashSet<>(); UpgradeGroupEntity coreSlavesGroup = upgradeGroups.get(1); for (UpgradeItemEntity itemEntity : coreSlavesGroup.getItems()) { slaveStageIds.add(itemEntity.getStageId()); } for (Stage stage : stages) { // For this test the core slaves group stages should be skippable and NOT // allow retry. assertEquals(slaveStageIds.contains(stage.getStageId()), stage.isSkippable()); for (Map<String, HostRoleCommand> taskMap : stage.getHostRoleCommands().values()) { for (HostRoleCommand task : taskMap.values()) { assertEquals(!slaveStageIds.contains(stage.getStageId()), task.isRetryAllowed()); } } } return status; } @Test public void testUpdateSkipFailures() throws Exception { testCreateResourcesWithAutoSkipFailures(); List<UpgradeEntity> upgrades = upgradeDao.findUpgrades(1); assertEquals(1, upgrades.size()); UpgradeEntity entity = upgrades.get(0); HostRoleCommandDAO dao = injector.getInstance(HostRoleCommandDAO.class); List<HostRoleCommandEntity> tasks = dao.findByRequest(entity.getRequestId()); for (HostRoleCommandEntity task : tasks) { StageEntity stage = task.getStage(); if (stage.isSkippable() && stage.isAutoSkipOnFailureSupported()) { assertTrue(task.isFailureAutoSkipped()); } else { assertFalse(task.isFailureAutoSkipped()); } } Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2200.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_FAILURES, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_SC_FAILURES, Boolean.FALSE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_REQUEST_ID, "" + entity.getRequestId()); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getUpdateRequest(requestProps, null); upgradeResourceProvider.updateResources(request, null); tasks = dao.findByRequest(entity.getRequestId()); for (HostRoleCommandEntity task : tasks) { if (task.getRoleCommand() == RoleCommand.SERVICE_CHECK) { assertFalse(task.isFailureAutoSkipped()); } else { StageEntity stage = task.getStage(); if (stage.isSkippable() && stage.isAutoSkipOnFailureSupported()) { assertTrue(task.isFailureAutoSkipped()); } else { assertFalse(task.isFailureAutoSkipped()); } } } requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2200.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_FAILURES, Boolean.FALSE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_SC_FAILURES, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_REQUEST_ID, "" + entity.getRequestId()); request = PropertyHelper.getUpdateRequest(requestProps, null); upgradeResourceProvider.updateResources(request, null); tasks = dao.findByRequest(entity.getRequestId()); for (HostRoleCommandEntity task : tasks) { if (task.getRoleCommand() == RoleCommand.SERVICE_CHECK) { StageEntity stage = task.getStage(); if (stage.isSkippable() && stage.isAutoSkipOnFailureSupported()) { assertTrue(task.isFailureAutoSkipped()); } else { assertFalse(task.isFailureAutoSkipped()); } } else { assertFalse(task.isFailureAutoSkipped()); } } requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2200.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_FAILURES, Boolean.FALSE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_SC_FAILURES, Boolean.FALSE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_REQUEST_ID, "" + entity.getRequestId()); request = PropertyHelper.getUpdateRequest(requestProps, null); upgradeResourceProvider.updateResources(request, null); tasks = dao.findByRequest(entity.getRequestId()); for (HostRoleCommandEntity task : tasks) { assertFalse(task.isFailureAutoSkipped()); } } /** * Tests that an error while commiting the data cleanly rolls back the transaction so that * no request/stage/tasks are created. * * @throws Exception */ @Test public void testRollback() throws Exception { Cluster cluster = clusters.getCluster("c1"); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2200.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_TYPE, UpgradeType.ROLLING.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_MANUAL_VERIFICATION, Boolean.FALSE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); // this will cause a NPE when creating the upgrade, allowing us to test // rollback UpgradeResourceProvider upgradeResourceProvider = createProvider(amc); UpgradeResourceProvider.s_upgradeDAO = null; try { Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); upgradeResourceProvider.createResources(request); Assert.fail("Expected a NullPointerException"); } catch (NullPointerException npe) { // expected } List<UpgradeEntity> upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(0, upgrades.size()); List<Long> requestIds = requestDao.findAllRequestIds(1, true, cluster.getClusterId()); assertEquals(0, requestIds.size()); } /** * Tests that a {@link UpgradeType#HOST_ORDERED} upgrade throws an exception * on missing hosts. * * @throws Exception */ @Test() public void testCreateHostOrderedUpgradeThrowsExceptions() throws Exception { Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2200.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test_host_ordered"); requestProps.put(UpgradeResourceProvider.UPGRADE_TYPE, UpgradeType.HOST_ORDERED.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); try { upgradeResourceProvider.createResources(request); Assert.fail("The request should have failed due to the missing Upgrade/host_order property"); } catch( SystemException systemException ){ // expected } // stick a bad host_ordered_hosts in there which has the wrong hosts Set<Map<String, List<String>>> hostsOrder = new LinkedHashSet<>(); Map<String, List<String>> hostGrouping = new HashMap<>(); hostGrouping.put("hosts", Lists.newArrayList("invalid-host")); hostsOrder.add(hostGrouping); requestProps.put(UpgradeResourceProvider.UPGRADE_HOST_ORDERED_HOSTS, hostsOrder); try { upgradeResourceProvider.createResources(request); Assert.fail("The request should have failed due to invalid hosts"); } catch (SystemException systemException) { // expected } // use correct hosts now hostsOrder = new LinkedHashSet<>(); hostGrouping = new HashMap<>(); hostGrouping.put("hosts", Lists.newArrayList("h1")); hostsOrder.add(hostGrouping); requestProps.put(UpgradeResourceProvider.UPGRADE_HOST_ORDERED_HOSTS, hostsOrder); upgradeResourceProvider.createResources(request); } /** * Exercises that a component that goes from upgrade->downgrade that switches * {@code versionAdvertised} between will go to UKNOWN. This exercises * {@link UpgradeHelper#updateDesiredRepositoriesAndConfigs(UpgradeContext)} * * @throws Exception */ @Test public void testCreateUpgradeDowngradeCycleAdvertisingVersion() throws Exception { Cluster cluster = clusters.getCluster("c1"); Service service = cluster.addService("STORM", repoVersionEntity2110); ServiceComponent component = service.addServiceComponent("DRPC_SERVER"); ServiceComponentHost sch = component.addServiceComponentHost("h1"); sch.setVersion("2.1.1.0"); ResourceProvider upgradeResourceProvider = createProvider(amc); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2200.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); Map<String, String> requestInfoProperties = new HashMap<>(); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), requestInfoProperties); RequestStatus status = upgradeResourceProvider.createResources(request); assertEquals(1, status.getAssociatedResources().size()); Resource r = status.getAssociatedResources().iterator().next(); String id = r.getPropertyValue("Upgrade/request_id").toString(); component = service.getServiceComponent("DRPC_SERVER"); assertNotNull(component); assertEquals("2.2.0.0", component.getDesiredVersion()); ServiceComponentHost hostComponent = component.getServiceComponentHost("h1"); assertEquals(UpgradeState.IN_PROGRESS, hostComponent.getUpgradeState()); // !!! can't start a downgrade until cancelling the previous upgrade abortUpgrade(Long.parseLong(id)); requestProps.clear(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.DOWNGRADE.name()); request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), requestInfoProperties); status = upgradeResourceProvider.createResources(request); component = service.getServiceComponent("DRPC_SERVER"); assertNotNull(component); assertEquals(repoVersionEntity2110, component.getDesiredRepositoryVersion()); hostComponent = component.getServiceComponentHost("h1"); assertEquals(UpgradeState.NONE, hostComponent.getUpgradeState()); assertEquals("UNKNOWN", hostComponent.getVersion()); } /** * Ensures that stages created with an HOU are sequential and do not skip any * IDs. When there are stages with IDs like (1,2,3,5,6,7,10), the request will * get stuck in a PENDING state. This affects HOU specifically since they can * potentially try to create empty stages which won't get persisted (such as a * STOP on client-only hosts). * * @throws Exception */ @Test() public void testEmptyGroupingsDoNotSkipStageIds() throws Exception { StageDAO stageDao = injector.getInstance(StageDAO.class); Assert.assertEquals(0, stageDao.findAll().size()); // strip out all non-client components - clients don't have STOP commands Cluster cluster = clusters.getCluster("c1"); List<ServiceComponentHost> schs = cluster.getServiceComponentHosts("h1"); for (ServiceComponentHost sch : schs) { if (sch.isClientComponent()) { continue; } cluster.removeServiceComponentHost(sch); } // define host order Set<Map<String, List<String>>> hostsOrder = new LinkedHashSet<>(); Map<String, List<String>> hostGrouping = new HashMap<>(); hostGrouping = new HashMap<>(); hostGrouping.put("hosts", Lists.newArrayList("h1")); hostsOrder.add(hostGrouping); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2200.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test_host_ordered"); requestProps.put(UpgradeResourceProvider.UPGRADE_TYPE, UpgradeType.HOST_ORDERED.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS,Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); requestProps.put(UpgradeResourceProvider.UPGRADE_HOST_ORDERED_HOSTS, hostsOrder); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); upgradeResourceProvider.createResources(request); List<StageEntity> stages = stageDao.findByRequestId(cluster.getUpgradeInProgress().getRequestId()); Assert.assertEquals(3, stages.size()); long expectedStageId = 1L; for (StageEntity stage : stages) { Assert.assertEquals(expectedStageId++, stage.getStageId().longValue()); } } /** * Tests that from/to repository version history is created correctly on the * upgrade. * * @throws Exception */ @Test public void testUpgradeHistory() throws Exception { Cluster cluster = clusters.getCluster("c1"); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2200.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_TYPE, UpgradeType.ROLLING.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_MANUAL_VERIFICATION, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, Boolean.TRUE.toString()); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); upgradeResourceProvider.createResources(request); List<UpgradeEntity> upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(1, upgrades.size()); UpgradeEntity upgrade = cluster.getUpgradeInProgress(); List<UpgradeHistoryEntity> histories = upgrade.getHistory(); assertEquals(2, histories.size()); for( UpgradeHistoryEntity history : histories){ assertEquals( "ZOOKEEPER", history.getServiceName() ); assertEquals(repoVersionEntity2110, history.getFromReposistoryVersion()); assertEquals(repoVersionEntity2200, history.getTargetRepositoryVersion()); } // abort the upgrade and create the downgrade abortUpgrade(upgrade.getRequestId()); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_nonrolling_new_stack"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.DOWNGRADE.name()); Map<String, String> requestInfoProperties = new HashMap<>(); request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), requestInfoProperties); RequestStatus status = upgradeResourceProvider.createResources(request); UpgradeEntity downgrade = upgradeDao.findUpgradeByRequestId(getRequestId(status)); assertEquals(Direction.DOWNGRADE, downgrade.getDirection()); // check from/to history histories = downgrade.getHistory(); assertEquals(2, histories.size()); for (UpgradeHistoryEntity history : histories) { assertEquals("ZOOKEEPER", history.getServiceName()); assertEquals(repoVersionEntity2200, history.getFromReposistoryVersion()); assertEquals(repoVersionEntity2110, history.getTargetRepositoryVersion()); } } /** * Tests that from/to repository version history is created correctly on the * upgrade. * * @throws Exception */ @Test public void testCreatePatchRevertUpgrade() throws Exception { Cluster cluster = clusters.getCluster("c1"); // add a single ZK server and client on 2.1.1.0 Service service = cluster.addService("HBASE", repoVersionEntity2110); ServiceComponent component = service.addServiceComponent("HBASE_MASTER"); ServiceComponentHost sch = component.addServiceComponentHost("h1"); sch.setVersion("2.1.1.0"); File f = new File("src/test/resources/hbase_version_test.xml"); repoVersionEntity2112.setVersionXml(IOUtils.toString(new FileInputStream(f))); repoVersionEntity2112.setVersionXsd("version_definition.xsd"); repoVersionDao.merge(repoVersionEntity2112); List<UpgradeEntity> upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(0, upgrades.size()); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2112.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); upgradeResourceProvider.createResources(request); upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(1, upgrades.size()); UpgradeEntity upgradeEntity = upgrades.get(0); assertEquals(RepositoryType.PATCH, upgradeEntity.getOrchestration()); // !!! make it look like the cluster is done cluster.setUpgradeEntity(null); requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REVERT_UPGRADE_ID, upgradeEntity.getId()); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, Boolean.TRUE.toString()); request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); upgradeResourceProvider.createResources(request); upgrades = upgradeDao.findUpgrades(cluster.getClusterId()); assertEquals(2, upgrades.size()); boolean found = false; Function<UpgradeHistoryEntity, String> function = new Function<UpgradeHistoryEntity, String>() { @Override public String apply(UpgradeHistoryEntity input) { return input.getServiceName() + "/" + input.getComponentName(); }; }; for (UpgradeEntity upgrade : upgrades) { if (upgrade.getId() != upgradeEntity.getId()) { found = true; assertEquals(upgradeEntity.getOrchestration(), upgrade.getOrchestration()); Collection<String> upgradeEntityStrings = Collections2.transform(upgradeEntity.getHistory(), function); Collection<String> upgradeStrings = Collections2.transform(upgrade.getHistory(), function); Collection<?> diff = CollectionUtils.disjunction(upgradeEntityStrings, upgradeStrings); assertEquals("Verify the same set of components was orchestrated", 0, diff.size()); } } assertTrue(found); } private String parseSingleMessage(String msgStr){ JsonParser parser = new JsonParser(); JsonArray msgArray = (JsonArray) parser.parse(msgStr); JsonObject msg = (JsonObject) msgArray.get(0); return msg.get("message").getAsString(); } /** * Aborts and upgrade. * * @param requestId * @throws Exception */ private void abortUpgrade(long requestId) throws Exception { // now abort the upgrade so another can be created Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_REQUEST_ID, String.valueOf(requestId)); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REQUEST_STATUS, "ABORTED"); requestProps.put(UpgradeResourceProvider.UPGRADE_SUSPENDED, "false"); Request request = PropertyHelper.getUpdateRequest(requestProps, null); ResourceProvider upgradeResourceProvider = createProvider(amc); upgradeResourceProvider.updateResources(request, null); // !!! this is required since the ActionManager/ActionScheduler isn't // running and can't remove queued PENDING - it's a cheap way of ensuring // that the upgrade commands do get aborted hrcDAO.updateStatusByRequestId(requestId, HostRoleStatus.ABORTED, HostRoleStatus.IN_PROGRESS_STATUSES); } @Test public void testTimeouts() throws Exception { StackEntity stackEntity = stackDAO.find("HDP", "2.1.1"); RepositoryVersionEntity repoVersionEntity = new RepositoryVersionEntity(); repoVersionEntity.setDisplayName("My New Version 3"); repoVersionEntity.setOperatingSystems(""); repoVersionEntity.setStack(stackEntity); repoVersionEntity.setVersion("2.2.2.3"); repoVersionDao.create(repoVersionEntity); Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); RequestStatus status = upgradeResourceProvider.createResources(request); Set<Resource> createdResources = status.getAssociatedResources(); assertEquals(1, createdResources.size()); Resource res = createdResources.iterator().next(); Long id = (Long) res.getPropertyValue("Upgrade/request_id"); assertNotNull(id); assertEquals(Long.valueOf(1), id); ActionManager am = injector.getInstance(ActionManager.class); List<HostRoleCommand> commands = am.getRequestTasks(id); boolean found = false; for (HostRoleCommand command : commands) { ExecutionCommandWrapper wrapper = command.getExecutionCommandWrapper(); if (command.getRole().equals(Role.ZOOKEEPER_SERVER) && command.getRoleCommand().equals(RoleCommand.CUSTOM_COMMAND)) { Map<String, String> commandParams = wrapper.getExecutionCommand().getCommandParams(); assertTrue(commandParams.containsKey(KeyNames.COMMAND_TIMEOUT)); assertEquals("824",commandParams.get(KeyNames.COMMAND_TIMEOUT)); found = true; } } assertTrue("ZooKeeper timeout override was found", found); } /** * Tests that commands created for {@link org.apache.ambari.server.state.stack.upgrade.StageWrapper.Type#UPGRADE_TASKS} set the * service and component on the {@link ExecutionCommand}. * <p/> * Without this, commands of this type would not be able to determine which * service/component repository they should use when the command is scheduled * to run. * * @throws Exception */ @Test public void testExecutionCommandServiceAndComponent() throws Exception { Map<String, Object> requestProps = new HashMap<>(); requestProps.put(UpgradeResourceProvider.UPGRADE_CLUSTER_NAME, "c1"); requestProps.put(UpgradeResourceProvider.UPGRADE_REPO_VERSION_ID, String.valueOf(repoVersionEntity2200.getId())); requestProps.put(UpgradeResourceProvider.UPGRADE_PACK, "upgrade_execute_task_test"); requestProps.put(UpgradeResourceProvider.UPGRADE_SKIP_PREREQUISITE_CHECKS, "true"); requestProps.put(UpgradeResourceProvider.UPGRADE_DIRECTION, Direction.UPGRADE.name()); ResourceProvider upgradeResourceProvider = createProvider(amc); Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null); RequestStatus status = upgradeResourceProvider.createResources(request); Set<Resource> createdResources = status.getAssociatedResources(); assertEquals(1, createdResources.size()); Resource res = createdResources.iterator().next(); Long id = (Long) res.getPropertyValue("Upgrade/request_id"); assertNotNull(id); assertEquals(Long.valueOf(1), id); ActionManager am = injector.getInstance(ActionManager.class); List<HostRoleCommand> commands = am.getRequestTasks(id); boolean foundActionExecuteCommand = false; for (HostRoleCommand command : commands) { ExecutionCommand executionCommand = command.getExecutionCommandWrapper().getExecutionCommand(); if (StringUtils.equals(UpgradeResourceProvider.EXECUTE_TASK_ROLE, executionCommand.getRole())) { foundActionExecuteCommand = true; assertNotNull(executionCommand.getServiceName()); assertNotNull(executionCommand.getComponentName()); } } assertTrue( "There was no task found with the role of " + UpgradeResourceProvider.EXECUTE_TASK_ROLE, foundActionExecuteCommand); } /** * */ private class MockModule implements Module { /** * */ @Override public void configure(Binder binder) { binder.bind(ConfigHelper.class).toInstance(configHelper); } } }
44.31706
129
0.760032
fcd4225dccb40d67fa41bd64e49bab79851f1a56
536
package xyz.model; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; public class User { @NotBlank private String name; @Max(value = 18) @Min(value = 10) private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
16.242424
45
0.623134
7ffbcc90b5a6ff5332876c72225574118f02d6e4
5,583
package com.arcussmarthome.ipcd.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import com.arcussmarthome.ipcd.server.debug.Console; public class IpcdServer { public static final String DEFAULT_CONTEXT = "/ipcd-config.xml"; private static final Logger logger = LoggerFactory.getLogger(IpcdServer.class); protected int portNumber = 443; protected InetSocketAddress socketBindAddress; protected boolean debugConsole = false; protected ChannelInitializer<SocketChannel> channelInitializer; protected EventLoopGroup bossGroup = null; protected EventLoopGroup workerGroup = null; @SuppressWarnings("rawtypes") protected Map<ChannelOption, Object> channelOptions; protected ServerBootstrap serverBootstrap; public IpcdServer() { } @SuppressWarnings( {"rawtypes", "unchecked"} ) public void startServer() throws Exception { try { serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup); serverBootstrap.channel(NioServerSocketChannel.class); for (Map.Entry<ChannelOption, Object> e : channelOptions.entrySet()) { serverBootstrap.childOption(e.getKey(), e.getValue()); } serverBootstrap.childHandler(channelInitializer); Channel ch = serverBootstrap.bind(portNumber).sync().channel(); // TODO log msg server start if (debugConsole) { BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in)); Console console = new Console(); while (true) { String msg = consoleReader.readLine(); if (msg == null) { break; } console.handleInput(msg); } } else { ch.closeFuture().sync(); } } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public void shutdownServer() throws Exception { } public EventLoopGroup getBossGroup() { return bossGroup; } @Required public void setBossGroup(EventLoopGroup bossGroup) { this.bossGroup = bossGroup; } public EventLoopGroup getWorkerGroup() { return workerGroup; } @Required public void setWorkerGroup(EventLoopGroup workerGroup) { this.workerGroup = workerGroup; } @SuppressWarnings("rawtypes") public Map<ChannelOption, Object> getChannelOptions() { return channelOptions; } @SuppressWarnings("rawtypes") @Required public void setChannelOptions(Map<ChannelOption, Object> channelOptions) { this.channelOptions = channelOptions; } public int getPortNumber() { return portNumber; } @Required public void setPortNumber(int portNumber) { this.portNumber = portNumber; } public void setDebugConsole(boolean debugConsole) { this.debugConsole = debugConsole; } public InetSocketAddress getSocketBindAddress() { return socketBindAddress; } @Required public void setSocketBindAddress(InetSocketAddress socketBindAddress) { this.socketBindAddress = socketBindAddress; } public ChannelInitializer<SocketChannel> getChannelPipelineInitializer() { return channelInitializer; } @Required public void setChannelInitializer(ChannelInitializer<SocketChannel> channelInitializer) { this.channelInitializer = channelInitializer; } private static GenericApplicationContext loadContext(String contextLocation) { GenericApplicationContext app = new GenericApplicationContext(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(app); if(IpcdServer.class.getResource(contextLocation) != null) { reader.loadBeanDefinitions(new ClassPathResource(contextLocation)); } else if(new File(contextLocation).exists()) { reader.loadBeanDefinitions(new FileSystemResource(contextLocation)); } else { return null; } app.refresh(); return app; } public static void main(String[] args) throws Exception { String contextLocation = args.length > 0 ? args[0] : DEFAULT_CONTEXT; System.out.println("Loading configuration " + contextLocation + "..."); final GenericApplicationContext ctx = loadContext(contextLocation); if(ctx == null) { System.err.println("Could not locate config file "+contextLocation+", exiting..."); System.exit(-1); } Map<String, IpcdServer> servers = ctx.getBeansOfType(IpcdServer.class); if(servers.size() == 0) { System.err.println("No IpcdServers defined, exiting..."); System.exit(-1); } else if(servers.size() > 1) { System.err.println("More than 1 IpcdServer defined, exiting..."); System.exit(-1); } final IpcdServer server = servers.values().iterator().next(); System.out.println("Starting server at " + server.getSocketBindAddress().getAddress() + ":" + server.getPortNumber()); server.startServer(); } }
28.927461
125
0.732581
741d7bf377c2d8bcfab0c9536b474aab5805238c
61
package com.example.lucas.buseye; public class Terminal { }
12.2
33
0.770492
ebd54604bff587ab1f7ae77c18d434590683ac23
6,328
package frc.robot.subsystems; import org.photonvision.PhotonCamera; import org.photonvision.targeting.PhotonTrackedTarget; import edu.wpi.first.wpilibj2.command.SubsystemBase; import edu.wpi.first.math.controller.PIDController; import edu.wpi.first.math.util.Units; import frc.robot.Constants; import frc.robot.utility.StepController; import java.lang.Math; public class HubVision extends SubsystemBase { //Define PhotonVision camera private PhotonCamera camera = new PhotonCamera("Camera1"); //Define PhotonVision vars private boolean targetInSights = false; private double targetYaw; private double targetPitch; //Create PID and step controller with constants from constants file StepController fowardsController = new StepController(Constants.VisionConstants.stepControllerArray); PIDController rotationController = new PIDController( Constants.VisionConstants.pAngularGain, Constants.VisionConstants.iAngularGain, Constants.VisionConstants.dAngularGain ); //Class that contains the fowards speed and rotation speed to be assigned to arcade drive to move the robot public class arcadeDriveSpeeds { //Speed vars private double fowardSpeed; private double rotationSpeed; private boolean applySaefty = true; private double maxSpeed; /** * Constructor * * @param fowardSpeed Fowards speed * @param rotationSpeed Rotation speed */ public arcadeDriveSpeeds(double fowardSpeed, double rotationSpeed) { this.maxSpeed = 1; this.fowardSpeed = fowardSpeed; this.rotationSpeed = rotationSpeed; } /** * Constructor * * @param fowardSpeed Fowards speed * @param rotationSpeed Rotation speed * @param maxSpeed Max speed the robot should go */ public arcadeDriveSpeeds(double fowardSpeed, double rotationSpeed, double maxSpeed) { this.maxSpeed = maxSpeed; this.fowardSpeed = fowardSpeed; this.rotationSpeed = rotationSpeed; } /** * Disable saefty */ public void disableSaefty() { applySaefty = false; } /** * Get the fowards speed and apply saefty if it is on * * @return Fowards speed */ public double getFowardSpeed() { if(applySaefty && fowardSpeed > maxSpeed) return maxSpeed; if(applySaefty && fowardSpeed < -maxSpeed) return -maxSpeed; return fowardSpeed; } /** * Get the rotation speed and apply saefty if it is on * * @return Rotation speed */ public double getRotationSpeed() { if(applySaefty && rotationSpeed > maxSpeed) return maxSpeed; if(applySaefty && rotationSpeed < -maxSpeed) return -maxSpeed; return rotationSpeed; } /** * Get fowards and rotation value as strings * * @return String that contains fowards and rotation speeds */ public String toString() { return "ARCADE DRIVE SPEEDS: [Fowards=" + fowardSpeed + " Rotation=" + rotationSpeed + "]"; } } /** * Call periodicly * Update results from PhotonVision */ @Override public void periodic() { //Get latest results from camera and set best target var result = camera.getLatestResult(); //If there are targets if(result.hasTargets()) { //Get best target and set targetInSights to true targetInSights = true; PhotonTrackedTarget bestTarget = result.getBestTarget(); //Assign yaw and pitch to best target yaw and pitch targetYaw = bestTarget.getYaw(); targetPitch = bestTarget.getPitch(); // If there are no targets then stop drive } else { targetInSights = false; } } /** * Print values returned from photon vision for debugging */ public String photonVisionValuesAsString() { return "PHOTONVISION VALUES: [Found Target=" + targetInSights + ", Pitch=" + targetPitch + ", Yaw=" + targetYaw + "]"; } /** * Calculate distance to target * * @return Distance in inches to the target */ public double getDistanceToTarget() { //If there is a target if(targetInSights) { //Get constants from constants file and convert to meters double upperHubTargetHeight = Units.inchesToMeters(Constants.VisionConstants.upperHubTargetHeight); double cameraHeight = Units.inchesToMeters(Constants.VisionConstants.cameraHeight); double cameraAngle = Constants.VisionConstants.cameraAngle; //Return distace return Units.metersToInches( (upperHubTargetHeight - cameraHeight) / Math.tan(Math.toRadians(targetPitch + cameraAngle)) ); //If there is no target } else { return 0; } } /** * Gets the speeds that arcade drive should be assigned to get to the target spot and aim at the target * * @return Arcade speed class containing the speed values required */ public arcadeDriveSpeeds getArcadeSpeed() { //If there is a target if(targetInSights) { //Use PID controllers to calculate the speed required double fowardSpeed = -fowardsController.calculate(getDistanceToTarget(), Constants.VisionConstants.targetDistanceFromHub); double rotationSpeed = -rotationController.calculate(targetYaw, 0); //Return speeds return new arcadeDriveSpeeds(fowardSpeed, rotationSpeed); //If there is no target then set then dont drive } else { return new arcadeDriveSpeeds(0, 0); } } /** * Returns the yaw * * @return Target yaw */ public double getYaw() { return targetYaw; } /** * Returns the pitch * * @return Target pitch */ public double getPitch() { return targetPitch; } }
27.876652
134
0.615202
5ea51f9e13befb854b62984bca03d6fdc3479246
8,008
package com.mobgen.halo.android.content.mock.instrumentation; import android.support.annotation.NonNull; import com.mobgen.halo.android.content.mock.dummy.DummyItem; import com.mobgen.halo.android.content.models.HaloContentInstance; import com.mobgen.halo.android.content.models.Paginated; import com.mobgen.halo.android.content.models.SearchQuery; import com.mobgen.halo.android.content.search.SearchQueryBuilderFactory; import com.mobgen.halo.android.framework.network.client.HaloNetClient; import com.mobgen.halo.android.framework.toolbox.data.CallbackV2; import com.mobgen.halo.android.framework.toolbox.data.HaloResultV2; import com.mobgen.halo.android.sdk.core.management.segmentation.HaloLocale; import com.mobgen.halo.android.sdk.core.management.segmentation.HaloSegmentationTag; import com.mobgen.halo.android.testing.CallbackFlag; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import okhttp3.Headers; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import static org.assertj.core.api.Java6Assertions.assertThat; public class SearchInstruments { public static SearchQuery givenTheSimplestQuery() { return SearchQuery.builder() .moduleIds("sampleId") .build(); } public static SearchQuery givenANotPaginatedQuery() { return SearchQuery.builder() .moduleIds("sampleId") .onePage(true) .build(); } public static SearchQuery givenAComplexQuery() { return SearchQueryBuilderFactory.getExpiredItems("sampleId", "sample") .build(); } public static SearchQuery givenASearchLikePatternQuery() { return SearchQueryBuilderFactory.getPublishedItemsByName("sampleId", "sample", "searchString") .build(); } public static SearchQuery givenTimedCacheQuery(long waitingMillis) { return SearchQuery.builder() .moduleIds("sampleId") .ttl(TimeUnit.MILLISECONDS, waitingMillis) .build(); } public static SearchQuery givenAFullQuery() { return SearchQuery.builder() .moduleIds("module1", "module2") .instanceIds("instance1", "instance2") .pickFields("field1", "field2") .tags(new HaloSegmentationTag("platform", "android")) .populateAll() .beginSearch() .eq("field1", "value1") .and() .eq("field2", "value2") .end() .beginMetaSearch() .eq("field1", "value1") .and() .eq("field2", "value2") .end() .locale(HaloLocale.ENGLISH_BELGIUM) .pagination(1, 10) .ttl(TimeUnit.HOURS, 1) .build(); } public static <T> CallbackV2<T> givenCallbackWithErrorType(final CallbackFlag flag, Class<T> classType, final Class<? extends Exception> errorType) { return new CallbackV2<T>() { @Override public void onFinish(@NonNull HaloResultV2<T> result) { flag.flagExecuted(); assertThat(result.data()).isNull(); assertThat(result.status().isError()).isTrue(); assertThat(result.status().exception()).isInstanceOf(errorType); } }; } public static CallbackV2<Paginated<HaloContentInstance>> givenCallbackContentSuccessData(final CallbackFlag flag, final boolean isFresh) { return new CallbackV2<Paginated<HaloContentInstance>>() { @Override public void onFinish(@NonNull HaloResultV2<Paginated<HaloContentInstance>> result) { flag.flagExecuted(); assertThat(result.data()).isNotNull(); assertThat(result.data().getLimit()).isEqualTo(result.data().data().size()); assertThat(result.data().data()).extracting("values").isNotEmpty(); assertThat(result.status().isError()).isFalse(); if (isFresh) { assertThat(result.status().isFresh()).isTrue(); } else { assertThat(result.status().isLocal()).isTrue(); } } }; } public static CallbackV2<List<DummyItem>> givenCallbackContentParsedSuccessData(final CallbackFlag flag, final boolean isFresh, final boolean hasError) { return new CallbackV2<List<DummyItem>>() { @Override public void onFinish(@NonNull HaloResultV2<List<DummyItem>> result) { flag.flagExecuted(); assertThat(result.data()).isNotNull(); assertThat(result.data()).isNotEmpty(); assertThat(result.data()).hasOnlyElementsOfType(DummyItem.class); assertThat(result.data()).extracting("foo").contains("bar").doesNotContainNull(); if (hasError) { assertThat(result.status().isError()).isTrue(); } else { assertThat(result.status().isError()).isFalse(); } if (isFresh) { assertThat(result.status().isFresh()).isTrue(); } else { assertThat(result.status().isLocal()).isTrue(); } } }; } public static CallbackV2<List<DummyItem>> givenCallbackContentParsedEmptyDataLocal(final CallbackFlag flag) { return new CallbackV2<List<DummyItem>>() { @Override public void onFinish(@NonNull HaloResultV2<List<DummyItem>> result) { flag.flagExecuted(); assertThat(result.data()).isNotNull(); assertThat(result.data()).isEmpty(); assertThat(result.status().isError()).isFalse(); assertThat(result.status().isLocal()).isTrue(); } }; } public static CallbackV2<Paginated<HaloContentInstance>> givenCallbackThatChecksDataIsInconsistent(final CallbackFlag flag) { return new CallbackV2<Paginated<HaloContentInstance>>() { @Override public void onFinish(@NonNull HaloResultV2<Paginated<HaloContentInstance>> result) { flag.flagExecuted(); assertThat(result.data()).isNull(); assertThat(result.status().isError()).isTrue(); assertThat(result.status().isInconsistent()).isTrue(); } }; } public static OkHttpClient.Builder givenAOkClientWithCustomInterceptor(HaloNetClient netClient, final String cacheTime) { return netClient.ok().newBuilder() .addInterceptor(new Interceptor() { boolean isFirstSyncExecution; @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Headers headers = request.headers(); if(isFirstSyncExecution) { if (headers.get("to-cache") != null) { assertThat(headers.get("to-cache")).isEqualTo(cacheTime); isFirstSyncExecution = false; } } return chain.proceed(request); } }); } public static SearchQuery givenASearchWithServerCache() { return SearchQueryBuilderFactory.getPublishedItemsByName("sampleId", "sample", "searchString") .serverCache(212) .build(); } public static SearchQuery givenASearchWithoutServerCache() { return SearchQueryBuilderFactory.getPublishedItemsByName("sampleId", "sample", "searchString") .build(); } }
41.278351
157
0.594031
6e07eefffeb4749ffab1f8b6179afe07e662b445
3,078
package com.lodz.android.agiledev.ui.idcard; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import com.lodz.android.agiledev.R; import com.lodz.android.component.base.activity.AbsActivity; import com.lodz.android.component.widget.base.SearchTitleBarLayout; import com.lodz.android.core.utils.DateUtils; import com.lodz.android.core.utils.IdCardUtils; import butterknife.BindView; import butterknife.ButterKnife; /** * 身份证号码测试类 * Created by zhouL on 2018/4/17. */ public class IdcardTestActivity extends AbsActivity{ public static void start(Context context) { Intent starter = new Intent(context, IdcardTestActivity.class); context.startActivity(starter); } /** 搜索标题框 */ @BindView(R.id.search_title_layout) SearchTitleBarLayout mSearchTitleBarLayout; /** 结果 */ @BindView(R.id.result) TextView mResultTv; @Override protected int getAbsLayoutId() { return R.layout.activity_id_card_test_layout; } @Override protected void findViews(Bundle savedInstanceState) { ButterKnife.bind(this); } @Override protected void setListeners() { super.setListeners(); mSearchTitleBarLayout.setOnBackBtnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); mSearchTitleBarLayout.setOnSearchClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(mSearchTitleBarLayout.getInputText())) { mResultTv.setTextColor(Color.RED); mResultTv.setText(R.string.idcard_empty_tips); return; } if (mSearchTitleBarLayout.getInputText().length() != 18){ mResultTv.setTextColor(Color.RED); mResultTv.setText(R.string.idcard_length_error); return; } checkIdcard(mSearchTitleBarLayout.getInputText()); } }); } /** * 校验身份证号 * @param idcard 身份证号 */ private void checkIdcard(String idcard) { mResultTv.setTextColor(Color.BLACK); if (!IdCardUtils.validateIdCard(idcard)){ mResultTv.setText("您输入的不是身份证号"); return; } String result = "身份证号校验成功\n" + "省份:" + IdCardUtils.getProvince(idcard) + "\n" + "性别:" + IdCardUtils.getSexStr(idcard) + "\n" + "出生年月日:" + IdCardUtils.getBirth(idcard, DateUtils.TYPE_6) + "\n" + "年:" + IdCardUtils.getYear(idcard) + "\n" + "月:" + IdCardUtils.getMonth(idcard) + "\n" + "日:" + IdCardUtils.getDay(idcard) + "\n" + "年龄:" + IdCardUtils.getAge(idcard) + "\n" ; mResultTv.setText(result); } }
30.176471
84
0.610461
0cccc72b8a32739c23f04f18e90bec8e6ed3a834
12,549
package de.emaeuer.environment.pong; import de.emaeuer.environment.AgentController; import de.emaeuer.environment.math.Vector2D; import de.emaeuer.environment.pong.configuration.PongConfiguration; import de.emaeuer.environment.pong.elements.Ball; import de.emaeuer.environment.pong.elements.Paddle; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class PaddleBallPair { private final Paddle paddle; private final Ball ball; private final AgentController controller; private final PongEnvironment environment; private final double maxReflectionAngle; public PaddleBallPair(Paddle paddle, Ball ball, AgentController controller, PongEnvironment environment) { this.paddle = paddle; this.ball = ball; this.controller = controller; this.environment = environment; this.maxReflectionAngle = Math.toRadians(this.environment.getConfiguration().getValue(PongConfiguration.BALL_MAX_REFLECTION_ANGLE, Double.class)); } public boolean isDead() { return this.ball.isOutOfGame(); } public void setDead(boolean dead) { this.ball.setOutOfGame(dead); } public void step() { this.paddle.step(); ballStep(); if (checkForMiss()) { setDead(true); this.controller.setScore(calculateScoreAfterMiss()); } else { double[] input = createInput(); double activation = this.controller.getAction(input)[0]; activation = adjustActivation(activation, this.controller); applyAction(activation); } } private void ballStep() { // if the ball collides with something the step was already made if (!adjustBorderCollision()) { this.ball.step(); } } private boolean adjustBorderCollision() { double rightX = this.ball.getPosition().getX() + this.ball.getSize().getX() / 2; double upperY = this.ball.getPosition().getY() - this.ball.getSize().getY() / 2; double lowerY = this.ball.getPosition().getY() + this.ball.getSize().getY() / 2; double xVelocity = this.ball.getVelocity().getX(); double yVelocity = this.ball.getVelocity().getY(); boolean hitsTop = upperY + yVelocity < 0 && yVelocity < 0; boolean hitsBottom = lowerY + yVelocity > this.environment.getHeight() && yVelocity > 0; boolean hitsRight = rightX + xVelocity > this.environment.getWidth() && xVelocity > 0; boolean hitsPaddle = checkPaddleCollision(); if (hitsTop) { handleTopHit(); } else if (hitsBottom) { handleBottomHit(); } else if (hitsRight) { handleRightHit(); } else if (hitsPaddle) { handlePaddleHit(); this.controller.setScore(this.controller.getScore() + 1); } return hitsTop || hitsBottom || hitsPaddle || hitsRight; } private void handleTopRightHit() { double y = this.ball.getPosition().getY() - this.ball.getSize().getY() / 2; double x = this.environment.getWidth() - this.ball.getPosition().getX() + this.ball.getSize().getX() / 2; double yVelocity = this.ball.getVelocity().getY(); double xVelocity = this.ball.getVelocity().getX(); this.ball.getPosition().setX(this.environment.getWidth() - (1 - x / xVelocity) * xVelocity); this.ball.getPosition().setY((1 - y / yVelocity) * yVelocity); this.ball.getVelocity().multiply(new Vector2D(-1, -1)); } private void handleBottomRightHit() { double y = this.environment.getHeight() - this.ball.getPosition().getY() + this.ball.getSize().getY() / 2; double x = this.environment.getWidth() - this.ball.getPosition().getX() + this.ball.getSize().getX() / 2; double yVelocity = this.ball.getVelocity().getY(); double xVelocity = this.ball.getVelocity().getX(); this.ball.getPosition().setX(this.environment.getWidth() - (1 - x / xVelocity) * xVelocity); this.ball.getPosition().setY(this.environment.getHeight() - (1 - y / yVelocity) * yVelocity); this.ball.getVelocity().multiply(new Vector2D(-1, -1)); } private void handleTopHit() { double y = this.ball.getPosition().getY() - this.ball.getSize().getY() / 2; double velocity = this.ball.getVelocity().getY(); this.ball.getPosition().setX(this.ball.getPosition().getX() + this.ball.getVelocity().getX()); this.ball.getPosition().setY(-1 * (1 + y / velocity) * velocity + this.ball.getSize().getY() / 2); this.ball.getVelocity().multiply(new Vector2D(1, -1)); } private void handleBottomHit() { double y = this.environment.getHeight() - (this.ball.getPosition().getY() + this.ball.getSize().getY() / 2); double velocity = this.ball.getVelocity().getY(); this.ball.getPosition().setX(this.ball.getPosition().getX() + this.ball.getVelocity().getX()); this.ball.getPosition().setY(this.environment.getHeight() + (-1 * (1 - y / velocity) * velocity - this.ball.getSize().getY() / 2)); this.ball.getVelocity().multiply(new Vector2D(1, -1)); } private void handleRightHit() { double x = this.environment.getWidth() - (this.ball.getPosition().getX() + this.ball.getSize().getX() / 2); double velocity = this.ball.getVelocity().getX(); this.ball.getPosition().setX(this.environment.getWidth() + (-1 * (1 - x / velocity) * velocity - this.ball.getSize().getX() / 2)); this.ball.getPosition().setY(this.ball.getPosition().getY() + this.ball.getVelocity().getY()); this.ball.getVelocity().multiply(new Vector2D(-1, 1)); } private void handlePaddleHit() { double distance = calculateBallPaddleDistance() - this.ball.getSize().getX() / 2; double maxVelocity = this.ball.getMaxVelocity(); // Step one: Go to hit position Vector2D velocity = Vector2D.limit(this.ball.getVelocity(), (distance / maxVelocity) * maxVelocity); this.ball.getPosition().add(velocity); // Step two: Calculate new velocity depending on the offset from the middle double offset = this.paddle.getPosition().getY() - this.ball.getPosition().getY(); offset /= this.paddle.getSize().getY() / 2; double reflectionAngle = this.maxReflectionAngle * offset; this.ball.getVelocity().setX(maxVelocity * Math.cos(reflectionAngle)); this.ball.getVelocity().setY(-1 * maxVelocity * Math.sin(reflectionAngle)); // Step three: Go remaining distance with new velocity velocity = Vector2D.limit(this.ball.getVelocity(), (1 - distance / maxVelocity) * maxVelocity); this.ball.getPosition().add(velocity); } private boolean checkPaddleCollision() { double ballRadius = this.ball.getSize().getX() / 2; double ballMaxVelocity = this.ball.getMaxVelocity(); double ballXVelocity = this.ball.getVelocity().getX(); return ballRadius + ballMaxVelocity >= calculateBallPaddleDistance() && ballXVelocity < 0; } private double calculateBallPaddleDistance() { double rightPaddleX = this.paddle.getPosition().getX() + this.paddle.getSize().getX() / 2; double upperPaddleY = this.paddle.getPosition().getY() - this.paddle.getSize().getY() / 2; double lowerPaddleY = this.paddle.getPosition().getY() + this.paddle.getSize().getY() / 2; Vector2D upperPaddle = new Vector2D(rightPaddleX, upperPaddleY); Vector2D lowerPaddle = new Vector2D(rightPaddleX, lowerPaddleY); Vector2D ballPosition = new Vector2D(this.ball.getPosition()); double paddleLengthSquared = Math.pow(Vector2D.distance(upperPaddle, lowerPaddle), 2); double lineIntersection = Math.max(0, Math.min(1, Vector2D.subtract(ballPosition, upperPaddle).dotProduct(Vector2D.subtract(lowerPaddle, upperPaddle)) / paddleLengthSquared)); Vector2D nearestPoint = Vector2D.subtract(lowerPaddle, upperPaddle) .multiply(lineIntersection) .add(upperPaddle); return Vector2D.distance(nearestPoint, ballPosition); } private boolean checkForHit() { double ballRadius = this.ball.getSize().getX() / 2; double leftBallX = this.ball.getPosition().getX() - ballRadius; double rightPaddleX = this.paddle.getPosition().getX() + this.paddle.getSize().getX() / 2; if (leftBallX > rightPaddleX) { return false; } double upperPaddleY = this.paddle.getPosition().getY() - this.paddle.getSize().getY() / 2; double lowerPaddleY = this.paddle.getPosition().getY() + this.paddle.getSize().getY() / 2; double upperBallY = this.ball.getPosition().getY() - ballRadius; double lowerBallY = this.ball.getPosition().getY() + ballRadius; return upperPaddleY < lowerBallY && lowerPaddleY > upperBallY; } private boolean checkForMiss() { double ballRadius = this.ball.getSize().getX() / 2; double rightBallX = this.ball.getPosition().getX() - ballRadius; if (rightBallX > 0) { return false; } double upperBallY = this.ball.getPosition().getY() - ballRadius; double lowerBallY = this.ball.getPosition().getY() + ballRadius; double upperPaddleY = this.paddle.getPosition().getY() - this.paddle.getSize().getY() / 2; double lowerPaddleY = this.paddle.getPosition().getY() + this.paddle.getSize().getY() / 2; return !(upperPaddleY < lowerBallY && lowerPaddleY > upperBallY); } private double calculateScoreAfterMiss() { double distanceScore = 1 - Math.abs(this.paddle.getPosition().getY() - this.ball.getPosition().getY()); return this.controller.getScore() + distanceScore / environment.getHeight(); } private double[] createInput() { List<Double> input = new ArrayList<>(); // height of paddle input.add(this.paddle.getPosition().getY() / this.environment.getHeight()); // height of ball input.add(this.ball.getPosition().getY() / this.environment.getHeight()); // x position of the ball input.add(this.ball.getPosition().getX() / this.environment.getWidth()); return input.stream() .mapToDouble(Double::doubleValue) .toArray(); } private double adjustActivation(double activation, AgentController controller) { // 10 and -10 are arbitrary bounds in case of unlimited values double maxActivation = Math.min(controller.getMaxAction(), 10); double minActivation = Math.max(controller.getMinAction(), -10); double upperThreshold = minActivation + (2.0 / 3) * (maxActivation - minActivation); double lowerThreshold = minActivation + (1.0 / 3) * (maxActivation - minActivation); // go up, down or do nothing if (activation < lowerThreshold) { return -1; } else if (activation > upperThreshold) { return 1; } else { return 0; } } private void applyAction(double activation) { double paddleVelocity = this.paddle.getMaxVelocity(); this.paddle.getVelocity().setY(activation * paddleVelocity); } public long getStepNumber() { return this.paddle.getStepNumber(); } public Paddle paddle() { return paddle; } public Ball ball() { return ball; } public AgentController controller() { return controller; } public PongEnvironment environment() { return environment; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || obj.getClass() != this.getClass()) return false; var that = (PaddleBallPair) obj; return Objects.equals(this.paddle, that.paddle) && Objects.equals(this.ball, that.ball) && Objects.equals(this.controller, that.controller) && Objects.equals(this.environment, that.environment); } @Override public int hashCode() { return Objects.hash(paddle, ball, controller, environment); } @Override public String toString() { return "PaddleBallPair[" + "paddle=" + paddle + ", " + "ball=" + ball + ", " + "controller=" + controller + ", " + "environment=" + environment + ']'; } }
40.092652
183
0.635349
5f82a1a805b2bf8205a6023b85a195320dedc7a5
528
package work.inabajun.filterdemo; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.DispatcherType; @Configuration public class SampleConfiguration { @Bean FilterRegistrationBean filter2() { var filter = new FilterRegistrationBean(new SampleFilter2()); filter.addUrlPatterns("/sample"); filter.setOrder(200); return filter; } }
26.4
69
0.75947
51c416173fb61addf7568ab34a30df14873266c9
1,282
package enhancedstream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; public class EnhancedInputStream extends DataInputStream { public EnhancedInputStream(InputStream in) { super(in); } public int readCmpInt() throws IOException { int a = 0; int len = read(); if(len == 0) return 0; int tmp; while(len>0){ tmp = read(); a=(a<<8)+tmp; len--; } return a; } public double readCmpFloat() throws IOException { double tmp = (double)readCmpInt(); int len = read(); if(len == 0) return tmp; int pows = -1; int c = 0; while(len>0){ c = read(); for(int i = 0; i < 8; i++){ if((c&(1<<i))>0) tmp+=Math.pow(2.0, pows); pows--; } len--; } return tmp; } public String readString() throws IOException { int len = readCmpInt(); StringBuilder sb = new StringBuilder(); while(len>0){ sb.append(readChar()); len--; } return sb.toString(); } }
22.103448
58
0.460218
1ead7ee52a9a516ecfdb8d9d17b11b23c8e54217
1,679
package ru.ospos.npf.commons.domain.document.regcard; import lombok.Getter; import lombok.Setter; import ru.ospos.npf.commons.domain.base.FileStorage; import javax.persistence.*; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Objects; @Getter @Setter @Entity(name = "RegistrationCardFile") @Table(name = "registration_card_files") public class RegistrationCardFile implements Serializable { @EmbeddedId private RegistrationCardFileId id; @ManyToOne(fetch = FetchType.LAZY) @MapsId("registrationCardId") @JoinColumn(name = "fk_registration_card") private RegistrationCard registrationCard; @ManyToOne(fetch = FetchType.LAZY) @MapsId("filestorageId") @JoinColumn(name = "fk_file") private FileStorage fileStorage; protected RegistrationCardFile() {} public RegistrationCardFile(RegistrationCard registrationCard, FileStorage fileStorage) { this.registrationCard = registrationCard; this.fileStorage = fileStorage; this.id = new RegistrationCardFileId(registrationCard.getId(), fileStorage.getId()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RegistrationCardFile that = (RegistrationCardFile) o; return Objects.equals(registrationCard, that.registrationCard) && Objects.equals(fileStorage, that.fileStorage); } @Override public int hashCode() { return Objects.hash(registrationCard, fileStorage); } private LocalDateTime creationDate; private Long fkOperator; // TODO }
27.983333
93
0.712924
2f44e83971051a900265f44e373d1ac37192cd7b
977
package com.ibm.lab.stock.repository.vo; public class StockOrderHistoryVo { private String productName; private String adjustmentType; private Long qty; private String orderId; public StockOrderHistoryVo() { } public StockOrderHistoryVo(String productName, String orderId, String adjustmentType, Long qty) { this.productName = productName; this.adjustmentType = adjustmentType; this.qty = qty; this.orderId = orderId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName= productName; } public String getAdjustmentType() { return adjustmentType; } public void setAdjustmentType(String adjustmentType) { this.adjustmentType = adjustmentType; } public Long getQty() { return qty; } public void setQty(Long qty) { this.qty = qty; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } }
18.092593
98
0.74002
fe2ebf907e0d7fb9035cc46c6171df7f19c4f0cd
6,176
/* * * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ package org.apache.geode.cache.client.internal; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.apache.geode.CancelCriterion; import org.apache.geode.cache.client.internal.pooling.ConnectionManager; import org.apache.geode.distributed.internal.ServerLocation; public class OpExecutorImplUnitTest { private OpExecutorImpl executor; private ConnectionManager connectionManager; private QueueManager queueManager; private EndpointManager endpointManager; private RegisterInterestTracker tracker; private CancelCriterion cancelCriterion; private PoolImpl pool; private ServerLocation server; private Connection connection; private AbstractOp op; @Before public void before() throws Exception { connectionManager = mock(ConnectionManager.class); queueManager = mock(QueueManager.class); endpointManager = mock(EndpointManager.class); tracker = mock(RegisterInterestTracker.class); cancelCriterion = mock(CancelCriterion.class); server = mock(ServerLocation.class); connection = mock(Connection.class); pool = mock(PoolImpl.class); op = mock(AbstractOp.class); when(connection.getServer()).thenReturn(server); executor = new OpExecutorImpl(connectionManager, queueManager, endpointManager, tracker, 1, 5L, 5L, cancelCriterion, pool); } @Test public void authenticateIfRequired_noOp_WhenNotRequireCredential() { when(server.getRequiresCredentials()).thenReturn(false); executor.authenticateIfMultiUser(connection, op); verify(pool, never()).executeOn(any(Connection.class), any(Op.class)); } @Test public void authenticateIfRequired_noOp_WhenOpNeedsNoUserId() { when(server.getRequiresCredentials()).thenReturn(true); when(op.needsUserId()).thenReturn(false); executor.authenticateIfMultiUser(connection, op); verify(pool, never()).executeOn(any(Connection.class), any(Op.class)); } @Test public void authenticateIfRequired_noOp_singleUser_hasId() { when(server.getRequiresCredentials()).thenReturn(true); when(op.needsUserId()).thenReturn(true); when(pool.getMultiuserAuthentication()).thenReturn(false); when(server.getUserId()).thenReturn(123L); executor.authenticateIfMultiUser(connection, op); verify(pool, never()).executeOn(any(Connection.class), any(Op.class)); } @Test public void authenticateIfRequired_setId_singleUser_hasNoId() { when(server.getRequiresCredentials()).thenReturn(true); when(op.needsUserId()).thenReturn(true); when(pool.getMultiuserAuthentication()).thenReturn(false); when(server.getUserId()).thenReturn(-1L); when(pool.executeOn(any(Connection.class), any(Op.class))).thenReturn(123L); when(connection.getWrappedConnection()).thenReturn(connection); executor.authenticateIfMultiUser(connection, op); verify(pool, never()).executeOn(any(Connection.class), any(Op.class)); } @Test public void execute_calls_authenticateIfMultiUser() throws Exception { when(connection.execute(any())).thenReturn(123L); when(connectionManager.borrowConnection(5)).thenReturn(connection); OpExecutorImpl spy = spy(executor); spy.execute(op, 1); verify(spy).authenticateIfMultiUser(any(), any()); } @Test public void authenticateIfMultiUser_calls_authenticateMultiUser() { OpExecutorImpl spy = spy(executor); when(connection.getServer()).thenReturn(server); when(pool.executeOn(any(ServerLocation.class), any())).thenReturn(123L); UserAttributes userAttributes = new UserAttributes(null, null); when(server.getRequiresCredentials()).thenReturn(false); spy.authenticateIfMultiUser(connection, op); verify(spy, never()).authenticateMultiuser(any(), any(), any()); when(server.getRequiresCredentials()).thenReturn(true); when(op.needsUserId()).thenReturn(false); spy.authenticateIfMultiUser(connection, op); verify(spy, never()).authenticateMultiuser(any(), any(), any()); when(server.getRequiresCredentials()).thenReturn(true); when(op.needsUserId()).thenReturn(true); when(pool.getMultiuserAuthentication()).thenReturn(false); spy.authenticateIfMultiUser(connection, op); verify(spy, never()).authenticateMultiuser(any(), any(), any()); when(server.getRequiresCredentials()).thenReturn(true); when(op.needsUserId()).thenReturn(true); when(pool.getMultiuserAuthentication()).thenReturn(true); spy.authenticateIfMultiUser(connection, op); verify(spy, never()).authenticateMultiuser(any(), any(), any()); when(server.getRequiresCredentials()).thenReturn(true); when(op.needsUserId()).thenReturn(true); when(pool.getMultiuserAuthentication()).thenReturn(true); doReturn(userAttributes).when(spy).getUserAttributesFromThreadLocal(); spy.authenticateIfMultiUser(connection, op); verify(spy).authenticateMultiuser(pool, connection, userAttributes); // calling it again wont' increase the invocation time spy.authenticateIfMultiUser(connection, op); verify(spy).authenticateMultiuser(pool, connection, userAttributes); } }
40.631579
100
0.756801
22bb522c0deb1781fb2a5a55388d544ff0895aef
721
package p5; public class P5D { public static void main(String[] args) { char[][] grid = new char[6][5]; char nextChar = 'a'; for(int row = 0; row < grid.length; row++ ) { for( int col = 0; col < grid[0].length; col++) { grid[row][col] = nextChar; if(nextChar == 'z') { nextChar = 'a'; } else { nextChar++; } } } for(int row = 0; row < grid.length; row++) { for (int col = 0; col < grid[0].length; col ++) { System.out.print(grid[row][col] + " "); } System.out.print("\n"); } } }
24.033333
61
0.385576
f33159bbaae05b601ade591b30f77755ba57cf39
2,723
package co.airy.mapping; import co.airy.mapping.model.Image; import co.airy.mapping.model.Text; import co.airy.mapping.sources.google.GoogleMapper; import org.junit.jupiter.api.Test; import org.springframework.util.StreamUtils; import java.nio.charset.StandardCharsets; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; public class GoogleTest { private final GoogleMapper mapper = new GoogleMapper(); @Test void canRenderText() throws Exception { final String textContent = "Hello World"; final String sourceContent = String.format(StreamUtils.copyToString(getClass().getClassLoader() .getResourceAsStream("google/text.json"), StandardCharsets.UTF_8), textContent); final Text message = (Text) mapper.render(sourceContent).get(0); assertThat(message.getText(), equalTo(textContent)); } @Test void canRenderImage() throws Exception { final String signedImageUrl = "https://storage.googleapis.com/business-messages-us/936640919331/jzsu6cdguNGsBhmGJGuLs1DS?x-goog-algorithm\u003dGOOG4-RSA-SHA256\u0026x-goog-credential\u003duranium%40rcs-uranium.iam.gserviceaccount.com%2F20190826%2Fauto%2Fstorage%2Fgoog4_request\u0026x-goog-date\u003d20190826T201038Z\u0026x-goog-expires\u003d604800\u0026x-goog-signedheaders\u003dhost\u0026x-goog-signature\u003d89dbf7a74d21ab42ad25be071b37840a544a43d68e67270382054e1442d375b0b53d15496dbba12896b9d88a6501cac03b5cfca45d789da3e0cae75b050a89d8f54c1ffb27e467bd6ba1d146b7d42e30504c295c5c372a46e44728f554ba74b7b99bd9c6d3ed45f18588ed1b04522af1a47330cff73a711a6a8c65bb15e3289f480486f6695127e1014727cac949e284a7f74afd8220840159c589d48dddef1cc97b248dfc34802570448242eac4d7190b1b10a008404a330b4ff6f9656fa84e87f9a18ab59dc9b91e54ad11ffdc0ad1dc9d1ccc7855c0d263d93fce6f999971ec79879f922b582cf3bb196a1fedc3eefa226bb412e49af7dfd91cc072608e98"; final String sourceContent = String.format(StreamUtils.copyToString(getClass().getClassLoader() .getResourceAsStream("google/text.json"), StandardCharsets.UTF_8), signedImageUrl); final Image message = (Image) mapper.render(sourceContent).get(0); assertThat(message.getUrl(), equalTo(signedImageUrl)); } @Test void canRenderSuggestionResponses() throws Exception { final String textContent = "Hello World"; final String sourceContent = String.format(StreamUtils.copyToString(getClass().getClassLoader() .getResourceAsStream("google/suggestionResponse.json"), StandardCharsets.UTF_8), textContent); final Text message = (Text) mapper.render(sourceContent).get(0); assertThat(message.getText(), equalTo(textContent)); } }
57.93617
934
0.795813
c08335d48cb91c584afcacbc025e99a56ba2eb2c
773
package com.lara; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.SQLException; public class Manager5 { public static void main(String arg[]) { Connection con=null; Statement st=null; ResultSet rs=null; try { con=Manager3.getConnection(); st=con.createStatement(); String sql="select * from tab3"; rs=st.executeQuery(sql); while(rs.next()) { System.out.println(rs.getString(1)+","); System.out.println(rs.getString(2)+","); } } catch(SQLException ex) { System.out.println(ex); } finally { Manager3.closeAll(null, st, con); } } }
19.820513
48
0.5511
d90b93ff211068e274b681bc9bff186484184f1b
2,163
package Jtrdr; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.JButton; import javax.swing.JInternalFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableCellRenderer; import org.apache.log4j.Logger; import kx.c.KException; import net.miginfocom.swing.MigLayout; public class FrameTableNoTimer { final static Logger logger=Logger.getLogger(FrameTableNoTimer.class); private ReadTable tab=null; private String query; public FrameTableNoTimer(FrameMain jfr, String title, String query,int x,int y,int width,int height) { this.query=query; JInternalFrame acFrame = new JInternalFrame(title, true,true,true,true); try { tab = new ReadTable(query); } catch (KException|IOException e1) { logger.fatal("showTable - "+title+" - "+e1); } JTable table = new JTable(tab.model()); table.setForeground(Color.white); table.setBackground(Color.gray); table.setFont(jfr.font()); table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer(){ @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); c.setBackground(row % 2 == 0 ? Color.darkGray : Color.black); return c; } }); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); TableColumnAdjuster tca = new TableColumnAdjuster(table); tca.adjustColumns(); JScrollPane scrollPane = new JScrollPane(); table.setAutoCreateRowSorter(true); scrollPane.setViewportView(table); acFrame.getContentPane().add(scrollPane); acFrame.setLocation(x, y); acFrame.setSize(width, height); acFrame.setVisible(true); jfr.dtp().add(acFrame); acFrame.toFront(); } }
36.05
147
0.704577
4d88aafc160a1afb12d8b64f1d94d488e5fe2fb0
3,408
/* * Tencent is pleased to support the open source community by making BK-JOB蓝鲸智云作业平台 available. * * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. * * BK-JOB蓝鲸智云作业平台 is licensed under the MIT License. * * License for BK-JOB蓝鲸智云作业平台: * -------------------------------------------------------------------- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of * the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package com.tencent.bk.job.execute.model.web.vo; import com.fasterxml.jackson.annotation.JsonInclude; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @ApiModel("文件分发执行详情") @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class FileDistributionDetailVO implements Comparable { @ApiModelProperty(name = "taskId", value = "文件任务ID,用于检索单个文件分发的结果") private String taskId; @ApiModelProperty(name = "destIp", value = "下载目标IP") private String destIp; @ApiModelProperty(name = "srcIp", value = "上传源IP") private String srcIp; @ApiModelProperty("文件名称") private String fileName; @ApiModelProperty("文件大小") private String fileSize; @ApiModelProperty("状态,0-Pulling,1-Waiting,2-Uploading,3-Downloading,4-Finished,5-Failed") private Integer status; @ApiModelProperty("状态描述") private String statusDesc; @ApiModelProperty("速率") private String speed; @ApiModelProperty("进度") private String progress; @ApiModelProperty("文件任务上传下载标识,0-上传,1-下载") private Integer mode; @ApiModelProperty("日志内容") private String logContent; @Override public int compareTo(Object o) { if (o == null) { return 1; } FileDistributionDetailVO other = (FileDistributionDetailVO) o; // 从文件源拉取文件的详情日志放在最前面 if (this.status == 0 && other.status > 0) { return -1; } int compareFileNameResult = compareString(this.fileName, other.getFileName()); if (compareFileNameResult != 0) { return compareFileNameResult; } return compareString(this.srcIp, other.getSrcIp()); } private int compareString(String a, String b) { if (a == null && b == null) { return 0; } else if (a != null && b == null) { return 1; } else if (a == null) { return -1; } else { return a.compareTo(b); } } }
38.727273
116
0.676056
74fc607fe3d05514c498412ce667c9b9dd1e65a1
5,000
package org.pcap4j.packet; import static org.junit.Assert.*; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.pcap4j.packet.IpV6ExtHopByHopOptionsPacket.IpV6ExtHopByHopOptionsHeader; import org.pcap4j.packet.IpV6ExtOptionsPacket.IpV6Option; import org.pcap4j.packet.namednumber.EtherType; import org.pcap4j.packet.namednumber.IpNumber; import org.pcap4j.packet.namednumber.IpVersion; import org.pcap4j.packet.namednumber.UdpPort; import org.pcap4j.util.MacAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings("javadoc") public class IpV6ExtHopByHopOptionsPacketTest extends AbstractPacketTest { private static final Logger logger = LoggerFactory.getLogger(IpV6ExtHopByHopOptionsPacketTest.class); private final IpNumber nextHeader; private final byte hdrExtLen; private final List<IpV6Option> options; private final IpV6ExtHopByHopOptionsPacket packet; private final Inet6Address srcAddr; private final Inet6Address dstAddr; public IpV6ExtHopByHopOptionsPacketTest() throws Exception { this.nextHeader = IpNumber.UDP; this.hdrExtLen = (byte) 0; this.options = new ArrayList<IpV6Option>(); options.add(IpV6Pad1Option.getInstance()); options.add(new IpV6PadNOption.Builder().data(new byte[] {0, 0, 0}).dataLen((byte) 3).build()); try { srcAddr = (Inet6Address) InetAddress.getByName("2001:db8::3:2:1"); dstAddr = (Inet6Address) InetAddress.getByName("2001:db8::3:2:2"); } catch (UnknownHostException e) { throw new AssertionError(); } UnknownPacket.Builder anonb = new UnknownPacket.Builder(); anonb.rawData(new byte[] {(byte) 0, (byte) 1, (byte) 2, (byte) 3}); UdpPacket.Builder udpb = new UdpPacket.Builder(); udpb.dstPort(UdpPort.getInstance((short) 0)) .srcPort(UdpPort.SNMP_TRAP) .dstAddr(dstAddr) .srcAddr(srcAddr) .payloadBuilder(anonb) .correctChecksumAtBuild(true) .correctLengthAtBuild(true); IpV6ExtHopByHopOptionsPacket.Builder b = new IpV6ExtHopByHopOptionsPacket.Builder(); b.nextHeader(nextHeader) .hdrExtLen(hdrExtLen) .options(options) .correctLengthAtBuild(false) .payloadBuilder(udpb); this.packet = b.build(); } @Override protected Packet getPacket() { return packet; } @Override protected Packet getWholePacket() { IpV6Packet.Builder IpV6b = new IpV6Packet.Builder(); IpV6b.version(IpVersion.IPV6) .trafficClass(IpV6SimpleTrafficClass.newInstance((byte) 0x12)) .flowLabel(IpV6SimpleFlowLabel.newInstance(0x12345)) .nextHeader(IpNumber.IPV6_HOPOPT) .hopLimit((byte) 100) .srcAddr(srcAddr) .dstAddr(dstAddr) .payloadBuilder(packet.getBuilder()) .correctLengthAtBuild(true); EthernetPacket.Builder eb = new EthernetPacket.Builder(); eb.dstAddr(MacAddress.getByName("fe:00:00:00:00:02")) .srcAddr(MacAddress.getByName("fe:00:00:00:00:01")) .type(EtherType.IPV6) .payloadBuilder(IpV6b) .paddingAtBuild(true); eb.get(UdpPacket.Builder.class).dstAddr(dstAddr).srcAddr(srcAddr); return eb.build(); } @BeforeClass public static void setUpBeforeClass() throws Exception { logger.info( "########## " + IpV6ExtHopByHopOptionsPacketTest.class.getSimpleName() + " START ##########"); } @AfterClass public static void tearDownAfterClass() throws Exception {} @Test public void testNewPacket() { try { IpV6ExtHopByHopOptionsPacket p = IpV6ExtHopByHopOptionsPacket.newPacket( packet.getRawData(), 0, packet.getRawData().length); assertEquals(packet, p); } catch (IllegalRawDataException e) { throw new AssertionError(e); } } @Test public void testGetHeader() { IpV6ExtHopByHopOptionsHeader h = packet.getHeader(); assertEquals(nextHeader, h.getNextHeader()); assertEquals(hdrExtLen, h.getHdrExtLen()); assertEquals(options.size(), h.getOptions().size()); Iterator<IpV6Option> iter = h.getOptions().iterator(); for (IpV6Option opt : options) { assertEquals(opt, iter.next()); } IpV6ExtHopByHopOptionsPacket.Builder b = packet.getBuilder(); IpV6ExtHopByHopOptionsPacket p; b.hdrExtLen((byte) 0); p = b.build(); assertEquals((byte) 0, (byte) p.getHeader().getHdrExtLenAsInt()); b.hdrExtLen((byte) -1); p = b.build(); assertEquals((byte) -1, (byte) p.getHeader().getHdrExtLenAsInt()); b.hdrExtLen((byte) 127); p = b.build(); assertEquals((byte) 127, (byte) p.getHeader().getHdrExtLenAsInt()); b.hdrExtLen((byte) -128); p = b.build(); assertEquals((byte) -128, (byte) p.getHeader().getHdrExtLenAsInt()); } }
31.847134
99
0.6976
440edcaff181ce786e2c78971466a01598652b54
7,279
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.apollographql.apollo.internal.subscription; import com.apollographql.apollo.subscription.OperationServerMessage; import java.util.concurrent.Executor; // Referenced classes of package com.apollographql.apollo.internal.subscription: // RealSubscriptionManager private static final class RealSubscriptionManager$SubscriptionTransportCallback implements com.apollographql.apollo.subscription.SubscriptionTransport.Callback { public void onConnected() { dispatcher.execute(new Runnable() { public void run() { _flddelegate.onTransportConnected(); // 0 0:aload_0 // 1 1:getfield #20 <Field RealSubscriptionManager$SubscriptionTransportCallback this$0> // 2 4:invokestatic #28 <Method RealSubscriptionManager RealSubscriptionManager$SubscriptionTransportCallback.access$000(RealSubscriptionManager$SubscriptionTransportCallback)> // 3 7:invokevirtual #31 <Method void RealSubscriptionManager.onTransportConnected()> // 4 10:return } final RealSubscriptionManager.SubscriptionTransportCallback this$0; { this$0 = RealSubscriptionManager.SubscriptionTransportCallback.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #20 <Field RealSubscriptionManager$SubscriptionTransportCallback this$0> super(); // 3 5:aload_0 // 4 6:invokespecial #22 <Method void Object()> // 5 9:return } } ); // 0 0:aload_0 // 1 1:getfield #28 <Field Executor dispatcher> // 2 4:new #11 <Class RealSubscriptionManager$SubscriptionTransportCallback$1> // 3 7:dup // 4 8:aload_0 // 5 9:invokespecial #35 <Method void RealSubscriptionManager$SubscriptionTransportCallback$1(RealSubscriptionManager$SubscriptionTransportCallback)> // 6 12:invokeinterface #41 <Method void Executor.execute(Runnable)> // 7 17:return } public void onFailure(final Throwable t) { dispatcher.execute(new Runnable() { public void run() { _flddelegate.onTransportFailure(t); // 0 0:aload_0 // 1 1:getfield #22 <Field RealSubscriptionManager$SubscriptionTransportCallback this$0> // 2 4:invokestatic #33 <Method RealSubscriptionManager RealSubscriptionManager$SubscriptionTransportCallback.access$000(RealSubscriptionManager$SubscriptionTransportCallback)> // 3 7:aload_0 // 4 8:getfield #24 <Field Throwable val$t> // 5 11:invokevirtual #36 <Method void RealSubscriptionManager.onTransportFailure(Throwable)> // 6 14:return } final RealSubscriptionManager.SubscriptionTransportCallback this$0; final Throwable val$t; { this$0 = RealSubscriptionManager.SubscriptionTransportCallback.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #22 <Field RealSubscriptionManager$SubscriptionTransportCallback this$0> t = throwable; // 3 5:aload_0 // 4 6:aload_2 // 5 7:putfield #24 <Field Throwable val$t> super(); // 6 10:aload_0 // 7 11:invokespecial #27 <Method void Object()> // 8 14:return } } ); // 0 0:aload_0 // 1 1:getfield #28 <Field Executor dispatcher> // 2 4:new #13 <Class RealSubscriptionManager$SubscriptionTransportCallback$2> // 3 7:dup // 4 8:aload_0 // 5 9:aload_1 // 6 10:invokespecial #46 <Method void RealSubscriptionManager$SubscriptionTransportCallback$2(RealSubscriptionManager$SubscriptionTransportCallback, Throwable)> // 7 13:invokeinterface #41 <Method void Executor.execute(Runnable)> // 8 18:return } public void onMessage(final OperationServerMessage message) { dispatcher.execute(new Runnable() { public void run() { _flddelegate.onOperationServerMessage(message); // 0 0:aload_0 // 1 1:getfield #22 <Field RealSubscriptionManager$SubscriptionTransportCallback this$0> // 2 4:invokestatic #33 <Method RealSubscriptionManager RealSubscriptionManager$SubscriptionTransportCallback.access$000(RealSubscriptionManager$SubscriptionTransportCallback)> // 3 7:aload_0 // 4 8:getfield #24 <Field OperationServerMessage val$message> // 5 11:invokevirtual #36 <Method void RealSubscriptionManager.onOperationServerMessage(OperationServerMessage)> // 6 14:return } final RealSubscriptionManager.SubscriptionTransportCallback this$0; final OperationServerMessage val$message; { this$0 = RealSubscriptionManager.SubscriptionTransportCallback.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #22 <Field RealSubscriptionManager$SubscriptionTransportCallback this$0> message = operationservermessage; // 3 5:aload_0 // 4 6:aload_2 // 5 7:putfield #24 <Field OperationServerMessage val$message> super(); // 6 10:aload_0 // 7 11:invokespecial #27 <Method void Object()> // 8 14:return } } ); // 0 0:aload_0 // 1 1:getfield #28 <Field Executor dispatcher> // 2 4:new #15 <Class RealSubscriptionManager$SubscriptionTransportCallback$3> // 3 7:dup // 4 8:aload_0 // 5 9:aload_1 // 6 10:invokespecial #51 <Method void RealSubscriptionManager$SubscriptionTransportCallback$3(RealSubscriptionManager$SubscriptionTransportCallback, OperationServerMessage)> // 7 13:invokeinterface #41 <Method void Executor.execute(Runnable)> // 8 18:return } private final RealSubscriptionManager _flddelegate; private final Executor dispatcher; /* static RealSubscriptionManager access$000(RealSubscriptionManager$SubscriptionTransportCallback realsubscriptionmanager$subscriptiontransportcallback) { return realsubscriptionmanager$subscriptiontransportcallback._flddelegate; // 0 0:aload_0 // 1 1:getfield #26 <Field RealSubscriptionManager _flddelegate> // 2 4:areturn } */ RealSubscriptionManager$SubscriptionTransportCallback(RealSubscriptionManager realsubscriptionmanager, Executor executor) { // 0 0:aload_0 // 1 1:invokespecial #24 <Method void Object()> _flddelegate = realsubscriptionmanager; // 2 4:aload_0 // 3 5:aload_1 // 4 6:putfield #26 <Field RealSubscriptionManager _flddelegate> dispatcher = executor; // 5 9:aload_0 // 6 10:aload_2 // 7 11:putfield #28 <Field Executor dispatcher> // 8 14:return } }
40.438889
189
0.640473
ee013a071f349e58b62b3fef51fc642a78bf0089
1,237
package com.temelt.schmgt.web.entity.yonetim; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import com.temelt.schmgt.web.entity.BaseEntity; @Entity @Table(name = "group_day") public class GrupGun extends BaseEntity{ private Long id; private Grup grup; private Gun gun; @Id @SequenceGenerator(name = "seq_group_day", allocationSize = 1, sequenceName = "seq_group_day") @GeneratedValue(generator = "seq_group_day", strategy = GenerationType.SEQUENCE) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @ManyToOne @JoinColumn(name = "group_id") public Grup getGrup() { return grup; } public void setGrup(Grup grup) { this.grup = grup; } @ManyToOne @JoinColumn(name = "days_id") public Gun getGun() { return gun; } public void setGun(Gun gun) { this.gun = gun; } }
22.907407
99
0.651576
1e8c37f90c895d934f1fd23876862ece645cac0e
2,662
package org.folio.services; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toList; import static org.folio.invoices.utils.HelperUtils.buildIdsChunks; import static org.folio.invoices.utils.HelperUtils.collectResultsOnSuccess; import static org.folio.invoices.utils.HelperUtils.convertIdsToCqlQuery; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import org.folio.rest.acq.model.VoucherLine; import org.folio.rest.acq.model.VoucherLineCollection; import org.folio.rest.impl.VoucherLineHelper; import org.folio.rest.jaxrs.model.Voucher; import org.folio.rest.jaxrs.model.VoucherCollection; import io.vertx.core.Context; public class VoucherLinesRetrieveService { static final int MAX_IDS_FOR_GET_RQ = 15; private final VoucherLineHelper voucherLineHelper; public VoucherLinesRetrieveService(Map<String, String> okapiHeaders, Context ctx, String lang) { this.voucherLineHelper = new VoucherLineHelper(okapiHeaders, ctx, lang); } public CompletableFuture<Map<String, List<VoucherLine>>> getVoucherLinesMap(VoucherCollection voucherCollection) { CompletableFuture<Map<String, List<VoucherLine>>> future = new CompletableFuture<>(); getVoucherLinesByChunks(voucherCollection.getVouchers()) .thenApply(voucherLineCollections -> voucherLineCollections.stream() .map(VoucherLineCollection::getVoucherLines) .collect(toList()).stream() .flatMap(List::stream) .collect(Collectors.toList())) .thenAccept(voucherLines -> future.complete(voucherLines.stream().collect(groupingBy(VoucherLine::getVoucherId)))) .thenAccept(v -> voucherLineHelper.closeHttpClient()) .exceptionally(t -> { future.completeExceptionally(t); voucherLineHelper.closeHttpClient(); return null; }); return future; } public CompletableFuture<List<VoucherLineCollection>> getVoucherLinesByChunks(List<Voucher> vouchers) { List<CompletableFuture<VoucherLineCollection>> invoiceFutureList = buildIdsChunks(vouchers, MAX_IDS_FOR_GET_RQ).values() .stream() .map(this::buildVoucherLinesQuery) .map(query -> voucherLineHelper.getVoucherLines(MAX_IDS_FOR_GET_RQ, 0, query)) .collect(Collectors.toList()); return collectResultsOnSuccess(invoiceFutureList); } private String buildVoucherLinesQuery(List<Voucher> vouchers) { List<String> voucherIds = vouchers.stream() .map(Voucher::getId) .collect(Collectors.toList()); return convertIdsToCqlQuery(voucherIds, "voucherId", true); } }
40.333333
124
0.764838
13ed6fe54b1f9a1ff9bbc8347e1c2428b7a49a9f
542
// recursive solution public class Solution { public double pow(double x, int n) { if (n == Integer.MIN_VALUE) { if (Math.abs(x) > 1.0) return 0.0; else return x * pow(x, Integer.MAX_VALUE); // abs(Integer.MIN_VALUE) - 1 = Integer.MAX_VALUE } if (n == 0 || Math.abs(x - 1) < 10e-9) return 1.0; if (n == 1) return x; if (n < 0) return 1 / pow(x, -n); if (n % 2 == 1) return x * pow(x * x, n / 2); else return pow(x * x, n / 2); } }
33.875
104
0.472325
31c9c1294b8914c5c609ed3384246b80d8aac524
6,255
package com.ybj366533.videolib.videoplayer; import android.view.Surface; import com.ybj366533.videolib.utils.LogUtils; import java.lang.ref.WeakReference; /** * Created by YY on 2018/1/23. */ public class VideoPlayer { public interface IYYVideoPlayerListener { void onPrepared(VideoPlayer player); void onCompletion(VideoPlayer player, int errorCode); } public interface IYYVideoPlayerLogOutput { void onLogOutput(String logMsg); } private static boolean _libraryLoaded = false; public static final int YY_PLAYER_EVT_INITED = 0x9000; public static final int YY_PLAYER_EVT_PREPARED = 0x9001; public static final int YY_PLAYER_EVT_FINISHED = 0x9002; public static final int YY_PLAYER_STREAM_OPENED = 0x5000; public static final int YY_PLAYER_STREAM_STREAMING = 0x5001; public static final int YY_PLAYER_STREAM_PAUSED = 0x5002; public static final int YY_PLAYER_STREAM_EOF = 0x5003; public static final int YY_PLAYER_STREAM_UNKNOWN = 0x5099; private IYYVideoPlayerListener iPlayerListener; private static IYYVideoPlayerLogOutput iPlayerLogOutput; String playUrl; Surface mOutputSurface; private int videoWidth; private int videoHeight; private long mNativeMediaPlayer; boolean isPaused = false; public int getVideoWidth() { return videoWidth; } public int getVideoHeight() { return videoHeight; } public VideoPlayer(String url) { synchronized(VideoPlayer.class) { if(!_libraryLoaded) { try { System.loadLibrary("yyvideo"); } catch (Exception ex) { ex.printStackTrace(); } _libraryLoaded = true; } } playUrl = url; } public void setUrl(String url) { playUrl = url; } public void setSurface(Surface surface) { mOutputSurface = surface; } public void play() { // if (playUrl == null || mOutputSurface == null) { // return; // } if (playUrl == null) { return; } mNativeMediaPlayer = _play(playUrl,new WeakReference<VideoPlayer>(this), mOutputSurface); if (mNativeMediaPlayer == 0) { return; } return; } public void close() { if (mNativeMediaPlayer != 0) { _close(mNativeMediaPlayer); mNativeMediaPlayer = 0; } } public void pauseVideo() { isPaused = true; if (mNativeMediaPlayer != 0) { _pause(mNativeMediaPlayer); } return; } public void resumeVideo() { if (mNativeMediaPlayer != 0) { _resume(mNativeMediaPlayer); } isPaused = false; } public int seekTo(int milli) { if (mNativeMediaPlayer != 0) { int duration = _getDuration(mNativeMediaPlayer); if(duration > 0 && milli > duration) { milli = milli % duration; } return _seekTo(mNativeMediaPlayer, milli); } return 0; } public int getDuration() { if (mNativeMediaPlayer != 0) { return _getDuration(mNativeMediaPlayer); } return 0; } public int currentTimestamp() { if (mNativeMediaPlayer != 0) { return _currentTimestamp(mNativeMediaPlayer); } return 0; } public int pullAudioData(byte[] buff) { if (mNativeMediaPlayer != 0) { return _pullAudioData(mNativeMediaPlayer, buff, buff.length); } return 0; } public int checkStreamStatus() { if (mNativeMediaPlayer != 0) { return _checkStreamStatus(mNativeMediaPlayer); } return YY_PLAYER_STREAM_UNKNOWN; } public int setRange(int s, int e) { if (mNativeMediaPlayer != 0) { return _setRange(mNativeMediaPlayer, s, e); } return 0; } private void postEventFromNative(int event, int arg1, int arg2){ if (iPlayerListener != null) { if (event == YY_PLAYER_EVT_PREPARED) { this.videoWidth = arg1; this.videoHeight = arg2; iPlayerListener.onPrepared(this); } else if (event == YY_PLAYER_EVT_FINISHED) { iPlayerListener.onCompletion(this,arg1); } else { // TODO: } } } public void setLogLevel(int level) { _setLogLevel(level); } public void setPlayerEventLisenter(IYYVideoPlayerListener l) { this.iPlayerListener = l; } private native long _play(String url, Object YYVideoPlayer_this, Object surface); private native void _close(long nativeMediaPlayer); private native void _pause(long nativeMediaPlayer); private native void _resume(long nativeMediaPlayer); private native int _seekTo(long nativeMediaPlayer, int milli); private native int _getDuration(long nativeMediaPlayer); private native int _currentTimestamp(long nativeMediaPlayer); private native int _pullAudioData(long nativeMediaPlayer, byte[] buff, int size); private native int _checkStreamStatus(long nativeMediaPlayer); private native int _setRange(long nativeMediaPlayer, int startMilli, int endMilli); private native void _setLogLevel(int level); private static void postEventFromNative(Object weakThiz, int event, int arg1, int arg2){ if (weakThiz != null) { VideoPlayer player = ((WeakReference<VideoPlayer>) weakThiz).get(); if (player != null) { player.postEventFromNative(event, arg1, arg2); } } } public static void setPlayerLogOutput(IYYVideoPlayerLogOutput l) { //VideoPlayer.iPlayerLogOutput = l; VideoPlayer.iPlayerLogOutput = null; //防止static内存泄露 } private static void postLogFromNative(String logMsg) { LogUtils.LOGI("YY_NDK", logMsg); // if(iPlayerLogOutput!= null) { // iPlayerLogOutput.onLogOutput(logMsg); // } } }
24.433594
97
0.607514
1af583b11a8c6f0b169ec509caefde18bb0d36ef
2,063
package com.majors.paranshusinghal.krishi; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; public class ScreenSlidePageFragment extends Fragment { private Context ctx; private static final String TAGlog = "myTAG"; private String cropType; private int position; private TextView textView; private String[] tabs; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ctx = getContext(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle args = getArguments(); cropType = args.getString("cropType"); position = args.getInt("position"); tabs = ctx.getResources().getStringArray(R.array.crop_category); ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_screen_slide_page, container, false); textView = (TextView)rootView.findViewById(R.id.textView); getText(); return rootView; } public void getText(){ InputStream input; try { input = ctx.getAssets().open("crop.txt"); int size = input.available(); byte[] buffer = new byte[size]; input.read(buffer); input.close(); String text = new String(buffer); try { JSONObject json = new JSONObject(text); String abc = json.getJSONObject(cropType).getString(tabs[position]); textView.setText(abc); } catch (Throwable e) { Log.d(TAGlog, e.getMessage());} } catch (IOException e) { Log.d(TAGlog, e.getMessage()); e.printStackTrace(); } } }
29.471429
113
0.638875
08f6d1b3abc16734a6b9d594bc149b7e1551f714
7,709
package to.ares.gamecenter.games.snowwar.objects; import to.ares.gamecenter.games.snowwar.room.SnowWarRoom; import to.ares.gamecenter.games.snowwar.stages.SynchronizedStage; import to.ares.gamecenter.util.MathUtil; import to.ares.gamecenter.games.snowwar.room.pathfinding.*; public class SnowBallObject extends BaseObject { private static int _4s = 0; private static int _09I = 1; private static int _x2 = 2; private static int _2t9 = 3000; private static int _3uf = 60000; public static int _0Wg = 3; public static int _0Po = 15; public static int[] boundingData = new int[]{400}; public SnowWarRoom currentSnowWar; private final PlayerTile currentLocation; private final Direction360 direction; private int launchType; private int speed; private int ttl; private HumanObject ballOwner; private int paraOffs; public SnowBallObject(final SnowWarRoom room){ super(11); currentSnowWar = room; currentLocation = new PlayerTile(0, 0, 0); direction = new Direction360(0); } private void setCurLocation(int x, int y, int z) { currentSnowWar.checksum += (x * 3) - (getVariable(2) * 3); currentSnowWar.checksum += (y * 4) - (getVariable(3) * 4); currentSnowWar.checksum += (z * 5) - (getVariable(4) * 5); currentLocation.setXYZ(x, y, z); } private void setTtl(int val) { currentSnowWar.checksum += (val * 8) - (getVariable(7) * 8); ttl = val; } private void setOwner(HumanObject val) { if(val == null) { currentSnowWar.checksum += (-1 * 9) - (getVariable(8) * 9); } else { currentSnowWar.checksum += (val.objectId * 9) - (getVariable(8) * 9); } ballOwner = val; } public void initialize(int x, int y, int type, int destX, int destY, HumanObject owner) { currentLocation.setXYZ(x, y, _2t9); int deltaX = (destX - x); int deltaY = (destY - y); deltaX = MathUtil._43Z((deltaX / 200)); deltaY = MathUtil._43Z((deltaY / 200)); direction._1ji(Direction360.getRot(deltaX, deltaY)); int local7 = (SquareRoot.squareRoot((deltaX * deltaX) + (deltaY * deltaY)) * 200); launchType = type; getMoveType(type, local7); if (launchType == _4s){ int _0v2 = 20000; int _2pR = 2000; ttl = (_0v2 / _2pR); speed = _2pR; } else { if (launchType == _09I){ local7 = Math.min(local7, _3uf); double _tO = 0.000559; ttl = (int) (local7 * _tO); speed = ((ttl)==0) ? 0 : MathUtil._43Z((local7 / ttl)); } else { if (launchType == _x2){ int _3Xd = 100000; local7 = Math.min(local7, _3Xd); double _1Zn = 0.000707213578500707; ttl = (int) (local7 * _1Zn); speed = ((ttl)==0) ? 0 : MathUtil._43Z((local7 / ttl)); } } } paraOffs = MathUtil._43Z((ttl / 2)); ballOwner = owner; } private void getMoveType(int _arg1,int _arg2){ int TOPLAYER = 3; if (_arg1 == TOPLAYER){ int _3uE = 42000; if (_arg2 <= _3uE){ launchType = _4s; } else { if (_arg2 <= _3uf){ launchType = _09I; } else { launchType = _x2; } } } else { launchType = _arg1; } } @Override public int getVariable(int val){ if(val == 0) { return SNOWBALL; } if(val == 1) { return objectId; } if(val == 2) { return currentLocation.x(); } if(val == 3) { return currentLocation.y(); } if(val == 4) { return currentLocation.z(); } if(val == 5) { return direction._2Hq(); } if(val == 6) { return launchType; } if(val == 7) { return ttl; } if(val == 8) { return ballOwner == null ? -1 : ballOwner.objectId; } if(val == 9) { return paraOffs; } //if(val == 10) { return speed; //} } @Override public Direction360 direction360(){ return (direction); } @Override public int[] boundingData(){ return (boundingData); } @Override public PlayerTile location3D(){ return (currentLocation); } @Override public void subturn(SynchronizedStage _arg1){ final SnowWarRoom local1 = ((SnowWarRoom)_arg1); if (!_active){ return; } setTtl(ttl-1); if (launchType == _4s){ int _2Sx = 10; _3rG(_2Sx, true); } else { if (launchType == _09I){ int _0zg = 25; _3rG(_0zg, false); } else { int _3kL = 50; _3rG(_3kL, false); } } final int local2 = Tile._4mC(currentLocation.x()); final int local3 = Tile._3FS(currentLocation.y()); final Tile local4 = local1.map.getTile(local2, local3); boolean collision = checkCollision(local4); if (!collision){ collision = local1.map.checkFloorCollision(this); } else { this.onRemove(); } } private boolean checkCollision(Tile _arg2){ Direction8 local3; boolean local2 = false; if (_arg2 != null){ local2 = this.testSnowBallCollision(_arg2); if (!local2){ local3 = direction.direction8Value(); local2 = this.testSnowBallCollision(_arg2.getNextTileAtRot(local3)); if (!local2){ local2 = this.testSnowBallCollision(_arg2.getNextTileAtRot(local3.rotateDirection45Degrees(false))); if (!local2){ local2 = this.testSnowBallCollision(_arg2.getNextTileAtRot(local3.rotateDirection45Degrees(true))); } } } } return local2; } private boolean testSnowBallCollision(Tile _arg2){ BaseObject item; if (_arg2 != null){ item = _arg2._4fe(); if (item != null){ if (item.testSnowBallCollision(this)){ item.onSnowBallHit(this); return (true); } } } return (false); } private void _3rG(int _arg1,boolean _arg2){ final int local2 = (currentLocation.x() + MathUtil._43Z(((direction._0uc() * speed) / 0xFF))); final int local3 = (currentLocation.y() + MathUtil._43Z(((direction._17x() * speed) / 0xFF))); final int local4 = (ttl - paraOffs); int local5 = ((((paraOffs * paraOffs) - (local4 * local4)) * _arg1) + _2t9); if (_arg2){ local5 = Math.min(local5, _2t9); } setCurLocation(local2, local3, local5); } @Override public String toString(){ return (((((((((((((" location=(" + currentLocation.x()) + ",") + currentLocation.y()) + ",") + currentLocation.z()) + ")") + " dir=") + direction) + " paraOffs=") + paraOffs) + " ttl=") + ttl)); } public HumanObject getAttacker(){ return (ballOwner); } @Override public void onRemove() { // this is in disponse (client-side) //setOwner(null); this.setOwner(null); this._active = false; this.GenerateCHECKSUM(this.currentSnowWar, -1); //this.currentSnowWar.subTurn(); } }
28.872659
203
0.527046
1186f37af9dc61c74bb91862974ff61f6129f954
13,551
/* * Copyright (C) 2014 Ali-Amir Aldan. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.github.rosjava.challenge.navigation; import java.awt.geom.*; import java.io.*; import java.util.*; import java.text.*; import gui_msgs.GUIEraseMsg; import gui_msgs.GUIPolyMsg; import gui_msgs.GUIRectMsg; import org.ros.node.ConnectedNode; import org.ros.node.AbstractNodeMain; import org.ros.node.topic.Publisher; import org.ros.namespace.GraphName; import com.github.rosjava.challenge.vision.*; import com.github.rosjava.challenge.gui.MapGUIPanel; /** * <p>The 2D {@link #worldRect}, {@link PolygonObstacle} {@link #obstacles}, * {@link #robotStart}, and {@link #robotGoal} that * make-up the environment in which the robot will navigate.</p> * * <p>You can either make an instance of this class and use it from within your * own program (typical usage), or you can run this code as an indepedent * process (see {@link #main}). The latter mode allows you to display the * contents of a map file, but does not give programmatic access to those * contents, and thus is useful mostly for displaying/debugging map * files.</p>. * * <p>The format of the map file is as follows (all items are signed doubles in * ASCII text format, all units are meters, and all separators are whitespace): * <pre> * robotStartX robotStartY * robotGoalX robotGoalY * worldX worldY worldWidth worldHeight * obstacle0X0 obstacle0Y0 obstacle0X1 obstacle0Y1 ... * ... * </pre> * The first three lines initialize the corresponding instance fields {@link #robotStart}, {@link #robotGoal}, and {@link * #worldRect}, respectively. Each obstacle line gives the coordinates of the * obstacle's vertices in CCW order. There may be zero obstacles.</p> * * @author Marty Vona * @author Aisha Walcott * * @author Kenny Donahue (minor edits 03/11/11) * @author Dylan Hadfield-Menell (port to ROS 01/12) **/ public class PolygonMap extends AbstractNodeMain{ /** * <p>Name to use when run as an application.</p> **/ public static final String APPNAME = "PolygonMap"; /** * <p>The start point for the robot origin, read in from the map file * (m).</p> **/ protected Point2D.Double robotStart = new Point2D.Double(); /** * <p>The goal point for the robot origin, read in from the map file (m).</p> **/ protected Point2D.Double robotGoal = new Point2D.Double(); /** * <p>The location and size of the world boundary, read in from the map file * (m).</p> **/ protected Rectangle2D.Double worldRect = new Rectangle2D.Double(); /** * <p>The obstacles (does not include the world boundary).</p> **/ protected LinkedList<PolygonObstacle> obstacles = new LinkedList<PolygonObstacle>(); private Publisher<GUIEraseMsg> erasePub; private Publisher<GUIRectMsg> rectPub; private Publisher<GUIPolyMsg> polyPub; private String mapFile = "/home/rss-staff/ros/rss/solutions/lab6/src/global-nav-maze-2011-basic.map"; /** * <p>Create a new map, parsing <code>mapFile</code>.</p> * * @param mapFile the map file to parse, or null if none **/ public PolygonMap(File mapFile) throws IOException, ParseException { if (mapFile != null) parse(mapFile); } /** * <p>Covers {@link #PolygonMap(File)}.</p> **/ public PolygonMap(String mapFile) throws IOException, ParseException { this((mapFile != null) ? new File(mapFile) : null); } /** * <p>Create a new un-initialized polygon map.</p> * * <p>You may populate it using the accessors below.</p> **/ public PolygonMap() { } /** * <p>Parse a <code>double</code>.</p> * * @param br the double is expected to be on the next line of this reader * @param name the name of the double * @param lineNumber the line number of the double * * @return the parsed double * * @exception IOException if there was an I/O error * @exception ParseException if there was a format error * @exception NumberFormatException if there was a format error **/ protected double parseDouble(BufferedReader br, String name, int lineNumber) throws IOException, ParseException, NumberFormatException { String line = br.readLine(); if (line == null) throw new ParseException(name + " (line " + lineNumber + ")", lineNumber); return Double.parseDouble(line); } /** * <p>Parse a <code>Point2D.Double</code>.</p> * * @param point the returned point * @param br the point is expected to be on the next line of this reader * @param name the name of the point * @param lineNumber the line number of the point * * @exception IOException if there was an I/O error * @exception ParseException if there was a format error * @exception NumberFormatException if there was a format error **/ protected void parsePoint(Point2D.Double point, BufferedReader br, String name, int lineNumber) throws IOException, ParseException, NumberFormatException { String line = br.readLine(); String[] tok = (line != null) ? line.split("\\s+") : null; if ((tok == null) || (tok.length < 2)){ throw new ParseException(name + " (line " + lineNumber + ")", lineNumber); } point.x = Double.parseDouble(tok[0]); point.y = Double.parseDouble(tok[1]); } /** * <p>Parse a <code>Rectangle2D.Double</code>.</p> * * @param rect the returned rectangle * @param br the rect is expected to be on the next line of this reader * @param name the name of the rect * @param lineNumber the line number of the rect * * @exception IOException if there was an I/O error * @exception ParseException if there was a format error * @exception NumberFormatException if there was a format error **/ protected void parseRect(Rectangle2D.Double rect, BufferedReader br, String name, int lineNumber) throws IOException, ParseException, NumberFormatException { String line = br.readLine(); String[] tok = (line != null) ? line.split("\\s+") : null; if ((tok == null) || (tok.length < 4)) throw new ParseException(name + " (line " + lineNumber + ")", lineNumber); rect.x = Double.parseDouble(tok[0]); rect.y = Double.parseDouble(tok[1]); rect.width = Double.parseDouble(tok[2]); rect.height = Double.parseDouble(tok[3]); } /** * <p>Parse a {@link PolygonObstacle}.</p> * * @param br the polygon is expected to be on the next line of this reader * @param name the name of the polygon * @param lineNumber the line number of the polygon * * @return a new polygon containing the vertices on the line, or null if * there was no line * * @exception IOException if there was an I/O error * @exception ParseException if there was a format error * @exception NumberFormatException if there was a format error **/ protected PolygonObstacle parseObs(BufferedReader br, String name, int lineNumber) throws IOException, ParseException, NumberFormatException { String line = br.readLine(); if (line == null) return null; String[] tok = line.trim().split("\\s+"); if (tok.length == 0) return null; // System.err.println( // "line " + lineNumber + " (" + tok.length + " tokens): "); // for (int i = 0; i < tok.length; i++) // System.err.println(" " + tok[i]); if (tok.length%2 != 1) throw new ParseException(name + " (line " + lineNumber + ")", lineNumber); int n = Integer.parseInt(tok[0]); PolygonObstacle poly = new PolygonObstacle(); for (int i = 0; i < n; i++) poly.addVertex(Double.parseDouble(tok[2*i+1]), Double.parseDouble(tok[2*i+2])); poly.close(); return poly; } /** * <p>Hook called from {@link #parse} after the first four lines are parsed * to allow subclasses to parse extra lines before the obstacles.</p> * * <p>Default impl just returns false.</p> * * @param br the next line of this reader is the next to be parsed * @param lineNumber the line number of the next line of br * * @return true if the line was parsed and more are expected, false if no * more extra lines are expected * * @exception IOException if there was an I/O error * @exception ParseException if there was a format error * @exception NumberFormatException if there was a format error **/ protected boolean parseExtra(BufferedReader br, int lineNumber) throws IOException, ParseException, NumberFormatException { return false; } /** * <p>Parse <code>mapFile</code>.</p> * * <p>Format is specified in the class header doc for {@link PolygonMap}.</p> * * @param mapFile the map file, not null **/ protected void parse(File mapFile) throws IOException, ParseException { int lineNumber = 1; try { BufferedReader br = new BufferedReader(new FileReader(mapFile)); parsePoint(robotStart, br, "robot start", lineNumber++); parsePoint(robotGoal, br, "robot goal", lineNumber++); parseRect(worldRect, br, "world rect", lineNumber++); String line = br.readLine(); int n = Integer.parseInt(line); for (int obstacleNumber = 0; obstacleNumber < n; obstacleNumber++) { PolygonObstacle poly = parseObs(br, "obstacle " + obstacleNumber, lineNumber++); if (poly != null) { poly.color = MapGUIPanel.makeRandomColor(); obstacles.add(poly); } else break; } } catch (NumberFormatException e) { throw new ParseException("malformed number on line " + lineNumber, lineNumber); } } /** * <p>Get {@link #robotStart}.</p> * * @return a reference to <code>robotStart</code> (you may modify it) **/ public Point2D.Double getRobotStart() { return robotStart; } /** * <p>Get {@link #robotGoal}.</p> * * @return a reference to <code>robotGoal</code> (you may modify it) **/ public Point2D.Double getRobotGoal() { return robotGoal; } /** * <p>Get {@link #worldRect}.</p> * * @return a reference to <code>worldRect</code> (you may modify it) **/ public Rectangle2D.Double getWorldRect() { return worldRect; } /** * <p>Get {@link #obstacles}.</p> * * @return a reference to <code>obstacles</code> (you may modify it) **/ public List<PolygonObstacle> getObstacles() { return obstacles; } /** * <p>Return a human-readable string representation of this map.</p> * * @return a human-readable string representation of this map **/ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("\nrobot start: "); sb.append(Double.toString(robotStart.x)); sb.append(", "); sb.append(Double.toString(robotStart.y)); sb.append("\nrobot goal: "); sb.append(Double.toString(robotGoal.x)); sb.append(", "); sb.append(Double.toString(robotGoal.y)); sb.append("\nworld rect: x="); sb.append(Double.toString(worldRect.x)); sb.append(" y="); sb.append(Double.toString(worldRect.y)); sb.append(" width="); sb.append(Double.toString(worldRect.width)); sb.append(" height="); sb.append(Double.toString(worldRect.height)); sb.append("\n" + obstacles.size() + " obstacles:"); for (PolygonObstacle obstacle : obstacles) { sb.append("\n "); obstacle.toStringBuffer(sb); } return sb.toString(); } /** * <p>Parses the specified map file, prints it out, and displays it in the * GUI, if any.</p> * * <p>Usage: {@link #getAppName} &lt;mapfile&gt; [centralhost]</p> **/ protected void instanceMain(String mapFile) { System.out.println(" map file: " + mapFile); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { parse(new File(mapFile)); System.out.println(toString()); erasePub.publish(erasePub.newMessage()); GUIRectMsg rectMsg = rectPub.newMessage(); GlobalNavigation.fillRectMsg(rectMsg, getWorldRect(), null, false); rectPub.publish(rectMsg); GUIPolyMsg polyMsg = polyPub.newMessage(); for (PolygonObstacle obstacle : getObstacles()){ polyMsg = polyPub.newMessage(); GlobalNavigation.fillPolyMsg(polyMsg, obstacle, MapGUIPanel.makeRandomColor(), true, true); polyPub.publish(polyMsg); } driverDisplayHook(); } catch (IOException e) { System.err.println("I/O error: " + e); } catch (ParseException e) { System.err.println("Parse error: " + e); } } /** * <p>Get the application name.</p> * * @return the application name **/ protected String getAppName() { return APPNAME; } /** * <p>Hook called after painting map objects in {@link #instanceMain} to * allow subclasses to display extra stuff.</p> * * <p>Default impl does nothing.</p> **/ protected void driverDisplayHook() { } /** * Entry hook for ROS when called as stand-alone node */ @Override public void onStart(ConnectedNode node) { erasePub = node.newPublisher("gui/Erase", GUIEraseMsg._TYPE); rectPub = node.newPublisher("gui/Rect", GUIRectMsg._TYPE); polyPub = node.newPublisher("gui/Poly", GUIPolyMsg._TYPE); this.instanceMain(mapFile); } @Override public GraphName getDefaultNodeName() { return GraphName.of("rss/polygonmap"); } }
28.831915
121
0.678695
b8dd85f964a6a2f45c2c0f0d885076197dc97dc6
2,370
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DataBase { private Connection con; private Statement statement; private String db = ""; public DataBase(String db) { this.db = db; } public boolean sjekker() { boolean eksisterer = true; try { this.con = DriverManager.getConnection(db); this.statement = con.createStatement(); String sqlTabellen = "CREATE TABLE IF NOT EXISTS todo(" + "nr INTEGER PRIMARY KEY, " + "todo VARCHAR(200) NOT NULL, " + "aktiv BOOLEAN NOT NULL); "; int antallEndret = statement.executeUpdate(sqlTabellen); if (antallEndret > 0) { // databasen eksisterer ikke eksisterer = false; } else { // databasen eksiterer allerede } con.close(); } catch ( SQLException e ) { System.err.print(e); } return eksisterer; } public String getQuery(String s) throws SQLException{ String tempResult = ""; try { this.con = DriverManager.getConnection(db); this.statement = con.createStatement(); ResultSet rs = statement.executeQuery(s); while (rs.next()) { // read the result set System.out.println("name = " + rs.getString("name")); System.out.println("id = " + rs.getInt("id")); } con.close(); } catch ( SQLException e ) { System.err.print("SQL Feil: " + e); } catch ( Exception e ) { System.err.print(e); } return tempResult; } public void lagNy(String s) { try { this.con = DriverManager.getConnection(db); this.statement = con.createStatement(); statement.executeUpdate(s); con.close(); } catch (SQLException e) { System.err.print(e); } } /* public int getNr() { System.out.println("getting a number from DB"); int temp = 0; try { this.con = DriverManager.getConnection(db); this.statement = con.createStatement(); ResultSet rs = statement.executeQuery("SELECT count(*) AS nr FROM todo"); System.out.print(rs); temp = rs.getInt("nr"); System.out.println(temp); con.close(); } catch (SQLException e) { System.err.print(e); } catch (Exception e) { System.out.print("Feil ved DB getNr metoden: " + e); } return temp; } */ }
24.183673
77
0.6173
ef28f66986973c94ca416ca41757aa8f1294314f
556
package com.fame.zbw; import com.zbw.fame.service.OptionService; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; /** * @author zhangbowen * @since 2019/6/24 10:44 */ @Slf4j public class OptionServiceTests extends BaseTests { @Autowired private OptionService optionService; @Test public void test1() { log.info("{}", optionService.getAllOptionMap()); } @Test public void test2() { optionService.save("new_option", "new123"); } }
19.857143
62
0.690647
9bae369b84ad46f41c9d38745dd318d320efbba0
8,437
package api.version_2_2_0.trackstestdata; import api.version_2_2_0.tracks.TracksApi_v2_2; import api.version_2_2_0.tracks.entity.TracksContext_v2_2; import api.version_2_2_0.wunderlist.appasapi.Project; import api.version_2_2_0.wunderlist.appasapi.Todo; import api.version_2_2_0.wunderlist.appasapi.Wunderlist; import api.version_2_2_0.wunderlist.appasapi.WunderlistCache; import io.restassured.RestAssured; import io.restassured.response.Response; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SetupTracksTestDataTest { // You probably want to change this to your user and your setup // Mac alan //public static final String MyDataFolder = "/Users/alan/Downloads/"; // Windows alan public static final String MyDataFolder = "d:/temp/"; public static final String WUNDERLIST_PROJECTS = MyDataFolder + "wunderlistProjects.properties"; public static final String WUNDERLIST_TODOS = MyDataFolder + "wunderlistTodos.properties"; public static final int MAX_NUMBER_OF_TODOS=20; public int numberOfProjectsLimit = 10; // -ve to use the number of projects from wunderlist // Number of users not enabled public int numberOfUsersToUse = 30; // for 0 users, the default username password will be used for all // for more than one user, fir the users will be created // then for each project a random user will be used for each project public static final String url = "192.168.58.128"; // API VM public static final String username = "user"; public static final String password = "bitnami"; // Bitnami Default // cloud VM for data //public static final String url = "tracks-with-data.bitnamiapp.com/tracks"; //public static final String password = "bitnami01tracks"; //public static final String username = "mrlogout"; //public static final String password = "logmeout"; //public static final String username = "mrlong"; //public static final String password = "longpasswordforme"; public static final String newUserPattern = "user%d"; public static final String newPasswordPattern = "bitnami%d"; // Run this test to update the data in the properties files from Wunderlist @Ignore // Do not run these tests automatically, they are not 'tests', they help me work @Test public void updateWunderlistCache() throws IOException { File projectsListCache = new File(WUNDERLIST_PROJECTS); WunderlistCache cache = new WunderlistCache(new Wunderlist()); cache.setProjectsCacheFile(projectsListCache); cache.addUncachedProjects(); File todoListCache = new File(WUNDERLIST_TODOS); cache.setTodosCacheFile(todoListCache); List<Project> projects = cache.getProjects(); for(Project aProject : projects){ cache.addUncachedTodos(aProject.id()); } } private String randomUser(Set<String> userNames){ String[] names = userNames.toArray(new String[userNames.size()]); return names[new Random().nextInt(names.length)]; } @Ignore // Do not run these tests automatically, they are not 'tests', they help me work @Test public void createTracksDataFromWunderlistCache(){ // If you are not using a proxy then comment this out. // If you are then make sure details are correct RestAssured.proxy("localhost", 8080); // Setup Wunderlist cache for test data WunderlistCache cache = new WunderlistCache(new Wunderlist()); cache.setProjectsCacheFile( new File(WUNDERLIST_PROJECTS)); cache.setTodosCacheFile(new File(WUNDERLIST_TODOS)); TracksApi_v2_2 tracks = new TracksApi_v2_2(url, username, password); // create the contexts String[] contexts = {"work", "home", "shopping", "schoolrun"}; // create the users name password map Map<String,String> usersNamePassword = new HashMap<String, String>(); usersNamePassword.put(username, password); for(int userNumber=1; userNumber<numberOfUsersToUse; userNumber++){ String newUsername = String.format(newUserPattern, userNumber); String newPassword = String.format(newPasswordPattern, userNumber); usersNamePassword.put(newUsername, newPassword); } // create the users - ignores duplicates for(String aUserName : usersNamePassword.keySet()){ // create users with the default user tracks.basicAuth(username,password); // create a user String aPassword = usersNamePassword.get(aUserName); tracks.createUser(aUserName, aPassword); // create the contexts for the user for(String aContext : contexts){ // each user needs ot create their own context tracks.basicAuth(aUserName,aPassword); Response response = tracks.createContext(aContext); if(response.getStatusCode()==201 || response.getStatusCode()==409){ // 201 - Created // 409 - Already exists }else{ System.out.println("Warning: Creating Context " + aContext + " Status Code " + response.getStatusCode()); } } } // read projects from cache List<Project> projects = cache.getProjects(); // read todos from cache List<Todo> todos = cache.getTodos(); // LOOP: create a project for( Project aProject : projects) { // have not enabled multiple users - run for each user you want to create data for String randomUserName = randomUser(usersNamePassword.keySet()); tracks.basicAuth(randomUserName, usersNamePassword.get(randomUserName)); // get all the context ids for the user List<TracksContext_v2_2> contextList = tracks.getContexts(); String newProjectName = aProject.name() + " " + randomWord(); System.out.println(newProjectName); Response response = tracks.createProject(newProjectName); // Only add todos if we created one if(response.statusCode()==201) { // get the project id you just added String location = response.header("Location"); //Location: [\S]+?/projects/(\d+) String findLocation = "[\\S]+?/projects/(\\d+)"; Pattern p = Pattern.compile(findLocation); Matcher m = p.matcher(location); String projectId = ""; if (m.find()) { projectId = m.group(1); } // LOOP: generate a random number of todos int numberOfTodos = new Random().nextInt(MAX_NUMBER_OF_TODOS); while (numberOfTodos > 0) { // randomly choose a context TracksContext_v2_2 rndcontext = contextList.get(new Random().nextInt(contextList.size())); // randomly choose a todo name Todo rndtodo = todos.get(new Random().nextInt(todos.size())); // add the todo to the project and a context tracks.createTodo(rndtodo.name() + " " + randomWord(), projectId, rndcontext.id()); numberOfTodos--; } } // next project numberOfProjectsLimit--; if(numberOfProjectsLimit==0){ break; } } } // Quick hack random word private String randomWord() { return String.valueOf(System.currentTimeMillis()). replaceAll("1", "a"). replaceAll("2", "d"). replaceAll("3", "o"). replaceAll("4", "n"). replaceAll("5", "e"). replaceAll("6", "r"). replaceAll("7", "h"). replaceAll("8", "i"). replaceAll("9", "t"). replaceAll("0", "s"); } }
38.35
125
0.607562
47ae78ff7a0390eac41916929e2609e08edfd960
237
/** * Provides smoothing techniques for transforming raw classifier * scores into calibrated probabilities. Includes implementations, utilities * builders, and abstract classes */ package com.dsi.parallax.ml.classifier.smoother;
39.5
77
0.78903
981d499f5197e48ae7cce47a0ae003f6fbc3a75a
1,562
/* * JBoss, Home of Professional Open Source * Copyright 2013, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.shrinkwrap.resolver.api.maven.pom; import java.io.File; /** * Represents a file-backed resource used by Maven model. * * @author <a href="mailto:kpiwko@redhat.com">Karel Piwko</a> * */ public class Resource { private final File source; private final String targetPath; public Resource(File source, String targetPath) { this.source = source; this.targetPath = targetPath; } /** * Return a file that contains content of the resource * * @return */ public File getSource() { return source; } /** * Returns a normalized path where resource should be stored in archive * * @return */ public String getTargetPath() { return targetPath; } }
27.403509
75
0.689501
dcb9a007bbfc8c3ebb500d89840ccd40d00dc13b
518
package com.luxoft.cddb.services; import java.util.Optional; import org.springframework.security.core.userdetails.UserDetailsService; import com.luxoft.cddb.beans.user.UserBean; public interface IUserService extends IDefaultService<UserBean>, UserDetailsService { public Optional<UserBean> findByName(String username); public void addRole(UserBean user, String userRole); public String encodePassword(String clearPassword); public void updateEmail(String username, String email); }
25.9
86
0.783784
35bd3506cfd86d1932559617016912a5df9b0424
2,874
/* * Copyright (C) 2013-2015 RoboVM AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bugvm.apple.metal; /*<imports>*/ import java.io.*; import java.nio.*; import java.util.*; import com.bugvm.objc.*; import com.bugvm.objc.annotation.*; import com.bugvm.objc.block.*; import com.bugvm.rt.*; import com.bugvm.rt.annotation.*; import com.bugvm.rt.bro.*; import com.bugvm.rt.bro.annotation.*; import com.bugvm.rt.bro.ptr.*; import com.bugvm.apple.foundation.*; import com.bugvm.apple.dispatch.*; /*</imports>*/ /*<javadoc>*/ /** * @since Available in iOS 8.0 and later. */ /*</javadoc>*/ /*<annotations>*/@Marshaler(ValuedEnum.AsMachineSizedUIntMarshaler.class)/*</annotations>*/ public enum /*<name>*/MTLDataType/*</name>*/ implements ValuedEnum { /*<values>*/ None(0L), Struct(1L), Array(2L), Float(3L), Float2(4L), Float3(5L), Float4(6L), Float2x2(7L), Float2x3(8L), Float2x4(9L), Float3x2(10L), Float3x3(11L), Float3x4(12L), Float4x2(13L), Float4x3(14L), Float4x4(15L), Half(16L), Half2(17L), Half3(18L), Half4(19L), Half2x2(20L), Half2x3(21L), Half2x4(22L), Half3x2(23L), Half3x3(24L), Half3x4(25L), Half4x2(26L), Half4x3(27L), Half4x4(28L), Int(29L), Int2(30L), Int3(31L), Int4(32L), UInt(33L), UInt2(34L), UInt3(35L), UInt4(36L), Short(37L), Short2(38L), Short3(39L), Short4(40L), UShort(41L), UShort2(42L), UShort3(43L), UShort4(44L), Char(45L), Char2(46L), Char3(47L), Char4(48L), UChar(49L), UChar2(50L), UChar3(51L), UChar4(52L), Bool(53L), Bool2(54L), Bool3(55L), Bool4(56L); /*</values>*/ /*<bind>*/ /*</bind>*/ /*<constants>*//*</constants>*/ /*<methods>*//*</methods>*/ private final long n; private /*<name>*/MTLDataType/*</name>*/(long n) { this.n = n; } public long value() { return n; } public static /*<name>*/MTLDataType/*</name>*/ valueOf(long n) { for (/*<name>*/MTLDataType/*</name>*/ v : values()) { if (v.n == n) { return v; } } throw new IllegalArgumentException("No constant with value " + n + " found in " + /*<name>*/MTLDataType/*</name>*/.class.getName()); } }
23.95
91
0.599165
5176f0f243cdc7367391c9f4662dfaafd12e1d00
889
package mx.code.challenge.bowling.domain; public class BowlDomain { private Integer frame; private String name; private Integer pinfalls; private Integer score; private Integer hit; private Boolean fault; public Integer getFrame() { return frame; } public void setFrame(Integer frame) { this.frame = frame; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getPinfalls() { return pinfalls; } public void setPinfalls(Integer pinfalls) { this.pinfalls = pinfalls; } public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } public Integer getHit() { return hit; } public void setHit(Integer hit) { this.hit = hit; } public Boolean isFault() { return fault; } public void setFault(Boolean fault) { this.fault = fault; } }
17.431373
44
0.699663
7d27e637cc42a43949f436c104142d99e635a47a
1,406
/** * Copyright (C) 2006-2019 Talend Inc. - www.talend.com * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.talend.sdk.component.runtime.beam.spi.record; import static org.apache.beam.sdk.util.SerializableUtils.ensureSerializableByCoder; import static org.junit.Assert.assertArrayEquals; import org.junit.jupiter.api.Test; import org.talend.sdk.component.api.record.Record; import org.talend.sdk.component.runtime.beam.coder.registry.SchemaRegistryCoder; class AvroRecordTest { @Test void bytes() { final byte[] array = { 0, 1, 2, 3, 4 }; final Record record = new AvroRecordBuilder().withBytes("bytes", array).build(); assertArrayEquals(array, record.getBytes("bytes")); final Record copy = ensureSerializableByCoder(SchemaRegistryCoder.of(), record, "test"); assertArrayEquals(array, copy.getBytes("bytes")); } }
38
96
0.72973
a3440ab4b3b2d966dde4273d3202ed0ebfeeb3ce
11,486
package com.zdd.myutil.bluetooth; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.util.Log; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.Timer; import java.util.TimerTask; /** * Created by yd on 2018/5/5. */ public class BluetoothUtil { private static BluetoothUtil bluetoothUtil; private static BluetoothAdapter mBluetoothAdapter; private static Context context; private static List<BT> bts = new ArrayList<>(); private static boolean isScanning = false; private static BT selectBT; private static BT connectBT; private static int pairCount; private static ScanLitener scanLitener; public static BluetoothUtil openBt(Context context){ BluetoothUtil.context = context; BluetoothUtil.bluetoothUtil = new BluetoothUtil(); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter!=null) { mBluetoothAdapter.enable(); } register(); return bluetoothUtil; } public static List<BT> getBts(){ return bts; } public static int getPairCount(){ return pairCount; } public static void scanBt(ScanLitener litener){ BluetoothUtil.scanLitener = litener; scanBt(); } private static void scanBt(){ if (mBluetoothAdapter!=null&&!isScanning) { isScanning = true; // 获取所有已经绑定的蓝牙设备 bts.clear(); Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices(); if (devices.size() > 0) { pairCount = 0; for (BluetoothDevice bluetoothDevice : devices) { // Log.i("device.getName()", bluetoothDevice.getName()); BT bt = new BT(bluetoothDevice.getName(), bluetoothDevice.getAddress()); bt.setPaired(true); bts.add(bt); if (scanLitener!=null){ scanLitener.discovered(bts,bt,connectBT!=null,pairCount); } pairCount++; } } mBluetoothAdapter.startDiscovery(); } } private static void register(){ IntentFilter mFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); // registerReceiver(mReceiver, mFilter); // 注册搜索完时的receiver mFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); mFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); mFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);//行动扫描模式改变了 mFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); // mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); context.registerReceiver(mReceiver, mFilter); } public static boolean removeBond(Class btClass, BluetoothDevice btDevice){ Method removeBondMethod = null; Boolean returnValue = false; try { removeBondMethod = btClass.getMethod("removeBond"); returnValue = (Boolean) removeBondMethod.invoke(btDevice); } catch (NoSuchMethodException e) { e.printStackTrace(); }catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return returnValue.booleanValue(); } private static void checkState(){ if(mBluetoothAdapter.isEnabled()){ int a2dp = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP); // 可操控蓝牙设备,如带播放暂停功能的蓝牙耳机 int headset = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET); // 蓝牙头戴式耳机,支持语音输入输出 int health = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH); // 蓝牙穿戴式设备 int GATT = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.GATT); Log.e("edong","a2dp="+a2dp+",headset="+headset+",health="+health); // 查看是否蓝牙是否连接到三种设备的一种,以此来判断是否处于连接状态还是打开并没有连接的状态 int flag = -1; if (a2dp == BluetoothProfile.STATE_CONNECTED) { flag = a2dp; } else if (headset == BluetoothProfile.STATE_CONNECTED) { flag = headset; } else if (health == BluetoothProfile.STATE_CONNECTED) { flag = health; } if (flag!=-1) mBluetoothAdapter.getProfileProxy(context, new BluetoothProfile.ServiceListener() { @Override public void onServiceDisconnected(int profile) { // TODO Auto-generated method stub } @Override public void onServiceConnected(int profile, BluetoothProfile proxy) { // TODO Auto-generated method stub List<BluetoothDevice> mDevices = proxy.getConnectedDevices(); if (mDevices != null && mDevices.size() > 0) { for (BluetoothDevice device : mDevices) { BT bt = getBTForAddress(device.getAddress()); if (bt!=null&&!bt.isConnected()){ bt.setConnected(true); connectBT = bt; if (scanLitener!=null){ scanLitener.discovered(bts,bt,connectBT!=null,pairCount); } } } } else { Log.i("edong", "mDevices is null"); } } }, flag); } else { // setBtState(BluetoothAdapter.STATE_OFF); } } public static void connect(String address){ BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); try { if (device.getBondState() == BluetoothDevice.BOND_NONE) { Method createBondMethod = BluetoothDevice.class.getMethod("createBond"); Log.d("edong", "开始配对"); Boolean result = (Boolean) createBondMethod.invoke(device); } else if (device.getBondState() == BluetoothDevice.BOND_BONDED) { // removeBond(device.getClass(),device); Log.d("edong", "开始连接"); BlueConnectTask connectTask = new BlueConnectTask(address); connectTask.setBlueConnectListener(new BlueConnectTask.BlueConnectListener() { @Override public void onBlueConnect(String address, BluetoothSocket socket) { } }); connectTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, device); } } catch (Exception e) { e.printStackTrace(); } } private static BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.i("edong",action); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { checkState(); } },3000); // 获得已经搜索到的蓝牙设备 if (action.equals(BluetoothDevice.ACTION_FOUND)) { BluetoothDevice device = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Log.i("edong", "device.getName()"+device.getName()+device.getAddress()); if (device.getName()!=null) { // Log.i("device.getName()", device.getName()); // bts.add(device.getName()); } // 搜索到的不是已经绑定的蓝牙设备 if (device.getBondState() != BluetoothDevice.BOND_BONDED) { // 显示在TextView上 if (device.getName()!=null) { // Log.i("device.getName()", device.getName()); BT bt = new BT(device.getName(),device.getAddress()); if (!bts.contains(bt)) { bts.add(bt); } if (scanLitener!=null){ scanLitener.discovered(bts,bt,connectBT!=null,pairCount); } } } } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); switch (device.getBondState()) { case BluetoothDevice.BOND_BONDING://正在配对 Log.d("edong", "正在配对......"+device.getName()); break; case BluetoothDevice.BOND_BONDED://配对结束 BT bt = getBTForAddress(device.getAddress()); if (bt!=null){ bt.setPaired(true); if (scanLitener!=null){ scanLitener.discovered(bts,bt,connectBT!=null,pairCount); } } Log.d("edong", "完成配对"+device.getName()); break; case BluetoothDevice.BOND_NONE://取消配对/未配对 bt = getBTForAddress(device.getAddress()); if (bt!=null){ bt.setPaired(false); if (bt.equals(connectBT)){ connectBT = null; } if (scanLitener!=null){ scanLitener.discovered(bts,bt,connectBT!=null,pairCount); } } Log.d("edong", "取消配对"+device.getName()); default: break; } }else if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { scanBt(); }else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) { Log.i("edong", "ACTION_DISCOVERY_FINISHED"); isScanning = false; if (scanLitener!=null){ scanLitener.scanEnd(bts); } } } }; public static void setScanLitener(ScanLitener litener){ BluetoothUtil.scanLitener = litener; } private static BT getBTForAddress(String address){ for (BT bt:bts){ if (bt.getAddress().equals(address)){ return bt; } } return null; } public interface ScanLitener{ void discovered(List bts, BT bt, boolean isConnected, int pairCount); void scanEnd(List bts); } }
40.875445
116
0.539439
00bc44ff2001cf7918919e4615ff4bde54714ce1
794
package ua.dirproy.profelumno.loginout.models; import com.avaje.ebean.Model; /** * Created by facundo on 3/11/15. */ public class FacebookLogger extends Model { private String fb_email; private String fb_name; private String fb_surname; public String getFb_email() { return fb_email; } public void setFb_email(String fb_email) { this.fb_email = fb_email; } public String getFb_name() { return fb_name; } public void setFb_name(String fb_name) { this.fb_name = fb_name; } public String getFb_surname() { return fb_surname; } public void setFb_surname(String fb_surname) { this.fb_surname = fb_surname; } }
19.85
54
0.59194
66bb0d1cd43053f5d5b8f4c94d8df864c6bbb70e
2,072
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.spanner.publisher; import com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult; import com.google.cloud.spanner.Statement; import com.google.cloud.spanner.watcher.RandomResultSetGenerator; import org.junit.Before; public abstract class AbstractMockServerTest extends com.google.cloud.spanner.watcher.AbstractMockServerTest { // SpannerToAvro statements. private static final Statement SPANNER_TO_AVRO_SCHEMA_FOO_STATEMENT = Statement.newBuilder(SpannerToAvroFactory.SCHEMA_QUERY) .bind("catalog") .to("") .bind("schema") .to("") .bind("table") .to("Foo") .build(); private static final Statement SPANNER_TO_AVRO_SCHEMA_BAR_STATEMENT = Statement.newBuilder(SpannerToAvroFactory.SCHEMA_QUERY) .bind("catalog") .to("") .bind("schema") .to("") .bind("table") .to("Bar") .build(); @Before public void setupAvroResults() { // SpannerToAvro results. mockSpanner.putStatementResult( StatementResult.query( SPANNER_TO_AVRO_SCHEMA_FOO_STATEMENT, RandomResultSetGenerator.generateRandomResultSetInformationSchemaResultSet())); mockSpanner.putStatementResult( StatementResult.query( SPANNER_TO_AVRO_SCHEMA_BAR_STATEMENT, RandomResultSetGenerator.generateRandomResultSetInformationSchemaResultSet())); } }
35.118644
91
0.704151
43913bc94a2e393f4ff7f0da4036c6f4dc7b8c15
3,485
package havis.middleware.ale.core.depot.service.pc; import havis.middleware.ale.base.exception.DuplicateNameException; import havis.middleware.ale.base.exception.ImplementationException; import havis.middleware.ale.base.exception.NoSuchNameException; import havis.middleware.ale.base.exception.ValidationException; import havis.middleware.ale.config.PortCycleType; import havis.middleware.ale.core.config.Config; import havis.middleware.ale.core.depot.service.Cycle; import havis.middleware.ale.core.manager.PC; import havis.middleware.ale.service.mc.MCPortCycleSpec; import havis.middleware.ale.service.pc.PCSpec; import java.util.List; import java.util.Map.Entry; import java.util.UUID; /** * Implements the port cycle depot */ public class PortCycle extends Cycle<PortCycleType, MCPortCycleSpec, PCSpec> { private static PortCycle instance; static { reset(); } public static void reset() { instance = new PortCycle(); } /** * Retrieves the static instance * * @return The static instance */ public static PortCycle getInstance() { return instance; } /** * Provides the entries * * @return The entry list */ @Override protected List<PortCycleType> getList() { return Config.getInstance().getService().getPc().getPortCycles() .getPortCycle(); } /** * Returns the entry by specification * * @param spec * The specification * @return The entry */ @Override protected PortCycleType get(final MCPortCycleSpec spec) { return new PortCycleType(spec.getName(), spec.isEnable(), spec.getSpec()); } /** * Return the specification by entry * * @param entry * The entry * @return The specification */ @Override protected MCPortCycleSpec get(final PortCycleType entry) { return new MCPortCycleSpec(entry.getName(), entry.isEnable(), entry.getSpec()); } /** * Creates a new instance and adds a subscriber to each entry */ protected PortCycle() { super(); for (Entry<UUID, PortCycleType> pair : this.dict.entrySet()) { subscribers.put(pair.getKey(), new Subscriber(pair.getValue() .getName(), pair.getValue().getSubscribers() .getSubscriber())); } } /** * Defines the entry * * @param entry * The entry * @throws ImplementationException * @throws DuplicateNameException * @throws ValidationException */ @Override protected void define(PortCycleType entry) throws ValidationException, DuplicateNameException, ImplementationException { PC.getInstance().define(entry.getName(), entry.getSpec(), false); } /** * Un-defines the entry * * @param entry * The entry * @throws NoSuchNameException */ @Override protected void undefine(PortCycleType entry) throws NoSuchNameException { PC.getInstance().undefine(entry.getName(), false); } /** * Adds a new entry with empty subscriber list and returns the new created * id. Serializes the configuration * * @param entry * The entry * @return The unique id */ @Override protected UUID add(PortCycleType entry) { UUID guid = super.add(entry); subscribers.put(guid, new Subscriber(entry.getName(), entry .getSubscribers().getSubscriber())); return guid; } /** * Adds a new entry * * @param name * The name * @param spec * The specification */ public void add(final String name, final PCSpec spec) { add(new PortCycleType(name, true, spec)); } }
24.201389
78
0.694692
cc7d99d0de88147f1c2cdd162799a37f5ded69da
2,267
package com.sflpro.notifier; import com.sflpro.notifier.services.notification.NotificationProcessingService; import com.sflpro.notifier.services.notification.push.PushNotificationSubscriptionRequestProcessingService; import com.sflpro.notifier.services.system.event.ApplicationEventDistributionService; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; /** * Created by Hayk Mkrtchyan. * Date: 7/9/19 * Time: 10:27 AM */ @ConditionalOnProperty(value = "notifier.queue.engine", havingValue = "none", matchIfMissing = true) @Configuration public class DirectNotificationProcessorConfiguration { @Bean Executor directSenderExecutor(@Value("${directSenderExecutor.corePoolSize:4}") final int corePoolSize, @Value("${directSenderExecutor.maxPoolSize:128}") final int maxPoolSize, @Value("${directSenderExecutor.queueCapacity:4056}") final int queueCapacity) { final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); return executor; } @Bean DirectNotificationProcessor directSender(final NotificationProcessingService notificationProcessingService, final PushNotificationSubscriptionRequestProcessingService pushNotificationSubscriptionRequestProcessingService, final ApplicationEventDistributionService applicationEventDistributionService, @Qualifier("directSenderExecutor") final Executor executor) { return new DirectNotificationProcessor(notificationProcessingService, pushNotificationSubscriptionRequestProcessingService, applicationEventDistributionService, executor); } }
52.72093
179
0.75783
93e451a5773c6241e7fa2e7bfdd4d3fe767d106e
16,821
/* * This file is part of ELKI: * Environment for Developing KDD-Applications Supported by Index-Structures * * Copyright (C) 2019 * ELKI Development Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.lmu.ifi.dbs.elki.utilities.io; import de.lmu.ifi.dbs.elki.utilities.datastructures.BitsUtil; /** * Helper functionality for parsing. * * @author Erich Schubert * @since 0.7.5 */ public final class ParseUtil { /** * Private constructor. Static methods only. */ private ParseUtil() { // Do not use. } /** * Preallocated exceptions. */ public static final NumberFormatException EMPTY_STRING = new NumberFormatException("Parser called on an empty string.") { private static final long serialVersionUID = 1L; @Override public synchronized Throwable fillInStackTrace() { return this; } }; /** * Preallocated exceptions. */ public static final NumberFormatException EXPONENT_OVERFLOW = new NumberFormatException("Precision overflow for double exponent.") { private static final long serialVersionUID = 1L; @Override public synchronized Throwable fillInStackTrace() { return this; } }; /** * Preallocated exceptions. */ public static final NumberFormatException INVALID_EXPONENT = new NumberFormatException("Invalid exponent") { private static final long serialVersionUID = 1L; @Override public synchronized Throwable fillInStackTrace() { return this; } }; /** * Preallocated exceptions. */ public static final NumberFormatException TRAILING_CHARACTERS = new NumberFormatException("String sequence was not completely consumed.") { private static final long serialVersionUID = 1L; @Override public synchronized Throwable fillInStackTrace() { return this; } }; /** * Preallocated exceptions. */ public static final NumberFormatException PRECISION_OVERFLOW = new NumberFormatException("Precision overflow for long values.") { private static final long serialVersionUID = 1L; @Override public synchronized Throwable fillInStackTrace() { return this; } }; /** * Preallocated exceptions. */ public static final NumberFormatException NOT_A_NUMBER = new NumberFormatException("Number must start with a digit or dot.") { private static final long serialVersionUID = 1L; @Override public synchronized Throwable fillInStackTrace() { return this; } }; /** * Infinity pattern, with any capitalization */ private static final char[] INFINITY_PATTERN = { // 'I', 'n', 'f', 'i', 'n', 'i', 't', 'y', // 'i', 'N', 'F', 'I', 'N', 'I', 'T', 'Y' }; /** Length of pattern */ private static final int INFINITY_LENGTH = INFINITY_PATTERN.length >> 1; /** * Parse a double from a character sequence. * * In contrast to Javas {@link Double#parseDouble}, this will <em>not</em> * create an object and thus is expected to put less load on the garbage * collector. It will accept some more spellings of NaN and infinity, thus * removing the need for checking for these independently. * * @param str String * @param start Begin * @param end End * @return Double value */ public static double parseDouble(final byte[] str, final int start, final int end) { if(start >= end) { throw EMPTY_STRING; } // Current position and character. int pos = start; byte cur = str[pos]; // Match for NaN spellings if(matchNaN(str, cur, pos, end)) { return Double.NaN; } // Match sign boolean isNegative = (cur == '-'); // Carefully consume the - character, update c and i: if((isNegative || (cur == '+')) && (++pos < end)) { cur = str[pos]; } if(matchInf(str, cur, pos, end)) { return isNegative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } // Begin parsing real numbers! if(((cur < '0') || (cur > '9')) && (cur != '.')) { throw NOT_A_NUMBER; } // Parse digits into a long, remember offset of decimal point. long decimal = 0; int decimalPoint = -1; while(true) { final int digit = cur - '0'; if((digit >= 0) && (digit <= 9)) { final long tmp = (decimal << 3) + (decimal << 1) + digit; if(tmp >= decimal) { decimal = tmp; // Otherwise, silently ignore the extra digits. } else if(++decimalPoint == 0) { // Because we ignored the digit throw PRECISION_OVERFLOW; } } else if((cur == '.') && (decimalPoint < 0)) { decimalPoint = pos; } else { // No more digits, or a second dot. break; } if(++pos >= end) { break; } cur = str[pos]; } // We need the offset from the back for adjusting the exponent: // Note that we need the current value of i! decimalPoint = (decimalPoint >= 0) ? pos - decimalPoint - 1 : 0; // Reads exponent. int exp = 0; if((pos + 1 < end) && ((cur == 'E') || (cur == 'e'))) { cur = str[++pos]; final boolean isNegativeExp = (cur == '-'); if((isNegativeExp || (cur == '+')) && (++pos < end)) { cur = str[pos]; } if((cur < '0') || (cur > '9')) { // At least one digit required. throw INVALID_EXPONENT; } while(true) { final int digit = cur - '0'; if(digit < 0 || digit > 9) { break; } exp = (exp << 3) + (exp << 1) + digit; if(exp > Double.MAX_EXPONENT) { throw EXPONENT_OVERFLOW; } if(++pos >= end) { break; } cur = str[pos]; } exp = isNegativeExp ? -exp : exp; } // Adjust exponent by the offset of the dot in our long. exp = decimalPoint > 0 ? (exp - decimalPoint) : exp; if(pos != end) { throw TRAILING_CHARACTERS; } return BitsUtil.lpow10(isNegative ? -decimal : decimal, exp); } /** * Parse a double from a character sequence. * * In contrast to Javas {@link Double#parseDouble}, this will <em>not</em> * create an object and thus is expected to put less load on the garbage * collector. It will accept some more spellings of NaN and infinity, thus * removing the need for checking for these independently. * * @param str String * @return Double value */ public static double parseDouble(final CharSequence str) { return parseDouble(str, 0, str.length()); } /** * Parse a double from a character sequence. * * In contrast to Javas {@link Double#parseDouble}, this will <em>not</em> * create an object and thus is expected to put less load on the garbage * collector. It will accept some more spellings of NaN and infinity, thus * removing the need for checking for these independently. * * @param str String * @param start Begin * @param end End * @return Double value */ public static double parseDouble(final CharSequence str, final int start, final int end) { if(start >= end) { throw EMPTY_STRING; } // Current position and character. int pos = start; char cur = str.charAt(pos); // Match for NaN spellings if(matchNaN(str, cur, pos, end)) { return Double.NaN; } // Match sign boolean isNegative = (cur == '-'); // Carefully consume the - character, update c and i: if((isNegative || (cur == '+')) && (++pos < end)) { cur = str.charAt(pos); } if(matchInf(str, cur, pos, end)) { return isNegative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } // Begin parsing real numbers! if(((cur < '0') || (cur > '9')) && (cur != '.')) { throw NOT_A_NUMBER; } // Parse digits into a long, remember offset of decimal point. long decimal = 0; int decimalPoint = -1; while(true) { final int digit = cur - '0'; if((digit >= 0) && (digit <= 9)) { final long tmp = (decimal << 3) + (decimal << 1) + digit; if(tmp >= decimal) { decimal = tmp; // Otherwise, silently ignore the extra digits. } else if(++decimalPoint == 0) { // Because we ignored the digit throw PRECISION_OVERFLOW; } } else if((cur == '.') && (decimalPoint < 0)) { decimalPoint = pos; } else { // No more digits, or a second dot. break; } if(++pos >= end) { break; } cur = str.charAt(pos); } // We need the offset from the back for adjusting the exponent: // Note that we need the current value of i! decimalPoint = (decimalPoint >= 0) ? pos - decimalPoint - 1 : 0; // Reads exponent. int exp = 0; if((pos + 1 < end) && ((cur == 'E') || (cur == 'e'))) { cur = str.charAt(++pos); final boolean isNegativeExp = (cur == '-'); if((isNegativeExp || (cur == '+')) && (++pos < end)) { cur = str.charAt(pos); } if((cur < '0') || (cur > '9')) { // At least one digit required. throw INVALID_EXPONENT; } while(true) { final int digit = cur - '0'; if(digit < 0 || digit > 9) { break; } exp = (exp << 3) + (exp << 1) + digit; if(exp > Double.MAX_EXPONENT) { throw EXPONENT_OVERFLOW; } if(++pos >= end) { break; } cur = str.charAt(pos); } exp = isNegativeExp ? -exp : exp; } // Adjust exponent by the offset of the dot in our long. exp = decimalPoint > 0 ? (exp - decimalPoint) : exp; if(pos != end) { throw TRAILING_CHARACTERS; } return BitsUtil.lpow10(isNegative ? -decimal : decimal, exp); } /** * Parse a long integer from a character sequence. * * @param str String * @return Long value */ public static long parseLongBase10(final CharSequence str) { return parseLongBase10(str, 0, str.length()); } /** * Parse a long integer from a character sequence. * * @param str String * @param start Begin * @param end End * @return Long value */ public static long parseLongBase10(final CharSequence str, final int start, final int end) { // Current position and character. int pos = start; char cur = str.charAt(pos); // Match sign boolean isNegative = (cur == '-'); // Carefully consume the - character, update c and i: if((isNegative || (cur == '+')) && (++pos < end)) { cur = str.charAt(pos); } // Begin parsing real numbers! if((cur < '0') || (cur > '9')) { throw NOT_A_NUMBER; } // Parse digits into a long, remember offset of decimal point. long decimal = 0; while(true) { final int digit = cur - '0'; if((digit >= 0) && (digit <= 9)) { final long tmp = (decimal << 3) + (decimal << 1) + digit; if(tmp < decimal) { throw PRECISION_OVERFLOW; } decimal = tmp; } else { // No more digits, or a second dot. break; } if(++pos < end) { cur = str.charAt(pos); } else { break; } } if(pos != end) { throw TRAILING_CHARACTERS; } return isNegative ? -decimal : decimal; } /** * Parse an integer from a character sequence. * * @param str String * @return Int value */ public static int parseIntBase10(final CharSequence str) { return parseIntBase10(str, 0, str.length()); } /** * Parse an integer from a character sequence. * * @param str String * @param start Begin * @param end End * @return int value */ public static int parseIntBase10(final CharSequence str, final int start, final int end) { // Current position and character. int pos = start; char cur = str.charAt(pos); // Match sign boolean isNegative = (cur == '-'); // Carefully consume the - character, update c and i: if((isNegative || (cur == '+')) && (++pos < end)) { cur = str.charAt(pos); } // Begin parsing real numbers! if((cur < '0') || (cur > '9')) { throw NOT_A_NUMBER; } // Parse digits into a long, remember offset of decimal point. int decimal = 0; while(true) { final int digit = cur - '0'; if((digit >= 0) && (digit <= 9)) { final int tmp = (decimal << 3) + (decimal << 1) + digit; if(tmp < decimal) { throw PRECISION_OVERFLOW; } decimal = tmp; } else { // No more digits, or a second dot. break; } if(++pos < end) { cur = str.charAt(pos); } else { break; } } if(pos != end) { throw TRAILING_CHARACTERS; } return isNegative ? -decimal : decimal; } /** * Match "inf", "infinity" in a number of different capitalizations. * * @param str String to match * @param firstchar First character * @param start Interval begin * @param end Interval end * @return {@code true} when infinity was recognized. */ private static boolean matchInf(byte[] str, byte firstchar, int start, int end) { final int len = end - start; // The wonders of unicode. The infinity symbol \u221E is three bytes: if(len == 3 && firstchar == -0x1E && str[start + 1] == -0x78 && str[start + 2] == -0x62) { return true; } if((len != 3 && len != INFINITY_LENGTH) // || (firstchar != 'I' && firstchar != 'i')) { return false; } for(int i = 1, j = INFINITY_LENGTH + 1; i < INFINITY_LENGTH; i++, j++) { final byte c = str[start + i]; if(c != INFINITY_PATTERN[i] && c != INFINITY_PATTERN[j]) { return false; } if(i == 2 && len == 3) { return true; } } return true; } /** * Match "inf", "infinity" in a number of different capitalizations. * * @param str String to match * @param firstchar First character * @param start Interval begin * @param end Interval end * @return {@code true} when infinity was recognized. */ private static boolean matchInf(CharSequence str, char firstchar, int start, int end) { final int len = end - start; // The wonders of unicode: infinity symbol if(len == 1 && firstchar == '\u221E') { return true; } if((len != 3 && len != INFINITY_LENGTH) // || (firstchar != 'I' && firstchar != 'i')) { return false; } for(int i = 1, j = INFINITY_LENGTH + 1; i < INFINITY_LENGTH; i++, j++) { final char c = str.charAt(start + i); if(c != INFINITY_PATTERN[i] && c != INFINITY_PATTERN[j]) { return false; } if(i == 2 && len == 3) { return true; } } return true; } /** * Match "NaN" in a number of different capitalizations. * * @param str String to match * @param firstchar First character * @param start Interval begin * @param end Interval end * @return {@code true} when NaN was recognized. */ private static boolean matchNaN(byte[] str, byte firstchar, int start, int end) { final int len = end - start; if(len < 2 || len > 3 || (firstchar != 'N' && firstchar != 'n')) { return false; } final byte c1 = str[start + 1]; if(c1 != 'a' && c1 != 'A') { return false; } // Accept just "NA", too: if(len == 2) { return true; } final byte c2 = str[start + 2]; return c2 == 'N' || c2 == 'n'; } /** * Match "NaN" in a number of different capitalizations. * * @param str String to match * @param firstchar First character * @param start Interval begin * @param end Interval end * @return {@code true} when NaN was recognized. */ private static boolean matchNaN(CharSequence str, char firstchar, int start, int end) { final int len = end - start; if(len < 2 || len > 3 || (firstchar != 'N' && firstchar != 'n')) { return false; } final char c1 = str.charAt(start + 1); if(c1 != 'a' && c1 != 'A') { return false; } // Accept just "NA", too: if(len == 2) { return true; } final char c2 = str.charAt(start + 2); return c2 == 'N' || c2 == 'n'; } }
28.704778
141
0.579216
2c1d2d818e9c68acd29f43ccf7152e1e2073e7fa
636
/* * Decompiled with CFR 0.150. */ package us.myles.viaversion.libs.fastutil.objects; import java.io.Serializable; import us.myles.viaversion.libs.fastutil.objects.Object2IntFunction; public abstract class AbstractObject2IntFunction<K> implements Object2IntFunction<K>, Serializable { private static final long serialVersionUID = -4940583368468432370L; protected int defRetValue; protected AbstractObject2IntFunction() { } @Override public void defaultReturnValue(int rv) { this.defRetValue = rv; } @Override public int defaultReturnValue() { return this.defRetValue; } }
21.931034
71
0.731132
9b6bbbb9b47d48b38636d74c76a54c042fc51045
2,711
package com.example.practical_4; public class TemeratureConverter { private String source,destination; double firstNumber,secondNumber; public TemeratureConverter(String source, String destination, double firstNumber) { this.source = source; this.destination = destination; this.firstNumber = firstNumber; } public double conversion(){ switch (source){ case "celsius":{ switch (destination){ case "celsius":{ secondNumber=firstNumber; return secondNumber; } case "fahrenheit":{ secondNumber=(firstNumber*9/(double)5)+32; return secondNumber; } case "kelvin":{ secondNumber=firstNumber+273.15; return secondNumber; } default:{ secondNumber=0; return secondNumber; } } } case "fahrenheit":{ switch (destination){ case "celsius":{ secondNumber=(firstNumber-32)*(double)(5/(double)9); return secondNumber; } case "fahrenheit":{ secondNumber=firstNumber; return secondNumber; } case "kelvin":{ secondNumber=(((firstNumber-32)*5) / (double)9)+273.15; return secondNumber; } default:{ secondNumber=0; return secondNumber; } } } case "kelvin":{ switch (destination){ case "celsius":{ secondNumber=firstNumber-273.15; return secondNumber; } case "fahrenheit":{ secondNumber=(firstNumber-273.15)*(9/(double)5)+32; return secondNumber; } case "kelvin": { secondNumber = firstNumber; return secondNumber; } default:{ return secondNumber; } } } default:{ secondNumber=0; return secondNumber; } } } }
33.060976
87
0.389155
129b3e582ca01cf234f4a1fdf9c9d73c97cf9d93
3,050
package yc.com.english_study.study_1vs1.model.bean; import android.os.Parcel; import android.os.Parcelable; import com.alibaba.fastjson.annotation.JSONField; /** * Created by wanglin on 2018/12/19 15:09. */ public class SlideInfo implements Parcelable{ private String id; private String title; private String type; private String img; @JSONField(name = "type_value") private String typeValue; @JSONField(name = "is_del") private String isDel; private String sort; private String statistics;//友盟统计字段 private String url;//跳转链接 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getTypeValue() { return typeValue; } public void setTypeValue(String typeValue) { this.typeValue = typeValue; } public String getIsDel() { return isDel; } public void setIsDel(String isDel) { this.isDel = isDel; } public String getSort() { return sort; } public void setSort(String sort) { this.sort = sort; } public String getStatistics() { return statistics; } public void setStatistics(String statistics) { this.statistics = statistics; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.id); dest.writeString(this.title); dest.writeString(this.type); dest.writeString(this.img); dest.writeString(this.typeValue); dest.writeString(this.isDel); dest.writeString(this.sort); dest.writeString(this.statistics); dest.writeString(this.url); } public SlideInfo() { } protected SlideInfo(Parcel in) { this.id = in.readString(); this.title = in.readString(); this.type = in.readString(); this.img = in.readString(); this.typeValue = in.readString(); this.isDel = in.readString(); this.sort = in.readString(); this.statistics = in.readString(); this.url = in.readString(); } public static final Creator<SlideInfo> CREATOR = new Creator<SlideInfo>() { @Override public SlideInfo createFromParcel(Parcel source) { return new SlideInfo(source); } @Override public SlideInfo[] newArray(int size) { return new SlideInfo[size]; } }; }
21.180556
79
0.594098
bf135728065cca5a89fc2046ec3653d60d89791c
2,563
package problems; import java.util.HashMap; import java.util.Map; /** * https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/ * algorithms * Medium (34.02%) * Total Accepted: 136.4K * Total Submissions: 400.1K * Testcase Example: '[3,9,20,15,7]\n[9,3,15,20,7]' Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example, given preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree: 3 / \ 9 20 / \ 15 7 */ public class ConstructBinaryTreeFromPreorderAndInorderTraversal { public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } /** * The idea is that the first value in the preorder represents the root value since it's root, left, right. * We can use this value and the inorder values to find all the values to the left and right of the root since it's * left, root, right. * * We can continue to do this, recursively, for each subarray. */ public static TreeNode buildTree(int[] preorder, int[] inorder) { Map<Integer, Integer> inorderValues = new HashMap<>(); for (int i = 0; i < inorder.length; i++) { inorderValues.put(inorder[i], i); } return helper(0, 0, inorder.length - 1, preorder, inorder, inorderValues); } private static TreeNode helper( int preorderStart, int inorderStart, int inorderEnd, int[] preorder, int[] inorder, Map<Integer, Integer> inorderValues ) { if (preorderStart > preorder.length || inorderStart > inorderEnd) { return null; } TreeNode root = new TreeNode(preorder[preorderStart]); Integer rootIndexInorder = inorderValues.get(preorder[preorderStart]); TreeNode left = helper( preorderStart + 1, inorderStart, rootIndexInorder - 1, preorder, inorder, inorderValues ); TreeNode right = helper( preorderStart + rootIndexInorder - inorderStart + 1, rootIndexInorder + 1, inorderEnd, preorder, inorder, inorderValues ); root.left = left; root.right = right; return root; } }
25.63
119
0.585642
107a466e0adf07917f0bd9720ebe2e5dcb61f4d4
4,815
package cz.balikobot.api.model.aggregates; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import lombok.Data; import cz.balikobot.api.contracts.Countable; import cz.balikobot.api.contracts.IteratorAggregate; import cz.balikobot.api.definitions.Shipper; import cz.balikobot.api.exceptions.InvalidArgumentException; import cz.balikobot.api.model.values.ArrayAccess; import cz.balikobot.api.model.values.PackageTransportCost; @Data public class PackageTransportCostCollection implements ArrayAccess<Integer ,PackageTransportCost>, Countable, IteratorAggregate<PackageTransportCost> { /** * Package costs * * @var ArrayList<int,\Inspirum\Balikobot\Model\Values\PackageTransportCost>|\Inspirum\Balikobot\Model\Values\PackageTransportCost[] */ private ArrayList<PackageTransportCost> costs = new ArrayList(); /** * Shipper code * * @var String|null */ private Shipper shipper; /** * OrderedPackageCollection constructor * * @param shipper */ public PackageTransportCostCollection(Shipper shipper) { this.shipper = shipper; } /** * Add package cost * * @param \Inspirum\Balikobot\Model\Values\PackageTransportCost package * @return void * @throws \InvalidArgumentException */ public void add(PackageTransportCost packageTransportCost) throws InvalidArgumentException { // validate package cost shipper this.validateShipper(packageTransportCost); // add package cost to collection this.costs.add(packageTransportCost); } /** * Get shipper * * @return String */ public Shipper getShipper() { if (this.shipper == null) { throw new RuntimeException("Collection is empty"); } return this.shipper; } /** * Get EIDs * * @return ArrayList<String> */ public List<String> getBatchIds() { return this.costs.stream().map(PackageTransportCost::getBatchId).collect(Collectors.toList()); } /** * Get total cost for all packages * * @return Double */ public Double getTotalCost() { Double totalCost = 0.0; String currencyCode = this.getCurrencyCode(); for(PackageTransportCost cost: this.costs) { if (!cost.getCurrencyCode().equals(currencyCode)) { throw new RuntimeException("Package cost currency codes are not the same"); } totalCost += cost.getTotalCost(); } return totalCost; } /** * Get currency code * * @return String */ public String getCurrencyCode() { if (this.costs==null ||this.costs.isEmpty()) { throw new RuntimeException("Collection is empty"); } return this.costs.get(0).getCurrencyCode(); } /** * Validate shipper * * @param \Inspirum\Balikobot\Model\Values\PackageTransportCost package * @return void * @throws \InvalidArgumentException */ private boolean validateShipper(PackageTransportCost pPackage) { //throws InvalidArgumentException { // set shipper if first pPackage in collection if (this.shipper == null) { this.shipper = pPackage.getShipper(); } // validate shipper // throw new InvalidArgumentException( // String.format( // "Package is from different shipper (\"%s\" instead of \"%s\")", // pPackage.getShipper(), // this.shipper // ) // ); return this.shipper == pPackage.getShipper(); } /** * Determine if an item exists at an offset * * @param key * @return Boolean */ public Boolean offsetExists(Integer key) { try { this.costs.get(key); return true; } catch (Exception e) { } return false; } /** * Get an item at a given offset * * @param key * @return \Inspirum\Balikobot\Model\Values\PackageTransportCost */ public PackageTransportCost offsetGet(Integer key) { return this.costs.get(key); } /** * Set the item at a given offset * * @param key * @param \Inspirum\Balikobot\Model\Values\PackageTransportCost value * @return void */ public void offsetSet(Integer key, PackageTransportCost value) { if (this.validateShipper(value)) { this.costs.set(key, value); } } /** * Unset the item at a given offset * * @param key * @return void */ public void offsetUnset(Integer key) { this.costs.remove(key); } /** * Count elements of an object * * @return int */ public int count() { return this.costs.size(); } /** * Get an iterator for the items * * @return \ArrayIterator<int,\Inspirum\Balikobot\Model\Values\PackageTransportCost> */ public Iterator<PackageTransportCost> getIterator() { return this.costs.iterator(); } }
23.719212
151
0.659398
b30092ab7f049ad849e373e583478b6ac4870252
96
package com.hazelcast.test; public class ExpectedRuntimeException extends RuntimeException { }
19.2
64
0.84375
140a13d1585bb59796700a24e13cd5452f9bb995
18,738
package pokecube.core.items.pokecubes; import java.util.List; import java.util.Set; import java.util.function.Predicate; import javax.annotation.Nullable; import com.google.common.collect.Sets; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.SoundEvents; import net.minecraft.item.EnumAction; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.server.permission.IPermissionHandler; import net.minecraftforge.server.permission.PermissionAPI; import net.minecraftforge.server.permission.context.PlayerContext; import pokecube.core.PokecubeItems; import pokecube.core.database.PokedexEntry; import pokecube.core.handlers.Config; import pokecube.core.handlers.playerdata.PlayerPokemobCache; import pokecube.core.interfaces.IPokecube; import pokecube.core.interfaces.IPokemob; import pokecube.core.interfaces.IPokemob.Stats; import pokecube.core.interfaces.PokecubeMod; import pokecube.core.interfaces.capabilities.CapabilityPokemob; import pokecube.core.moves.MovesUtils; import pokecube.core.utils.Permissions; import pokecube.core.utils.TagNames; import pokecube.core.utils.Tools; import thut.api.maths.Vector3; import thut.core.common.commands.CommandTools; import thut.lib.CompatWrapper; public class Pokecube extends Item implements IPokecube { public static final Set<Class<? extends EntityLivingBase>> snagblacklist = Sets.newHashSet(); private static final Predicate<EntityLivingBase> capturable = new Predicate<EntityLivingBase>() { @Override public boolean test(EntityLivingBase t) { if (snagblacklist .contains(t.getClass())) return false; for (Class<? extends EntityLivingBase> claz : snagblacklist) { if (claz.isInstance(t)) return false; } return true; } }; @SideOnly(Side.CLIENT) public static void displayInformation(NBTTagCompound nbt, List<String> list) { boolean flag2 = nbt.getBoolean("Flames"); if (flag2) { list.add(I18n.format("item.pokecube.flames")); } boolean flag3 = nbt.getBoolean("Bubbles"); if (flag3) { list.add(I18n.format("item.pokecube.bubbles")); } boolean flag4 = nbt.getBoolean("Leaves"); if (flag4) { list.add(I18n.format("item.pokecube.leaves")); } boolean flag5 = nbt.hasKey("dye"); if (flag5) { // TODO better tooltip for dyes? list.add(I18n.format(EnumDyeColor.byDyeDamage(nbt.getInteger("dye")).getUnlocalizedName())); } } public Pokecube() { super(); this.setHasSubtypes(false); this.setNoRepair(); setMaxDamage(PokecubeMod.MAX_DAMAGE); } /** allows items to add custom lines of information to the mouseover * description */ @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack item, @Nullable World world, List<String> list, ITooltipFlag advanced) { if (PokecubeManager.isFilled(item)) { IPokemob pokemob = PokecubeManager.itemToPokemob(item, world); if (pokemob == null) { list.add("ERROR"); return; } list.add(pokemob.getPokedexEntry().getTranslatedName()); NBTTagCompound pokeTag = item.getTagCompound().getCompoundTag(TagNames.POKEMOB); float health = pokeTag.getFloat("Health"); float maxHealth = pokemob.getStat(Stats.HP, false); int lvlexp = Tools.levelToXp(pokemob.getExperienceMode(), pokemob.getLevel()); int exp = pokemob.getExp() - lvlexp; int neededexp = Tools.levelToXp(pokemob.getExperienceMode(), pokemob.getLevel() + 1) - lvlexp; list.add(I18n.format("pokecube.tooltip.level", pokemob.getLevel())); list.add(I18n.format("pokecube.tooltip.health", health, maxHealth)); list.add(I18n.format("pokecube.tooltip.xp", exp, neededexp)); if (GuiScreen.isShiftKeyDown()) { String arg = ""; for (String s : pokemob.getMoves()) { if (s != null) { arg += I18n.format(MovesUtils.getUnlocalizedMove(s)) + ", "; } } if (arg.endsWith(", ")) { arg = arg.substring(0, arg.length() - 2); } list.add(I18n.format("pokecube.tooltip.moves", arg)); arg = ""; for (Byte b : pokemob.getIVs()) { arg += b + ", "; } if (arg.endsWith(", ")) { arg = arg.substring(0, arg.length() - 2); } list.add(I18n.format("pokecube.tooltip.ivs", arg)); arg = ""; for (Byte b : pokemob.getEVs()) { int n = b + 128; arg += n + ", "; } if (arg.endsWith(", ")) { arg = arg.substring(0, arg.length() - 2); } list.add(I18n.format("pokecube.tooltip.evs", arg)); list.add(I18n.format("pokecube.tooltip.nature", pokemob.getNature())); list.add(I18n.format("pokecube.tooltip.ability", pokemob.getAbility())); } else list.add(I18n.format("pokecube.tooltip.advanced")); } if (item.hasTagCompound()) { NBTTagCompound nbttagcompound = PokecubeManager.getSealTag(item); displayInformation(nbttagcompound, list); } } @Override public double getCaptureModifier(IPokemob mob, ResourceLocation id) { if (IPokecube.BEHAVIORS.containsKey(id)) return IPokecube.BEHAVIORS.getValue(id).getCaptureModifier(mob); return 0; } @Override public double getCaptureModifier(EntityLivingBase mob, ResourceLocation pokecubeId) { if (pokecubeId.getResourcePath().equals("snag")) { if (mob.getIsInvulnerable()) return 0; return 1; } IPokemob pokemob = CapabilityPokemob.getPokemobFor(mob); return (pokemob != null) ? getCaptureModifier(pokemob, pokecubeId) : 0; } @Override /** returns the action that specifies what animation to play when the items * is being used */ public EnumAction getItemUseAction(ItemStack stack) { return EnumAction.BOW; } @Override /** How long it takes to use or consume an item */ public int getMaxItemUseDuration(ItemStack stack) { return 2000; } @Override public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) { player.setActiveHand(hand); return new ActionResult<ItemStack>(EnumActionResult.SUCCESS, player.getHeldItem(hand)); } @Override /** Called when the player stops using an Item (stops holding the right * mouse button). */ public void onPlayerStoppedUsing(ItemStack stack, World worldIn, EntityLivingBase entityLiving, int timeLeft) { if (entityLiving instanceof EntityPlayer && !worldIn.isRemote) { EntityPlayer player = (EntityPlayer) entityLiving; com.google.common.base.Predicate<Entity> selector = new com.google.common.base.Predicate<Entity>() { @Override public boolean apply(Entity input) { IPokemob pokemob = CapabilityPokemob.getPokemobFor(input); if (pokemob == null) return true; return pokemob.getOwner() != player; } }; Entity target = Tools.getPointedEntity(player, 32, selector); Vector3 direction = Vector3.getNewVector().set(player.getLook(0)); Vector3 targetLocation = Tools.getPointedLocation(player, 32); if (target instanceof EntityPokecube) target = null; IPokemob targetMob = CapabilityPokemob.getPokemobFor(target); if (targetMob != null) { if (targetMob.getPokemonOwner() == entityLiving) target = null; } boolean filled = PokecubeManager.isFilled(stack); if (!filled && target instanceof EntityLivingBase && getCaptureModifier((EntityLivingBase) target, PokecubeItems.getCubeId(this)) == 0) target = null; boolean used = false; boolean filledOrSneak = filled || player.isSneaking(); if (target != null && EntityPokecubeBase.SEEKING) { used = throwPokecubeAt(worldIn, player, stack, targetLocation, target); } else if (filledOrSneak || !EntityPokecubeBase.SEEKING) { float power = (getMaxItemUseDuration(stack) - timeLeft) / (float) 100; power = Math.min(1, power); used = throwPokecube(worldIn, player, stack, direction, power); } else { CommandTools.sendError(player, "pokecube.badaim"); } if (used) { stack.splitStack(1); if (!CompatWrapper.isValid(stack)) { for (int i = 0; i < player.inventory.getSizeInventory(); i++) { if (player.inventory.getStackInSlot(i) == stack) { player.inventory.setInventorySlotContents(i, ItemStack.EMPTY); break; } } } } } } // Pokeseal stuff @SideOnly(Side.CLIENT) public boolean requiresMultipleRenderPasses() { return true; } @Override public boolean throwPokecube(World world, EntityLivingBase thrower, ItemStack cube, Vector3 direction, float power) { EntityPokecube entity = null; ResourceLocation id = PokecubeItems.getCubeId(cube.getItem()); if (id == null || !IPokecube.BEHAVIORS.containsKey(id)) return false; ItemStack stack = cube.copy(); boolean hasMob = PokecubeManager.hasMob(stack); Config config = PokecubeMod.core.getConfig(); // Check permissions if (hasMob && (config.permsSendOut || config.permsSendOutSpecific) && thrower instanceof EntityPlayer) { PokedexEntry entry = PokecubeManager.getPokedexEntry(stack); EntityPlayer player = (EntityPlayer) thrower; IPermissionHandler handler = PermissionAPI.getPermissionHandler(); PlayerContext context = new PlayerContext(player); if (config.permsSendOut && !handler.hasPermission(player.getGameProfile(), Permissions.SENDOUTPOKEMOB, context)) return false; if (config.permsSendOutSpecific && !handler.hasPermission(player.getGameProfile(), Permissions.SENDOUTSPECIFIC.get(entry), context)) return false; } stack.setCount(1); entity = new EntityPokecube(world, thrower, stack); Vector3 temp = Vector3.getNewVector().set(thrower).add(0, thrower.getEyeHeight(), 0); Vector3 temp1 = Vector3.getNewVector().set(thrower.getLookVec()).scalarMultBy(1.5); temp.addTo(temp1).moveEntity(entity); temp.set(direction.scalarMultBy(power * 10)).setVelocities(entity); entity.targetEntity = null; entity.targetLocation.clear(); entity.forceSpawn = true; if (hasMob && !thrower.isSneaking()) { entity.targetLocation.y = -1; } if (!world.isRemote) { thrower.playSound(SoundEvents.ENTITY_EGG_THROW, 0.5F, 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F)); world.spawnEntity(entity); if (hasMob) PlayerPokemobCache.UpdateCache(stack, false, false); } return true; } @Override public boolean throwPokecubeAt(World world, EntityLivingBase thrower, ItemStack cube, Vector3 targetLocation, Entity target) { EntityPokecube entity = null; ResourceLocation id = PokecubeItems.getCubeId(cube.getItem()); if (id == null || !IPokecube.BEHAVIORS.containsKey(id)) return false; ItemStack stack = cube.copy(); stack.setCount(1); entity = new EntityPokecube(world, thrower, stack); boolean rightclick = target == thrower; if (rightclick) target = null; if (target instanceof EntityLivingBase || PokecubeManager.hasMob(cube) || thrower.isSneaking() || (thrower instanceof FakePlayer)) { if (target instanceof EntityLivingBase) entity.targetEntity = (EntityLivingBase) target; if (target == null && targetLocation == null && PokecubeManager.hasMob(cube)) { targetLocation = Vector3.secondAxisNeg; } entity.targetLocation.set(targetLocation); if (thrower.isSneaking()) { Vector3 temp = Vector3.getNewVector().set(thrower).add(0, thrower.getEyeHeight(), 0); Vector3 temp1 = Vector3.getNewVector().set(thrower.getLookVec()).scalarMultBy(1.5); temp.addTo(temp1).moveEntity(entity); temp.clear().setVelocities(entity); entity.targetEntity = null; entity.targetLocation.clear(); } if (!world.isRemote) { thrower.playSound(SoundEvents.ENTITY_EGG_THROW, 0.5F, 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F)); world.spawnEntity(entity); if (PokecubeManager.isFilled(stack)) PlayerPokemobCache.UpdateCache(stack, false, false); } } else if (!rightclick) { return false; } return true; } @Override public boolean canCapture(EntityLiving hit, ItemStack cube) { ResourceLocation id = PokecubeItems.getCubeId(cube); if (id != null && id.getResourcePath().equals("snag")) { if (getCaptureModifier(hit, id) <= 0) return false; return capturable.test(hit); } return CapabilityPokemob.getPokemobFor(hit) != null; } /** Determines if this Item has a special entity for when they are in the * world. Is called when a EntityItem is spawned in the world, if true and * Item#createCustomEntity returns non null, the EntityItem will be * destroyed and the new Entity will be added to the world. * * @param stack * The current item stack * @return True of the item has a custom entity, If true, * Item#createCustomEntity will be called */ @Override public boolean hasCustomEntity(ItemStack stack) { return PokecubeManager.hasMob(stack); } /** This function should return a new entity to replace the dropped item. * Returning null here will not kill the EntityItem and will leave it to * function normally. Called when the item it placed in a world. * * @param world * The world object * @param location * The EntityItem object, useful for getting the position of the * entity * @param itemstack * The current item stack * @return A new Entity object to spawn or null */ @Override public Entity createEntity(World world, Entity oldItem, ItemStack itemstack) { if (hasCustomEntity(itemstack)) { FakePlayer player = PokecubeMod.getFakePlayer(world); EntityPokecube cube = new EntityPokecube(world, player, itemstack); cube.motionX = cube.motionY = cube.motionZ = 0; cube.shootingEntity = null; cube.shooter = null; Vector3.getNewVector().set(oldItem).moveEntity(cube); cube.tilt = -2; cube.targetLocation.clear(); return cube; } return null; } }
41.364238
146
0.549685
ac347249ee45693212ac49f1e13b715d353a0cdf
8,814
// Copyright 2017 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.content_shell_apk; import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout; import android.annotation.TargetApi; import android.app.Activity; import android.app.Instrumentation; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.PowerManager; import android.text.TextUtils; import android.view.ViewGroup; import org.junit.Assert; import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.UrlUtils; import org.chromium.content.browser.ContentView; import org.chromium.content.browser.ContentViewCore; import org.chromium.content.browser.test.util.Criteria; import org.chromium.content.browser.test.util.CriteriaHelper; import org.chromium.content.browser.test.util.TestCallbackHelperContainer; import org.chromium.content_public.browser.LoadUrlParams; import org.chromium.content_public.browser.NavigationController; import org.chromium.content_public.browser.WebContents; import org.chromium.content_shell.Shell; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; /** * Implementation of utility methods for ContentShellTestBase and ContentShellActivityTestRule to * wrap around during instrumentation test JUnit3 to JUnit4 migration * * Please do not use this class' methods in places other than {@link ContentShellTestBase} * and {@link ContentShellActivityTestRule} */ public final class ContentShellTestCommon { /** The maximum time the waitForActiveShellToBeDoneLoading method will wait. */ private static final long WAIT_FOR_ACTIVE_SHELL_LOADING_TIMEOUT = scaleTimeout(10000); static final long WAIT_PAGE_LOADING_TIMEOUT_SECONDS = scaleTimeout(15); private final TestCommonCallback<ContentShellActivity> mCallback; ContentShellTestCommon(TestCommonCallback<ContentShellActivity> callback) { mCallback = callback; } @TargetApi(Build.VERSION_CODES.KITKAT_WATCH) @SuppressWarnings("deprecation") void assertScreenIsOn() { PowerManager pm = (PowerManager) mCallback.getInstrumentationForTestCommon() .getContext() .getSystemService(Context.POWER_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { Assert.assertTrue("Many tests will fail if the screen is not on.", pm.isInteractive()); } else { Assert.assertTrue("Many tests will fail if the screen is not on.", pm.isScreenOn()); } } ContentShellActivity launchContentShellWithUrl(String url) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (url != null) intent.setData(Uri.parse(url)); intent.setComponent( new ComponentName(mCallback.getInstrumentationForTestCommon().getTargetContext(), ContentShellActivity.class)); return mCallback.launchActivityWithIntentForTestCommon(intent); } // TODO(yolandyan): This should use the url exactly without the getIsolatedTestFileUrl call. ContentShellActivity launchContentShellWithUrlSync(String url) { String isolatedTestFileUrl = UrlUtils.getIsolatedTestFileUrl(url); ContentShellActivity activity = launchContentShellWithUrl(isolatedTestFileUrl); Assert.assertNotNull(mCallback.getActivityForTestCommon()); waitForActiveShellToBeDoneLoading(); Assert.assertEquals( isolatedTestFileUrl, getContentViewCore().getWebContents().getLastCommittedUrl()); return activity; } void waitForActiveShellToBeDoneLoading() { // Wait for the Content Shell to be initialized. CriteriaHelper.pollUiThread(new Criteria() { @Override public boolean isSatisfied() { Shell shell = mCallback.getActivityForTestCommon().getActiveShell(); // There are two cases here that need to be accounted for. // The first is that we've just created a Shell and it isn't // loading because it has no URL set yet. The second is that // we've set a URL and it actually is loading. if (shell == null) { updateFailureReason("Shell is null."); return false; } if (shell.isLoading()) { updateFailureReason("Shell is still loading."); return false; } if (TextUtils.isEmpty( shell.getContentViewCore().getWebContents().getLastCommittedUrl())) { updateFailureReason("Shell's URL is empty or null."); return false; } return true; } }, WAIT_FOR_ACTIVE_SHELL_LOADING_TIMEOUT, CriteriaHelper.DEFAULT_POLLING_INTERVAL); } ContentViewCore getContentViewCore() { return mCallback.getActivityForTestCommon().getActiveShell().getContentViewCore(); } WebContents getWebContents() { return mCallback.getActivityForTestCommon().getActiveShell().getWebContents(); } void loadUrl(final NavigationController navigationController, TestCallbackHelperContainer callbackHelperContainer, final LoadUrlParams params) throws Throwable { handleBlockingCallbackAction( callbackHelperContainer.getOnPageFinishedHelper(), new Runnable() { @Override public void run() { navigationController.loadUrl(params); } }); } Shell loadNewShell(final String url) throws ExecutionException { Shell shell = ThreadUtils.runOnUiThreadBlocking(new Callable<Shell>() { @Override public Shell call() { mCallback.getActivityForTestCommon().getShellManager().launchShell(url); return mCallback.getActivityForTestCommon().getActiveShell(); } }); Assert.assertNotNull("Unable to create shell.", shell); Assert.assertEquals("Active shell unexpected.", shell, mCallback.getActivityForTestCommon().getActiveShell()); waitForActiveShellToBeDoneLoading(); return shell; } void handleBlockingCallbackAction(CallbackHelper callbackHelper, Runnable uiThreadAction) throws Throwable { int currentCallCount = callbackHelper.getCallCount(); mCallback.runOnUiThreadForTestCommon(uiThreadAction); callbackHelper.waitForCallback( currentCallCount, 1, WAIT_PAGE_LOADING_TIMEOUT_SECONDS, TimeUnit.SECONDS); } void assertWaitForPageScaleFactorMatch(float expectedScale) { CriteriaHelper.pollInstrumentationThread( Criteria.equals(expectedScale, new Callable<Float>() { @Override public Float call() { return getContentViewCore().getScale(); } })); } void replaceContainerView() throws Throwable { ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { ContentView cv = ContentView.createContentView( mCallback.getActivityForTestCommon(), getContentViewCore()); ((ViewGroup) getContentViewCore().getContainerView().getParent()).addView(cv); getContentViewCore().setContainerView(cv); getContentViewCore().setContainerViewInternals(cv); cv.requestFocus(); } }); } /** * Interface used by TestRule and TestBase class to implement methods for TestCommonCallback * class to use. */ public static interface TestCommonCallback<T extends Activity> { Instrumentation getInstrumentationForTestCommon(); T launchActivityWithIntentForTestCommon(Intent t); T getActivityForTestCommon(); void runOnUiThreadForTestCommon(Runnable runnable) throws Throwable; ContentViewCore getContentViewCoreForTestCommon(); ContentShellActivity launchContentShellWithUrlForTestCommon(String url); WebContents getWebContentsForTestCommon(); void waitForActiveShellToBeDoneLoadingForTestCommon(); } }
43.418719
99
0.680281
f55c27e075996c68553801fd6451d8f6a44795a4
2,105
/* * Copyright 2017 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.pipeline.api.base; import com.streamsets.pipeline.api.ConfigIssue; import com.streamsets.pipeline.api.service.Service; import java.util.ArrayList; import java.util.Collections; import java.util.List; public abstract class BaseService implements Service { private Service.Context context; /** * Initializes the service. * * Stores the <code>Service.Context</code> in instance variables and calls the {@link #init()} method. * * @param context Service context. * @return The list of configuration issues found during initialization, an empty list if none. */ @Override public List<ConfigIssue> init(Service.Context context) { this.context = context; return init(); } /** * Initializes the stage. Subclasses should override this method for service initialization. * * This implementation is a no-operation. * * @return The list of configuration issues found during initialization, an empty list if none. */ protected List<ConfigIssue> init() { return new ArrayList<>(); } /** * Returns the service context passed by the Data Collector during initialization. * * @return Service context passed by the Data Collector during initialization. */ protected Service.Context getContext() { return context; } /** * Destroy the service. Subclasses should override this method for stage cleanup. * * This implementation is a no-operation. */ @Override public void destroy() { } }
29.236111
104
0.719715
1064c839e8b00187aab935e710ef2ec2ab73b3cd
1,816
package practicaltest01.eim.systems.cs.pub.ro.practicaltest01var02.view; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import practicaltest01.eim.systems.cs.pub.ro.practicaltest01var02.R; public class PracticalTest01Var02SecondaryActivity extends AppCompatActivity { Button correctButt; Button incorrectButt; EditText resultEdit; ButtonClickListener buttonClickListener = new ButtonClickListener(); private class ButtonClickListener implements View.OnClickListener { @Override public void onClick(View view) { if (view.getId() == correctButt.getId()) { setResult(RESULT_OK, null); } if (view.getId() == incorrectButt.getId()) { setResult(RESULT_CANCELED, null); } // pt a te intoarce la activitatea principala finish(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_practical_test01_var02_secondary); resultEdit = (EditText) findViewById(R.id.result_edit); // Trebuie sa obtii intentia! Intent intent = getIntent(); if (intent != null && intent.getExtras().containsKey("thirdEdit")) { String text = intent.getStringExtra("thirdEdit"); resultEdit.setText(text); } correctButt = (Button) findViewById(R.id.correct_butt); correctButt.setOnClickListener(buttonClickListener); incorrectButt = (Button) findViewById(R.id.incorrect_butt); incorrectButt.setOnClickListener(buttonClickListener); } }
32.428571
78
0.68337
18553fe31eebb88924371ef9fa0389b69f23c8e3
137
public class HelloWorld { public static void main(String[] args) { System.out.println("give me a bottle of rum!"); } }
17.125
55
0.620438
8df6f83fb860144b65509b5b9b6476b1f2666ba7
1,657
/* * MIT License * * Copyright (c) 2018 Tassu <hello@tassu.me> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.tassu.mill.example.commands; import com.google.inject.Singleton; import me.tassu.mill.api.ann.Command; import me.tassu.snake.util.Chat; import org.bukkit.command.CommandSender; @Singleton public class ExampleSubcommands { @Command({"fun"}) public void onCommand(CommandSender sender, int number) { sender.sendMessage(Chat.PURPLE + "That number is: " + number); } @Command({"/asdf asd", "yeah", "/asdf"}) public void doThatCommand() {} public void execute() {} }
36.021739
81
0.738081
c1ee45a3914178849d2b95ccc6d82652f75fff6f
8,535
/** * * 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.openejb.server.axis.assembler; import org.apache.openejb.assembler.classic.InfoObject; import javax.xml.namespace.QName; import java.util.List; import java.util.Map; import java.util.Set; import java.util.HashSet; import java.util.ArrayList; import java.lang.reflect.Field; import org.junit.Assert; public final class TypeInfoTestUtil { private TypeInfoTestUtil() { } public static void assertEqual(InfoObject expected, InfoObject actual) throws Exception { assertEqual(expected, actual, false); } public static void assertEqual(InfoObject expected, InfoObject actual, boolean printExpected) throws Exception { List<String> messages = new ArrayList<String>(); diff(null, expected, actual, messages); if (!messages.isEmpty()) { if (printExpected) { System.out.println("************ Actual " + expected.getClass().getSimpleName() + " ************"); dump("expected", actual); System.out.println("**********************************************"); System.out.println(); } StringBuilder msg = new StringBuilder(); for (String message : messages) { if (msg.length() != 0) msg.append("\n"); msg.append(message); } msg.insert(0, expected.getClass().getSimpleName() + " is different:\n"); Assert.fail(msg.toString()); } } public static void diff(String name, Object expected, Object actual, List<String> messages) throws Exception { for (Field field : expected.getClass().getFields()) { String fieldName = name == null ? field.getName() : name + "." + field.getName(); Object expectedValue = field.get(expected); Object actualValue = field.get(actual); if (expectedValue instanceof InfoObject) { diff(fieldName, expectedValue, actualValue, messages); } else if (expectedValue instanceof Map) { //noinspection unchecked diffMap(fieldName, (Map) expectedValue, (Map) actualValue, messages); } else { diffSimple(fieldName, expectedValue, actualValue, messages); } } } private static void diffMap(String name, Map<Object,Object> expected, Map<Object,Object> actual, List<String> message) throws Exception { // Added Set<Object> keys = new HashSet<Object>(actual.keySet()); keys.removeAll(expected.keySet()); for (Object key : keys) { message.add("A " + name + "[" + key + "]"); } // Removed keys = new HashSet<Object>(expected.keySet()); keys.removeAll(actual.keySet()); for (Object key : keys) { message.add("R " + name + "[" + key + "]"); } // Changed for (Object key : expected.keySet()) { Object expectValue = expected.get(key); Object actualValue = actual.get(key); if (actualValue != null) { diff(name + "[" + key + "]", expectValue, actualValue, message); } } } private static void diffSimple(String name, Object expected, Object actual, List<String> messages) { boolean changed = true; if (expected == null) { if (actual == null) changed = false; } else { if (expected.equals(actual)) changed = false; } if (changed) { messages.add("C " + name + ": " + expected + " ==> " + actual); } } public static void dump(String name, Object value) throws Exception { if (name == null) throw new NullPointerException("name is null"); if (isSimpleValue(value)) { if (name.indexOf('.') > 0) { System.out.println(name + " = " + getSimpleValue(value) + ";"); } else { if (value == null) throw new NullPointerException("value is null"); System.out.println(getTypeDecl(value.getClass(), name) + " = " + getSimpleValue(value) + ";"); } } else { System.out.println(getTypeDecl(value.getClass(), name) + " = new " + value.getClass().getSimpleName() + "();"); for (Field field : value.getClass().getFields()) { String fieldName = name == null ? field.getName() : name + "." + field.getName(); Object fieldValue = field.get(value); if (fieldValue instanceof Map) { //noinspection unchecked dumpMap(fieldName, (Map) fieldValue); } else { dump(fieldName, fieldValue); } } } } private static void dumpMap(String name, Map<Object,Object> map) throws Exception { for (Map.Entry<Object, Object> entry : map.entrySet()) { Object key = entry.getKey(); Object value = entry.getValue(); if (isSimpleValue(key) && isSimpleValue(value)) { System.out.println(name + ".put(" + getSimpleValue(key) + ", " + getSimpleValue(value) + ");"); } else { String indent = name.substring(0, getIndentSize(name)); String baseName; if (value instanceof InfoObject) { baseName = value.getClass().getSimpleName(); if (baseName.endsWith("Info")) baseName = baseName.substring(0, baseName.length() - 4); baseName = Character.toLowerCase(baseName.charAt(0)) + baseName.substring(1); } else { baseName = name.substring(indent.length()).replace('.', '_'); if (baseName.endsWith("Key")) baseName = baseName.substring(0, baseName.length() - 3); } System.out.println(indent + "{"); dump(indent + " " + baseName + "Key", key); System.out.println(); dump(indent + " " + baseName, value); System.out.println(); System.out.println(" " + name + ".put(" + baseName + "Key, " + baseName + ");"); System.out.println(indent + "}"); } } } private static boolean isSimpleValue(Object value) { return value == null || value instanceof Boolean || value instanceof Number || value instanceof String|| value instanceof QName; } private static String getSimpleValue(Object value) { if (!isSimpleValue(value)) throw new IllegalArgumentException("Value is not a simple type " + value.getClass().getName()); String stringValue; if (value == null) { stringValue = "null"; } else if (value instanceof Boolean) { stringValue = value.toString(); } else if (value instanceof Number) { stringValue = value.toString(); } else if (value instanceof QName) { QName qname = (QName) value; stringValue = "new QName(\"" + qname.getNamespaceURI() + "\", \"" + qname.getLocalPart() + "\")"; } else { stringValue = "\"" + value + "\""; } return stringValue; } private static String getTypeDecl(Class type, String name) { int indentSize = getIndentSize(name); return name.substring(0, indentSize) + type.getSimpleName() + " " + name.substring(indentSize); } private static int getIndentSize(String name) { for (int i = 0; i < name.length(); i++) { if (name.charAt(i) != ' ') { return i; } } return 0; } }
41.033654
141
0.56321
513514f3f9fce161df38f96e740334ca9aad7d46
2,970
/** * @class RMEPUBSearchItem.java * @date 2014-3-12 * @copyright 版权(C)重庆软媒科技有限公司 2013-2014 * @author vken */ package rmkj.lib.read.epub.search; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import rmkj.lib.read.util.LogUtil; public class RMSpineSearchResult { public class RMEPUBSearchResultItem { // private String key; // private Rect rect = new Rect(); // private int containerIndex; // private int startIndex; // private int endIndex; private int page; public int getPage() { return page; } public RMEPUBSearchResultItem() { /* * {"containerIndex":13,"startIndex":9,"endIndex":11,"value":"彼得"} * 'left': rect.left + scrollLeft, 'top': rect.top + scrollTop, * 'width': rect.width, 'height': rect.height */ // containerIndex = valueJson.getInt("containerIndex"); // startIndex = valueJson.getInt("startIndex"); // endIndex = valueJson.getInt("endIndex"); } // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // public Rect getRect() { // return rect; // } // // public void setRect(Rect rect) { // this.rect = rect; // } // public int getContainerIndex() { // return containerIndex; // } // // public void setContainerIndex(int containerIndex) { // this.containerIndex = containerIndex; // } // // public int getStartIndex() { // return startIndex; // } // // public void setStartIndex(int startIndex) { // this.startIndex = startIndex; // } // // public int getEndIndex() { // return endIndex; // } // // public void setEndIndex(int endIndex) { // this.endIndex = endIndex; // } } private List<RMEPUBSearchResultItem> searchArray = null; public RMSpineSearchResult(JSONObject json) throws JSONException { if (json == null) return; if (searchArray == null) searchArray = new ArrayList<RMEPUBSearchResultItem>(); // int resultCount = json.getInt("count"); JSONArray itemsArray = json.getJSONArray("searchResult"); for (int i = 0; i < itemsArray.length(); i++) { RMEPUBSearchResultItem item = new RMEPUBSearchResultItem(); JSONObject itemObject = itemsArray.getJSONObject(i); try{ item.page = itemObject.getInt("page"); }catch(Exception e){ item.page=0; } //LogUtil.e(RMSpineSearchResult.class, "") // JSONObject rect = itemObject.getJSONObject("rect"); // item.rect.left = rect.getInt("x"); // item.rect.bottom = rect.getInt("y"); // item.rect.right = rect.getInt("w"); // item.rect.top = rect.getInt("h"); searchArray.add(item); } } public RMEPUBSearchResultItem getItem(int i) { if (searchArray == null) return null; if (searchArray.size() > i && i >= 0) { return searchArray.get(i); } else return null; } public int getCount() { if (searchArray == null) return 0; return searchArray.size(); } }
23.385827
69
0.651515
5b8a3807da4ef8d2450721a90a3f35d33fee2560
1,197
package domainTests; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import carPool.domain.GeoPosition; public class TestGeoPosition { private static Logger logger = LoggerFactory.getLogger(TestGeoPosition.class); GeoPosition testGeoPosotion; @Before public void before() { // Create a new GeoPosition for each test testGeoPosotion = new GeoPosition(5.55, 5.55); } @Test public void testGeoPositionFromString() { String asString = testGeoPosotion.toString(); logger.debug(asString); assertTrue(asString.equals("(5.55,5.55)")); GeoPosition fromString = new GeoPosition(asString); assertTrue(testGeoPosotion.equals(fromString)); } @Test public void testLengthTo() { // Make another GeoPosition GeoPosition position2 = new GeoPosition(0.0, 0.0); // Check that the length is the same each way assertTrue(position2.lengthTo(testGeoPosotion) == testGeoPosotion.lengthTo(position2)); logger.debug("length is: " + position2.lengthTo(testGeoPosotion)); assertTrue(position2.lengthTo(testGeoPosotion) == 871226); } }
27.204545
90
0.734336
026f027948b3ea20347dfed0e6454ed3b921bf1d
1,470
package de.naclstudios.btj.components; import de.edgelord.saltyengine.components.Component; import de.edgelord.saltyengine.core.graphics.SaltyGraphics; import de.naclstudios.btj.B4TJEntity; public abstract class EnemyMovement< T extends B4TJEntity> extends Component< T > { public static final String TAG = "de.naclstudios.enemymovement"; private float speed; private float senseRadius; public EnemyMovement(final T parent, final String name, final float speed, final float senseRadius) { super(parent, name, TAG); this.speed = speed; this.senseRadius = senseRadius; } @Override public void draw(final SaltyGraphics saltyGraphics) { // nothing to render! } /** * Gets {@link #speed}. * * @return the value of {@link #speed} */ public float getSpeed() { return speed; } /** * Sets {@link #speed}. * * @param speed the new value of {@link #speed} */ public void setSpeed(final float speed) { this.speed = speed; } /** * Gets {@link #senseRadius}. * * @return the value of {@link #senseRadius} */ public float getSenseRadius() { return senseRadius; } /** * Sets {@link #senseRadius}. * * @param senseRadius the new value of {@link #senseRadius} */ public void setSenseRadius(final float senseRadius) { this.senseRadius = senseRadius; } }
23.709677
105
0.623129
2f4c5d89a4467d21969961db5af961a67377493d
684
/** * * * * * */ package ecc; /** * An abstract elliptic curve point class representing a * point on the curve as two finite field elements x and y. * * @version 0.90 */ public abstract class ECPoint { /** * The x coordinate of the point. */ public Fq x; /** * The x coordinate of the point. */ public Fq y; /** * Returns true if this is the point at infinity, O = (0, 0). */ public boolean isZero() { return (x.isZero() & y.isZero()); } public String toString() { return "x:0x" + x + " y:0x" + y; } /** * Returns the additive inverse of this point (-P). */ public abstract ECPoint negate(); protected abstract Object clone(); }
14.553191
62
0.595029
dacdcf96ccf634fa0b9f4e8332d589d50c35857a
2,823
package com.dedicatedcode.paperspace.feeder; import com.dedicatedcode.paperspace.BinaryService; import com.dedicatedcode.paperspace.TestHelper; import com.dedicatedcode.paperspace.model.Binary; import com.dedicatedcode.paperspace.model.OCRState; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.TestPropertySource; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Optional; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @SpringBootTest @TestPropertySource(locations = "classpath:application-test.properties") class MergingFileEventHandlerTest { @Value("${storage.folder.documents}") private File documentStorage; @Autowired private BinaryService binaryService; @MockBean private PdfOcrService pdfOcrService; @BeforeEach void setUp() throws OcrException { when(pdfOcrService.supportedFileFormats()).thenReturn(Collections.singletonList("application/pdf")); when(pdfOcrService.doOcr(any(File.class))).thenReturn(Collections.emptyList()); } @Test @Timeout(5) void shouldHandleDuplicatedFileIfAlreadyKnown() throws IOException, InterruptedException { File targetFile = new File(documentStorage, UUID.randomUUID() + ".pdf"); TestHelper.TestFile testFile = TestHelper.randPdf(); FileUtils.moveFile(testFile.getFile(), targetFile); await(testFile); File copy = new File(documentStorage, targetFile.getName() + "_duplicate"); FileUtils.copyFile(targetFile, copy); while (this.binaryService.getAll().stream().noneMatch(binary -> binary.getStorageLocation().equals(copy.getAbsolutePath()))) { Thread.sleep(500); } Optional<Binary> storedBinary = this.binaryService.getAll().stream().filter(binary -> binary.getStorageLocation().equals(copy.getAbsolutePath())).findFirst(); assertTrue(storedBinary.isPresent()); assertEquals(OCRState.DUPLICATE, storedBinary.get().getState()); } private void await(TestHelper.TestFile testFile) throws InterruptedException { while (this.binaryService.getAll().stream().noneMatch(binary -> binary.getHash().equals(testFile.getHash()))) { Thread.sleep(500); } } }
37.64
166
0.754162
1afeae59477742eca1be3c2a43c066e589130388
941
package com.simon.service.impl; import com.simon.common.service.impl.CrudServiceImpl; import com.simon.mapper.DictTypeMultiLanguageMapper; import com.simon.model.DictTypeMultiLanguage; import com.simon.repository.DictTypeMultiLanguageRepository; import com.simon.service.DictTypeMultiLanguageService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * @author jeesun * @date 2019-06-03 **/ @Slf4j @Service @Transactional(rollbackFor = {Exception.class}) public class DictTypeMultiLanguageServiceImpl extends CrudServiceImpl<DictTypeMultiLanguage, Long> implements DictTypeMultiLanguageService { @Autowired private DictTypeMultiLanguageMapper dictTypeMultiLanguageMapper; @Autowired private DictTypeMultiLanguageRepository dictTypeMultiLanguageRepository; }
33.607143
140
0.844846
045d4b31d0d725fa57fa58831f7e8a44ec165ef2
92
package api.util; /** * @author ve * @date 2020/2/23 22:40 */ public enum DigestKit { }
10.222222
24
0.608696
6d194472b84d684c816250b06f445645c73d6448
1,988
package com.sleekbyte.tailor.format; import java.util.Arrays; import java.util.stream.Collectors; /** * {@link com.sleekbyte.tailor.output.ViolationMessage} output formats. */ public enum Format { XCODE, JSON, CC, HTML; private String name; private String className; private String description; public String getName() { return name; } public String getClassName() { return className; } public String getDescription() { return description; } /** * Exception thrown when invalid format is provided. */ public static class IllegalFormatException extends Exception {} /** * Parse str and convert to appropriate Format. * * @param str Format string * @return Parsed Format value * @throws IllegalFormatException if string is not recognized */ public static Format parseFormat(String str) throws IllegalFormatException { for (Format format : Format.values()) { if (format.getName().equals(str)) { return format; } } throw new IllegalFormatException(); } public static String getFormats() { return String.join("|", Arrays.asList(Format.values()).stream().map(Format::getName).collect(Collectors.toList())); } static { XCODE.name = "xcode"; XCODE.description = "Output that displays directly in the Xcode editor when run from a Build Phase Run Script."; XCODE.className = XcodeFormatter.class.getName(); JSON.name = "json"; JSON.description = "Valid JSON format."; JSON.className = JSONFormatter.class.getName(); CC.name = "cc"; CC.description = "Format for integration with Code Climate."; CC.className = CCFormatter.class.getName(); HTML.name = "html"; HTML.description = "Valid HTML format."; HTML.className = HTMLFormatter.class.getName(); } }
26.506667
120
0.624748
7197c79a796c64f539eb488b9d377778abc40092
315
package org.jee.cdi.events; import javax.enterprise.event.Event; import javax.inject.Inject; /** * @author Radim Hanus */ public class GreetingSender implements EventSender { @Inject private Event<String> event; @Override public void send(String message) { event.fire(message); } }
17.5
52
0.692063
4df16796da4eba56e332c6dd1c0f6a99eb0964e5
2,494
package ru.sdetteam.easygauge.models.issue_model; import com.fasterxml.jackson.annotation.*; import java.util.HashMap; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "id", "name", "label" }) public class Reproducibility { @JsonProperty("id") private Integer id; @JsonProperty("name") private String name; @JsonProperty("label") private String label; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("id") public Integer getId() { return id; } @JsonProperty("id") public Reproducibility setId(Integer id) { this.id = id; return this; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public Reproducibility setName(String name) { this.name = name; return this; } @JsonProperty("label") public String getLabel() { return label; } @JsonProperty("label") public Reproducibility setLabel(String label) { this.label = label; return this; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public Reproducibility setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Reproducibility.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('['); sb.append("id"); sb.append('='); sb.append(((this.id == null)?"<null>":this.id)); sb.append(','); sb.append("name"); sb.append('='); sb.append(((this.name == null)?"<null>":this.name)); sb.append(','); sb.append("label"); sb.append('='); sb.append(((this.label == null)?"<null>":this.label)); sb.append(','); sb.append("additionalProperties"); sb.append('='); sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties)); sb.append(','); if (sb.charAt((sb.length()- 1)) == ',') { sb.setCharAt((sb.length()- 1), ']'); } else { sb.append(']'); } return sb.toString(); } }
25.44898
134
0.582598
b9824165a339c1cc258f40e39b9a02c65382f530
1,962
package com.karim.examples.java.audit.dal.orm.audit; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import com.karim.examples.java.audit.dal.orm.AuditEntity; /** * @author kabdelkareem * * Detail Entity contain extra properties about changed * columns' values only. * In case of insert/update, all columns logged. * */ @Entity @Table(name="AUDT_LOG_DTLS") @SuppressWarnings("serial") public class AuditLogDetailData extends AuditEntity { private Long id; private String columnName; private String columnType; private String oldValue; private String newValue; private Long auditLogId; @Id @Column(name="ID") @SequenceGenerator(name = "SEQ_AUDT_LOG_DTLS", sequenceName = "SEQ_AUDT_LOG_DTLS") @GeneratedValue(generator = "SEQ_AUDT_LOG_DTLS") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Basic @Column(name="COLUMN_NAME") public String getColumnName() { return columnName; } public void setColumnName(String columnName) { this.columnName = columnName; } @Basic @Column(name="COLUMN_TYPE") public String getColumnType() { return columnType; } public void setColumnType(String columnType) { this.columnType = columnType; } @Basic @Column(name="OLD_VALUE") public String getOldValue() { return oldValue; } public void setOldValue(String oldValue) { this.oldValue = oldValue; } @Basic @Column(name="NEW_VALUE") public String getNewValue() { return newValue; } public void setNewValue(String newValue) { this.newValue = newValue; } @Basic @Column(name="AUDIT_LOG_ID") public Long getAuditLogId() { return auditLogId; } public void setAuditLogId(Long auditLogId) { this.auditLogId = auditLogId; } }
21.8
86
0.727829
ee242d5d45bbd41fbd57d4a8a96b03022a7c986f
3,983
/* Suggestion Provider for RDP bookmarks Copyright 2013 Thinstuff Technologies GmbH, Author: Martin Fleisz This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.freerdp.freerdpcore.services; import java.util.ArrayList; import com.freerdp.freerdpcore.R; import com.freerdp.freerdpcore.application.GlobalApp; import com.freerdp.freerdpcore.domain.BookmarkBase; import com.freerdp.freerdpcore.domain.ConnectionReference; import com.freerdp.freerdpcore.domain.ManualBookmark; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentValues; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; public class FreeRDPSuggestionProvider extends ContentProvider { public static final Uri CONTENT_URI = Uri.parse("content://com.freerdp.afreerdp.services.freerdpsuggestionprovider"); @Override public int delete(Uri uri, String selection, String[] selectionArgs) { // TODO Auto-generated method stub return 0; } @Override public String getType(Uri uri) { return "vnd.android.cursor.item/vnd.freerdp.remote"; } @Override public Uri insert(Uri uri, ContentValues values) { // TODO Auto-generated method stub return null; } @Override public boolean onCreate() { return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { String query = (selectionArgs != null && selectionArgs.length > 0) ? selectionArgs[0] : ""; // search history ArrayList<BookmarkBase> history = GlobalApp.getQuickConnectHistoryGateway().findHistory(query); // search bookmarks ArrayList<BookmarkBase> manualBookmarks; if(query.length() > 0) manualBookmarks = GlobalApp.getManualBookmarkGateway().findByLabelOrHostnameLike(query); else manualBookmarks = GlobalApp.getManualBookmarkGateway().findAll(); return createResultCursor(history, manualBookmarks); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // TODO Auto-generated method stub return 0; } private void addBookmarksToCursor(ArrayList<BookmarkBase> bookmarks, MatrixCursor resultCursor) { Object[] row = new Object[5]; for(BookmarkBase bookmark : bookmarks) { row[0] = new Long(bookmark.getId()); row[1] = bookmark.getLabel(); row[2] = bookmark.<ManualBookmark>get().getHostname(); row[3] = ConnectionReference.getManualBookmarkReference(bookmark.getId()); row[4] = "android.resource://" + getContext().getPackageName() + "/" + R.drawable.icon_star_on; resultCursor.addRow(row); } } private void addHistoryToCursor(ArrayList<BookmarkBase> history, MatrixCursor resultCursor) { Object[] row = new Object[5]; for(BookmarkBase bookmark : history) { row[0] = new Integer(1); row[1] = bookmark.getLabel(); row[2] = bookmark.getLabel(); row[3] = ConnectionReference.getHostnameReference(bookmark.getLabel()); row[4] = "android.resource://" + getContext().getPackageName() + "/" + R.drawable.icon_star_off; resultCursor.addRow(row); } } private Cursor createResultCursor(ArrayList<BookmarkBase> history, ArrayList<BookmarkBase> manualBookmarks) { // create result matrix cursor int totalCount = history.size() + manualBookmarks.size(); String[] columns = { android.provider.BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_TEXT_2, SearchManager.SUGGEST_COLUMN_INTENT_DATA, SearchManager.SUGGEST_COLUMN_ICON_2 }; MatrixCursor matrixCursor = new MatrixCursor(columns, totalCount); // populate result matrix if(totalCount > 0) { addHistoryToCursor(history, matrixCursor); addBookmarksToCursor(manualBookmarks, matrixCursor); } return matrixCursor; } }
32.120968
119
0.750439
3cd678959adb73a75273b2dc7517eb19a051303e
5,707
/* * Copyright 2015 Viliam Repan (lazyman) * * 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 sk.lazyman.gizmo.data.provider; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.Predicate; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.EntityPathBase; import com.querydsl.jpa.impl.JPAQuery; import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import sk.lazyman.gizmo.data.AbstractTask; import sk.lazyman.gizmo.data.QAbstractTask; import sk.lazyman.gizmo.data.QLog; import sk.lazyman.gizmo.data.QWork; import sk.lazyman.gizmo.dto.CustomerProjectPartDto; import sk.lazyman.gizmo.dto.WorkFilterDto; import sk.lazyman.gizmo.dto.WorkType; import sk.lazyman.gizmo.web.PageTemplate; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author lazyman */ public class AbstractTaskDataProvider extends SortableDataProvider<AbstractTask, String> { private PageTemplate page; private WorkFilterDto filter; public AbstractTaskDataProvider(PageTemplate page) { this.page = page; } @Override public Iterator<? extends AbstractTask> iterator(long first, long count) { QAbstractTask task = QAbstractTask.abstractTask; QWork work = task.as(QWork.class); JPAQuery query = new JPAQuery(page.getEntityManager()); query.from(QAbstractTask.abstractTask).leftJoin(work.part.project); query.where(createPredicate()); query.orderBy(task.date.asc()); query.offset(first); query.limit(count); List<AbstractTask> found = query.select(task).fetch(); if (found != null) { return found.iterator(); } return new ArrayList<AbstractTask>().iterator(); } @Override public long size() { JPAQuery query = new JPAQuery(page.getEntityManager()); QAbstractTask task = QAbstractTask.abstractTask; QWork work = task.as(QWork.class); query.from(QAbstractTask.abstractTask).leftJoin(work.part.project); query.where(createPredicate()); return query.select(task).fetchCount(); } @Override public IModel<AbstractTask> model(AbstractTask object) { return new Model<>(object); } public void setFilter(WorkFilterDto filter) { this.filter = filter; } private Predicate createPredicate() { if (filter == null) { return null; } List<Predicate> list = createPredicates(filter); if (list.isEmpty()) { return null; } BooleanBuilder bb = new BooleanBuilder(); return bb.orAllOf(list.toArray(new Predicate[list.size()])); } public static List<Predicate> createPredicates(WorkFilterDto filter) { QAbstractTask task = QAbstractTask.abstractTask; if (filter == null) { return null; } List<Predicate> list = new ArrayList<>(); Predicate p = createListPredicate(filter.getRealizators(), task.realizator); if (p != null) { list.add(p); } if (!WorkType.ALL.equals(filter.getType())) { list.add(task.type.eq(filter.getType().getType())); } p = createProjectListPredicate(filter.getProjects()); if (p != null) { list.add(p); } if (filter.getFrom() != null) { list.add(task.date.goe(filter.getFrom())); } if (filter.getTo() != null) { list.add(task.date.loe(filter.getTo())); } return list; } private static Predicate createProjectListPredicate(List<CustomerProjectPartDto> list) { if (list == null || list.isEmpty()) { return null; } if (list.size() == 1) { return createPredicate(list.get(0)); } BooleanBuilder bb = new BooleanBuilder(); for (CustomerProjectPartDto dto : list) { bb.or(createPredicate(dto)); } return bb; } private static Predicate createPredicate(CustomerProjectPartDto dto) { BooleanBuilder bb = new BooleanBuilder(); QAbstractTask task = QAbstractTask.abstractTask; QLog log = task.as(QLog.class); bb.or(log.customer.id.eq(dto.getCustomerId())); QWork work = task.as(QWork.class); if (dto.getProjectId() != null) { bb.or(work.part.project.id.eq(dto.getProjectId())); } else if (dto.getCustomerId() != null) { bb.or(work.part.project.customer.id.eq(dto.getCustomerId())); } return bb; } private static <T> Predicate createListPredicate(List<T> list, EntityPathBase<T> base) { if (list == null || list.isEmpty()) { return null; } if (list.size() == 1) { return base.eq(list.get(0)); } BooleanExpression expr = base.eq(list.get(0)); for (int i = 1; i < list.size(); i++) { expr = expr.or(base.eq(list.get(i))); } return expr; } }
30.036842
92
0.63536
7fae54945eaf53ecf993f9694e9498c4693a5fee
4,499
package me.iwf.photopicker.widget; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.annotation.IntDef; import android.support.v7.widget.OrientationHelper; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.AttributeSet; import android.widget.FrameLayout; import android.widget.Toast; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.List; import me.iwf.photopicker.PhotoPickUtils; /** * Created by Administrator on 2016/8/15 0015. */ public class MultiPickResultView extends FrameLayout { @IntDef({ACTION_SELECT, ACTION_ONLY_SHOW}) //Tell the compiler not to store annotation data in the .class file @Retention(RetentionPolicy.SOURCE) //Declare the NavigationMode annotation public @interface MultiPicAction {} public static final int ACTION_SELECT = 1;//该组件用于图片选择 带有减号的 public static final int ACTION_ONLY_SHOW = 2;//该组件仅用于图片显示 private int action; private int maxCount; android.support.v7.widget.RecyclerView recyclerView; PhotoAdapter photoAdapter; ArrayList<String> selectedPhotos; public MultiPickResultView(Context context) { this(context,null,0); } public MultiPickResultView(Context context, AttributeSet attrs) { this(context, attrs,0); } public MultiPickResultView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context,attrs); initData(context,attrs); initEvent(context,attrs); } private void initEvent(Context context, AttributeSet attrs) { } private void initData(Context context, AttributeSet attrs) { } private void initView(Context context, AttributeSet attrs) { recyclerView = new android.support.v7.widget.RecyclerView(context,attrs); recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL)); this.addView(recyclerView); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public MultiPickResultView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { this(context, attrs, defStyleAttr); } public void init(Activity context,@MultiPicAction int action, ArrayList<String> photos){ this.action = action; if (action == MultiPickResultView.ACTION_ONLY_SHOW){//当只用作显示图片时,一行显示3张 recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, OrientationHelper.VERTICAL)); } selectedPhotos = new ArrayList<>(); this.action = action; if (photos != null && photos.size() >0){ selectedPhotos.addAll(photos); } photoAdapter = new PhotoAdapter(context, selectedPhotos); photoAdapter.setAction(action); recyclerView.setAdapter(photoAdapter); //recyclerView.setLayoutFrozen(true); } public void showPics(List<String> paths){ if (paths != null){ selectedPhotos.clear(); selectedPhotos.addAll(paths); photoAdapter.notifyDataSetChanged(); } } // 控件需要调用这个初始化好接口的实现类onActivityResult public void onActivityResult(int requestCode, int resultCode, Intent data){ if (action == ACTION_SELECT){ // 回调接口 让控件适配器 PhotoPickUtils.onActivityResult(requestCode, resultCode, data, new PhotoPickUtils.PickHandler() { @Override public void onPickSuccess(ArrayList<String> photos) { photoAdapter.refresh(photos); } @Override public void onPreviewBack(ArrayList<String> photos) { photoAdapter.refresh(photos); } @Override public void onPickFail(String error) { Toast.makeText(getContext(),error,Toast.LENGTH_LONG).show(); selectedPhotos.clear(); photoAdapter.notifyDataSetChanged(); } @Override public void onPickCancle() { //Toast.makeText(getContext(),"取消选择",Toast.LENGTH_LONG).show(); } }); } } public ArrayList<String> getPhotos() { return selectedPhotos; } }
28.11875
109
0.663036
81699e1a98ce0adb31409cd781d0f52a78ea0e07
2,187
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.netty.common.proxyprotocol; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.ProtocolDetectionState; import io.netty.handler.codec.haproxy.HAProxyMessageDecoder; /** * Decides if we need to decode a HAProxyMessage. If so, adds the decoder followed by the handler. * Else, removes itself from the pipeline. */ public final class ElbProxyProtocolChannelHandler extends ChannelInboundHandlerAdapter { public static final String NAME = ElbProxyProtocolChannelHandler.class.getSimpleName(); private final boolean withProxyProtocol; public ElbProxyProtocolChannelHandler(boolean withProxyProtocol) { this.withProxyProtocol = withProxyProtocol; } public void addProxyProtocol(ChannelPipeline pipeline) { pipeline.addLast(NAME, this); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (withProxyProtocol && isHAPMDetected(msg)) { ctx.pipeline().addAfter(NAME, null, new HAProxyMessageChannelHandler()) .replace(this, null, new HAProxyMessageDecoder()); } else { ctx.pipeline().remove(this); } super.channelRead(ctx, msg); } private boolean isHAPMDetected(Object msg) { return HAProxyMessageDecoder.detectProtocol((ByteBuf) msg).state() == ProtocolDetectionState.DETECTED; } }
37.706897
110
0.722451
7fbe4f3d93e18fc06bc5fc8c164163f134782e2e
1,766
/* * Copyright (c) 2008-2016 MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package xyz.morphia.converters; import org.junit.Assert; import org.junit.Test; import java.text.ParseException; import java.time.LocalTime; import java.util.Random; @SuppressWarnings("Since15") public class LocalTimeConverterTest extends ConverterTest<LocalTime, Long> { public LocalTimeConverterTest() { super(new LocalTimeConverter()); } @Test public void convertNull() { Assert.assertNull(getConverter().decode(null, null)); Assert.assertNull(getConverter().encode(null)); } @Test public void spanClock() { Random random = new Random(); for (int hour = 0; hour < 23; hour++) { for (int minute = 0; minute < 60; minute++) { for (int second = 0; second < 60; second++) { compare(LocalTime.class, LocalTime.of(hour, minute, second, random.nextInt(1000) * 1000000)); } } } } @Test public void testConversion() throws ParseException { final LocalTime time = LocalTime.of(12, 30, 45); compare(LocalTime.class, LocalTime.now()); assertFormat(time, 45045000L); } }
29.932203
113
0.656852
d8e6b1096f2c7bc1f283dd77a75a17601c2ed449
2,804
import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; import javafx.util.Duration; import java.io.IOException; public class MainController extends Stage { private Game game; private DisplayController displayController; private Scene scene; private Timeline timer; private int numHumans, numAIs; public MainController(int numHumans, int numAIs) { if(numHumans > -1 && numHumans < 3 && numAIs > -1 && numAIs < 15 && (numHumans + numAIs) > 0) { this.numHumans = numHumans; this.numAIs = numAIs; loadDisplayFXMLLoader(); loadScene(); newGame(); } else { Main.outputError("Error: invalid number of players entered. Maximum of: 2 humans and 14 AIs"); } } public void newGame() { System.out.println("<----- NEW GAME ----->"); game = new Game(10, scene, numHumans, numAIs); displayController.setUpDisplay(game); timer = new Timeline((new KeyFrame( Duration.millis(60), event -> timerTick()))); timer.setCycleCount(Animation.INDEFINITE); start(); } private void start() { game.start(); timer.play(); Timeline stopCountdown = new Timeline((new KeyFrame( Duration.millis(3000), event -> stop()))); stopCountdown.setCycleCount(1); game.runningProperty().addListener(v -> { if(!game.isRunning()) { stopCountdown.play(); } }); } public void stop() { timer.stop(); game = null; newGame(); } private void timerTick() { displayController.draw(); game.timerTick(); } private void loadDisplayFXMLLoader() { FXMLLoader displayFXMLLoader = new FXMLLoader(getClass().getResource("DisplayView.fxml")); try { scene = new Scene(displayFXMLLoader.load(), 400, 425); } catch (IOException e) { Main.outputError(e); } displayController = displayFXMLLoader.getController(); } private void loadScene() { this.setScene(scene); this.show(); // ensure the window closes correctly this.setOnCloseRequest(v -> { Platform.exit(); System.exit(0); }); this.setTitle("Snake!"); this.setResizable(false); // try to load application icon // this implementation makes the file handling platform-agnostic // so the icon should work on different platforms // (however, setting the icon Dock icon on Mac requires making additional calls) try { this.getIcons().add(new Image(this.getClass().getResourceAsStream("icon.png"))); //Icon made by freepik.com and flaticon.com // Flaticon is licensed by Creative Commons 3.0 BY } catch (Exception e) { System.out.println("Error: application icon not found"); Main.outputError(e); } } }
23.965812
97
0.689729
d8c81297ec79a00e37321dce7228043699e5c339
400
package RunProgram; import Applikation.Applikation; /** * MTG2BEM * * @author Barry Al-Jawari */ public class MTG2BEM { public static void main(String[] args) { String mode = "mtg2bem"; String in = RunProgram.FilePlace + RunProgram.Imagefile + ".mtg"; String ut = RunProgram.FilePlace + RunProgram.Imagefile + ".BEM"; Applikation.run(mode, in, ut); } }
21.052632
73
0.64
67ee97a1ecebf65343468ad55e8c5110cf603692
4,409
package com.nhl.dflib; import com.nhl.dflib.series.IntArraySeries; import com.nhl.dflib.unit.DataFrameAsserts; import org.junit.jupiter.api.Test; import static com.nhl.dflib.Exp.*; import static org.junit.jupiter.api.Assertions.assertThrows; public class DataFrame_SelectRowsTest { @Test public void testInts() { DataFrame df = DataFrame.newFrame("a", "b").foldByRow( 5, "x", 9, "y", 1, "z") .selectRows(0, 2); new DataFrameAsserts(df, "a", "b") .expectHeight(2) .expectRow(0, 5, "x") .expectRow(1, 1, "z"); } @Test public void testInts_out_of_range() { DataFrame df = DataFrame.newFrame("a", "b").foldByRow( 5, "x", 9, "y", 1, "z"); assertThrows(ArrayIndexOutOfBoundsException.class, () -> df.selectRows(0, 3).materialize()); } @Test public void testIntSeries() { DataFrame df = DataFrame.newFrame("a", "b").foldByRow( 5, "x", 9, "y", 1, "z") .selectRows(new IntArraySeries(0, 2)); new DataFrameAsserts(df, "a", "b") .expectHeight(2) .expectRow(0, 5, "x") .expectRow(1, 1, "z"); } @Test public void testReorder() { DataFrame df = DataFrame.newFrame("a", "b").foldByRow( 5, "x", 9, "y", 1, "z") .selectRows(2, 1); new DataFrameAsserts(df, "a", "b") .expectHeight(2) .expectRow(0, 1, "z") .expectRow(1, 9, "y"); } @Test public void testSelectRows_duplicate() { DataFrame df = DataFrame.newFrame("a", "b").foldByRow( 5, "x", 9, "y", 1, "z") .selectRows(2, 1, 1, 2); new DataFrameAsserts(df, "a", "b") .expectHeight(4) .expectRow(0, 1, "z") .expectRow(1, 9, "y") .expectRow(1, 9, "y") .expectRow(0, 1, "z"); } @Test public void testByColumn_Name() { DataFrame df = DataFrame.newFrame("a") .foldByRow(10, 20) .selectRows("a", (Integer v) -> v > 15); new DataFrameAsserts(df, "a") .expectHeight(1) .expectRow(0, 20); } @Test public void testSByColumn_Pos() { DataFrame df = DataFrame.newFrame("a") .foldByRow(10, 20) .selectRows(0, (Integer v) -> v > 15); new DataFrameAsserts(df, "a") .expectHeight(1) .expectRow(0, 20); } @Test public void testWithBooleanSeries() { DataFrame df = DataFrame.newFrame("a").foldByRow(10, 20, 30) .selectRows(BooleanSeries.forBooleans(true, false, true)); new DataFrameAsserts(df, "a") .expectHeight(2) .expectRow(0, 10) .expectRow(1, 30); } @Test public void testExp_Ge() { Condition c = $int("a").ge(20); DataFrame df = DataFrame.newFrame("a") .foldByRow(10, 20, 30, 40) .selectRows(c); new DataFrameAsserts(df, "a") .expectHeight(3) .expectRow(0, 20) .expectRow(1, 30) .expectRow(2, 40); } @Test public void testExp_EqOr() { Condition c = $col("b").eq($col("a")).or($bool("c")); DataFrame df = DataFrame.newFrame("a", "b", "c").foldByRow( "1", "1", false, "2", "2", true, "4", "5", false).selectRows(c); new DataFrameAsserts(df, "a", "b", "c") .expectHeight(2) .expectRow(0, "1", "1", false) .expectRow(1, "2", "2", true); } @Test public void testExp_Lt() { Condition c = $int("b").mul($int("c")).lt($double("a").div($int("d"))); DataFrame df = DataFrame.newFrame("a", "b", "c", "d").foldByRow( 1.01, -1, 0, 1, 60., 4, 8, 2).selectRows(c); new DataFrameAsserts(df, "a", "b", "c", "d") .expectHeight(1) .expectRow(0, 1.01, -1, 0, 1); } }
27.216049
100
0.457927
e1d79643890a95b036910ca87d54c88b78c1007f
2,958
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml; import java.io.IOException; import net.sourceforge.plantuml.security.SFile; import net.sourceforge.plantuml.security.SecurityUtils; public class FileSystem { private final static FileSystem singleton = new FileSystem(); private final ThreadLocal<SFile> currentDir = new ThreadLocal<SFile>(); private FileSystem() { reset(); } public static FileSystem getInstance() { return singleton; } public void setCurrentDir(SFile dir) { // if (dir == null) { // throw new IllegalArgumentException(); // } if (dir != null) { Log.info("Setting current dir: " + dir.getAbsolutePath()); } this.currentDir.set(dir); } public SFile getCurrentDir() { return this.currentDir.get(); } public SFile getFile(String nameOrPath) throws IOException { if (isAbsolute(nameOrPath)) { return new SFile(nameOrPath).getCanonicalFile(); } final SFile dir = currentDir.get(); SFile filecurrent = null; if (dir != null) { filecurrent = dir.getAbsoluteFile().file(nameOrPath); if (filecurrent.exists()) { return filecurrent.getCanonicalFile(); } } for (SFile d : SecurityUtils.getPath("plantuml.include.path")) { assert d.isDirectory(); final SFile file = d.file(nameOrPath); if (file.exists()) { return file.getCanonicalFile(); } } for (SFile d : SecurityUtils.getPath("java.class.path")) { assert d.isDirectory(); final SFile file = d.file(nameOrPath); if (file.exists()) { return file.getCanonicalFile(); } } if (dir == null) { assert filecurrent == null; return new SFile(nameOrPath).getCanonicalFile(); } assert filecurrent != null; return filecurrent; } private boolean isAbsolute(String nameOrPath) { final SFile f = new SFile(nameOrPath); return f.isAbsolute(); } public void reset() { setCurrentDir(new SFile(".")); } }
26.410714
76
0.659905
c6a66a86d0eda3e52d72b18e4368e5150a0eed4d
1,123
package ampcontrol.model.training.model.validation.listen; import org.nd4j.evaluation.classification.Evaluation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.function.Consumer; import java.util.function.Supplier; /** * Logs evaluation results * * @author Christian Skärby */ public class EvalLog implements Consumer<Evaluation> { private static final Logger log = LoggerFactory.getLogger(EvalLog.class); private final String modelName; private final Supplier<Double> bestAccuracy; /** * Constructor * @param modelName name of model for which evaluation is provided */ public EvalLog(String modelName, Supplier<Double> bestAccuracy) { this.modelName = modelName; this.bestAccuracy = bestAccuracy; } @Override public void accept(Evaluation eval) { final double newAccuracy = eval.accuracy(); log.info("Eval report for " + modelName); log.info(eval.stats()); //log.info("\n" + eval.confusionToString()); log.info("Accuracy = " + newAccuracy + " Best: " + bestAccuracy.get()); } }
28.794872
79
0.692787
ce760d63ac8d9dfdba2e3049efe25e0003ed1dff
2,038
package osgl.func; /*- * #%L * OSGL Core * %% * Copyright (C) 2017 OSGL (Open Source General Library) * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import osgl.exception.FastRuntimeException; /** * Used to break out from functions in a iterating loop. * * A `Break` can carry a payload. */ public final class Break extends FastRuntimeException { /** * A payload to be carried through to the external caller. */ private Object payload; /** * Construct a `Break` without payload. */ public Break() {} /** * Construct a `Break` with payload. * * The payload can be accessed through {@link #payload()} call * * @param payload * the payload */ public Break(Object payload) { this.payload = payload; } /** * Returns the payload of the `Break` instance. * * @return * the payload * @see #Break(Object) */ public Object payload() { return payload; } /** * Create an new `Break` instance. * @return * an new `Break` instance */ public static Break breakOut() { return new Break(); } /** * Create an new `Break` instance with payload specified. * * @param payload * the payload to be carried out through the `Break` * @return * A `Break` instance with payload */ public static Break breakOut(Object payload) { return new Break(payload); } }
23.697674
75
0.610402
d3ce915b3347fb67a0d895fbff4ae8a60f04397f
2,560
/* * Copyright 2010 the original author or authors. * Copyright 2010 SorcerSoft.org. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sorcer.core.provider.exerter; import net.jini.core.entry.Entry; import net.jini.lookup.entry.Name; import org.junit.Test; import sorcer.core.SorcerConstants; import sorcer.core.provider.exerter.cache.ProviderProxyCache; import sorcer.core.provider.exerter.cache.ProviderProxyCacheGuava; import sorcer.util.Sorcer; import static org.junit.Assert.*; public class ProviderCacheTest { @Test public void testGetJavaCacheUsingProperty() { Sorcer.getProperties().setProperty(SorcerConstants.S_PROVIDER_CACHE_NAME, ProviderProxyCache.class.getName()); ProviderCache providerCache = ProviderCache.get(); assertTrue(providerCache instanceof ProviderProxyCache); } @Test public void testGetDefaultCache() { Sorcer.getProperties().remove(SorcerConstants.S_PROVIDER_CACHE_NAME); assertNull(Sorcer.getProperties().getProperty(SorcerConstants.S_PROVIDER_CACHE_NAME)); ProviderCache providerCache = ProviderCache.get(); assertTrue(providerCache instanceof ProviderProxyCache); } @Test public void testGetGuavaCache() { Sorcer.getProperties().setProperty(SorcerConstants.S_PROVIDER_CACHE_NAME, ProviderProxyCacheGuava.class.getName()); ProviderCache providerCache = ProviderCache.get(); assertTrue(providerCache instanceof ProviderProxyCacheGuava); } @Test(expected = RuntimeException.class) public void testGetBogusCache() { Sorcer.getProperties().setProperty(SorcerConstants.S_PROVIDER_CACHE_NAME, "org.phony.Cache"); ProviderCache.get(); } @Test(expected = RuntimeException.class) public void testGetBogusCacheNotInstance() { Sorcer.getProperties().setProperty(SorcerConstants.S_PROVIDER_CACHE_NAME, Object.class.getName()); ProviderCache.get(); } }
38.208955
106
0.725391
25a30844a32ab26721c3d34869006f0defe57bc2
1,563
package org.xmlet.regexapi; import java.util.function.Consumer; public final class SingleLineMode<Z extends Element> implements CustomAttributeGroup<SingleLineMode<Z>, Z>, TextGroup<SingleLineMode<Z>, Z> { protected final Z parent; protected final ElementVisitor visitor; public SingleLineMode(ElementVisitor visitor) { this.visitor = visitor; this.parent = null; visitor.visitElementSingleLineMode(this); } public SingleLineMode(Z parent) { this.parent = parent; this.visitor = parent.getVisitor(); this.visitor.visitElementSingleLineMode(this); } protected SingleLineMode(Z parent, ElementVisitor visitor, boolean shouldVisit) { this.parent = parent; this.visitor = visitor; if (shouldVisit) { visitor.visitElementSingleLineMode(this); } } public Z __() { this.visitor.visitParentSingleLineMode(this); return this.parent; } public final SingleLineMode<Z> dynamic(Consumer<SingleLineMode<Z>> consumer) { this.visitor.visitOpenDynamic(); consumer.accept(this); this.visitor.visitCloseDynamic(); return this; } public final SingleLineMode<Z> of(Consumer<SingleLineMode<Z>> consumer) { consumer.accept(this); return this; } public Z getParent() { return this.parent; } public final ElementVisitor getVisitor() { return this.visitor; } public String getName() { return "singleLineMode"; } public final SingleLineMode<Z> self() { return this; } }
24.809524
141
0.678823
02d27e1dff406f67714d4f0562a1ce1e7a742a25
8,675
package org.jboss.windup.web.services.rest; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import java.util.Collection; import java.util.stream.Collectors; import javax.ws.rs.client.Entity; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput; import org.jboss.windup.web.services.AbstractTest; import org.jboss.windup.web.services.MigrationProjectAssertions; import org.jboss.windup.web.services.ServiceTestUtil; import org.jboss.windup.web.services.data.DataProvider; import org.jboss.windup.web.services.data.ServiceConstants; import org.jboss.windup.web.services.model.MigrationProject; import org.jboss.windup.web.services.model.RegisteredApplication; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="mailto:dklingenberg@gmail.com">David Klingenberg</a> * @author <a href="mailto:jesse.sightler@gmail.com">Jesse Sightler</a> */ @RunWith(Arquillian.class) public class MigrationProjectRegisteredApplicationsEndpointTest extends AbstractTest { @ArquillianResource private URL contextPath; private ResteasyClient client; private ResteasyWebTarget target; private MigrationProjectEndpoint migrationProjectEndpoint; private MigrationProjectRegisteredApplicationsEndpoint migrationProjectRegisteredApplicationsEndpoint; private RegisteredApplicationEndpoint registeredApplicationEndpoint; private DataProvider dataProvider; private MigrationProject dummyProject; @Before public void setUp() { this.client = ServiceTestUtil.getResteasyClient(); this.target = client.target(contextPath + ServiceConstants.REST_BASE); this.dataProvider = new DataProvider(target); this.migrationProjectRegisteredApplicationsEndpoint = target.proxy(MigrationProjectRegisteredApplicationsEndpoint.class); this.migrationProjectEndpoint = target.proxy(MigrationProjectEndpoint.class); this.registeredApplicationEndpoint = target.proxy(RegisteredApplicationEndpoint.class); this.dummyProject = this.dataProvider.getMigrationProject(); } @Test @RunAsClient public void testRegisterAppByPath() throws Exception { Collection<RegisteredApplication> existingApps = registeredApplicationEndpoint.getAllApplications(); Assert.assertEquals(0, filterOutDeleted(existingApps).size()); File tempFile1 = File.createTempFile(RegisteredApplicationEndpointTest.class.getSimpleName() + ".1", ".ear"); File tempFile2 = File.createTempFile(RegisteredApplicationEndpointTest.class.getSimpleName() + ".2", ".ear"); this.migrationProjectRegisteredApplicationsEndpoint.registerApplicationByPath(dummyProject.getId(), false, tempFile1.getAbsolutePath()); this.migrationProjectRegisteredApplicationsEndpoint.registerApplicationByPath(dummyProject.getId(), false, tempFile2.getAbsolutePath()); try { Collection<RegisteredApplication> apps = registeredApplicationEndpoint.getAllApplications(); apps = filterOutDeleted(apps); Assert.assertEquals(2, apps.size()); boolean foundPath1 = false; boolean foundPath2 = false; for (RegisteredApplication app : apps) { if (app.getInputPath().equals(tempFile1.getAbsolutePath())) foundPath1 = true; else if (app.getInputPath().equals(tempFile2.getAbsolutePath())) foundPath2 = true; else if (app.getFileSize() > 0) Assert.fail("Registered application file size is not set correctly!"); } Assert.assertTrue(foundPath1); Assert.assertTrue(foundPath2); MigrationProject updatedProject = this.migrationProjectEndpoint.getMigrationProject(dummyProject.getId()); MigrationProjectAssertions.assertLastModifiedIsUpdated(dummyProject, updatedProject); } finally { for (RegisteredApplication application : registeredApplicationEndpoint.getAllApplications()) { registeredApplicationEndpoint.deleteApplication(application.getId()); } } } @Test @RunAsClient public void testRegisterAppUpload() throws Exception { Collection<RegisteredApplication> existingApps = registeredApplicationEndpoint.getAllApplications(); Assert.assertEquals(0, filterOutDeleted(existingApps).size()); try (InputStream sampleIS = getClass().getResourceAsStream(DataProvider.TINY_SAMPLE_PATH)) { String fileName = "sample-tiny.war"; String registeredAppTargetUri = this.target.getUri() + MigrationProjectRegisteredApplicationsEndpoint.PROJECT_APPLICATIONS .replace("{projectId}", dummyProject.getId().toString()) + "/upload"; ResteasyWebTarget registeredAppTarget = this.client.target(registeredAppTargetUri); try { Entity entity = this.dataProvider.getMultipartFormDataEntity(sampleIS, fileName); Response response = registeredAppTarget.request().post(entity); response.bufferEntity(); String entityString = response.readEntity(String.class); RegisteredApplication application = response.readEntity(RegisteredApplication.class); response.close(); Collection<RegisteredApplication> apps = registeredApplicationEndpoint.getAllApplications(); apps = filterOutDeleted(apps); Assert.assertEquals(1, apps.size()); Assert.assertEquals(fileName, application.getTitle()); Assert.assertEquals(2692L, application.getFileSize()); ServiceTestUtil.assertFileExists(application.getInputPath()); ServiceTestUtil.assertFileContentsAreEqual(getClass().getResourceAsStream( DataProvider.TINY_SAMPLE_PATH), new FileInputStream(application.getInputPath())); MigrationProject updatedProject = this.migrationProjectEndpoint.getMigrationProject(dummyProject.getId()); MigrationProjectAssertions.assertLastModifiedIsUpdated(dummyProject, updatedProject); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException("Failed to post application due to: " + t.getMessage() + " exception: " + t.getClass().getName()); } finally { for (RegisteredApplication application : registeredApplicationEndpoint.getAllApplications()) { registeredApplicationEndpoint.deleteApplication(application.getId()); } } } } private Collection<RegisteredApplication> filterOutDeleted(Collection<RegisteredApplication> apps) { return apps.stream().filter(app -> !app.isDeleted()).collect(Collectors.toList()); } public void testRegisterAppWithoutFile() throws Exception { MultipartFormDataOutput uploadData = new MultipartFormDataOutput(); GenericEntity<MultipartFormDataOutput> genericEntity = new GenericEntity<MultipartFormDataOutput>(uploadData) { }; Entity entity = Entity.entity(genericEntity, MediaType.MULTIPART_FORM_DATA_TYPE); String registeredAppTargetUri = this.target.getUri() + MigrationProjectRegisteredApplicationsEndpoint.PROJECT_APPLICATIONS .replace("{projectId}", dummyProject.getId().toString()) + "/upload"; ResteasyWebTarget registeredAppTarget = this.client.target(registeredAppTargetUri); Response response = registeredAppTarget.request().post(entity); response.close(); Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatus()); MigrationProject updatedProject = this.migrationProjectEndpoint.getMigrationProject(dummyProject.getId()); MigrationProjectAssertions.assertLastModifiedIsNotUpdated(dummyProject, updatedProject); } }
45.182292
144
0.709395
53a548d651a6eb8f27ad4132d413aa38aefbad2e
878
package com.example.demo02.service.imp; import com.example.demo02.dao.IUser; import com.example.demo02.entity.User; import com.example.demo02.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceImp implements UserService { /*自动装载*/ @Autowired private IUser iUser; /*对方法进行重写*/ @Override public int insertUser(User user) { // System.out.println(user.getCreatetime()+""+user.getAppid()+""+user.getId()+""+user.getPasswd()+""+user.getUsername()); return iUser.insertUser(user); } @Override public int updateUser(User user) { return iUser.updateUser(user); } @Override public List<User> getUser(User user){ return iUser.getUser(user); } @Override public int deleteUser(User user) { return iUser.deleteUser(user); } }
23.105263
122
0.751708
95f81c06d7bd68f72cd86a83487f732f5e90f480
4,189
package org.springframework.data.tarantool.core.convert; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.Jsr310Converters; import org.springframework.data.convert.ReadingConverter; import org.springframework.data.convert.WritingConverter; import java.time.*; import java.time.temporal.ChronoField; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Tarantool date converters * * @author Tatiana Blinova */ public class TarantoolJsr310Converters { public static Collection<Converter<?, ?>> getConvertersToRegister() { List<Converter<?, ?>> converters = new ArrayList<>(); converters.add(NumberToLocalDateTimeConverter.INSTANCE); converters.add(LocalDateTimeToLongConverter.INSTANCE); converters.add(NumberToLocalDateConverter.INSTANCE); converters.add(LocalDateToLongConverter.INSTANCE); converters.add(NumberToLocalTimeConverter.INSTANCE); converters.add(LocalTimeToLongConverter.INSTANCE); converters.add(NumberToInstantConverter.INSTANCE); converters.add(InstantToLongConverter.INSTANCE); converters.add(Jsr310Converters.ZoneIdToStringConverter.INSTANCE); converters.add(Jsr310Converters.StringToZoneIdConverter.INSTANCE); converters.add(Jsr310Converters.DurationToStringConverter.INSTANCE); converters.add(Jsr310Converters.StringToDurationConverter.INSTANCE); converters.add(Jsr310Converters.PeriodToStringConverter.INSTANCE); converters.add(Jsr310Converters.StringToPeriodConverter.INSTANCE); converters.add(Jsr310Converters.StringToLocalDateConverter.INSTANCE); converters.add(Jsr310Converters.StringToLocalDateTimeConverter.INSTANCE); converters.add(Jsr310Converters.StringToInstantConverter.INSTANCE); return converters; } @ReadingConverter public enum NumberToLocalDateTimeConverter implements Converter<Number, LocalDateTime> { INSTANCE; @Override public LocalDateTime convert(Number source) { return LocalDateTime.ofInstant(Instant.ofEpochMilli(source.longValue()), ZoneId.systemDefault()); } } @WritingConverter public enum LocalDateTimeToLongConverter implements Converter<LocalDateTime, Long> { INSTANCE; @Override public Long convert(LocalDateTime source) { return source.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); } } @ReadingConverter public enum NumberToLocalDateConverter implements Converter<Number, LocalDate> { INSTANCE; @Override public LocalDate convert(Number source) { return LocalDate.ofInstant(Instant.ofEpochMilli(source.longValue()), ZoneId.systemDefault()); } } @WritingConverter public enum LocalDateToLongConverter implements Converter<LocalDate, Long> { INSTANCE; @Override public Long convert(LocalDate source) { return source.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli(); } } @ReadingConverter public enum NumberToLocalTimeConverter implements Converter<Number, LocalTime> { INSTANCE; @Override public LocalTime convert(Number source) { return LocalTime.ofNanoOfDay(source.longValue()); } } @WritingConverter public enum LocalTimeToLongConverter implements Converter<LocalTime, Long> { INSTANCE; @Override public Long convert(LocalTime source) { return source.getLong(ChronoField.NANO_OF_DAY); } } @ReadingConverter public enum NumberToInstantConverter implements Converter<Number, Instant> { INSTANCE; @Override public Instant convert(Number source) { return Instant.ofEpochMilli(source.longValue()); } } @WritingConverter public enum InstantToLongConverter implements Converter<Instant, Long> { INSTANCE; @Override public Long convert(Instant source) { return source.toEpochMilli(); } } }
31.977099
109
0.711387
f6c8db87b5fe8930765ad435233833f3dafc9b62
4,127
// Copyright 2020 Fraser McCallum and Braden Palmer // // 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 quinzical.impl.multiplayer; import com.google.inject.Inject; import com.google.inject.name.Named; import com.jfoenix.controls.JFXProgressBar; import com.jfoenix.controls.JFXTextField; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.Label; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import org.json.JSONException; import org.json.JSONObject; import quinzical.impl.constants.GameScene; import quinzical.interfaces.models.SceneHandler; import quinzical.interfaces.multiplayer.SocketModel; import quinzical.interfaces.multiplayer.XpClass; import quinzical.interfaces.multiplayer.XpClassFactory; import java.io.IOException; public class ProfileController extends AbstractAlertController { @Inject private SceneHandler sceneHandler; @Inject private SocketModel socketModel; @Inject @Named("socketUrl") private String socketUrl; @Inject private XpClassFactory xpClassFactory; @FXML private JFXTextField txtSearch; @FXML private Label lblUsername; @FXML private Label lblLevel; @FXML private Label lblCorrect; @FXML private JFXProgressBar barXp; @FXML private Label lblXp; @FXML final void btnCancel() { new Thread(() -> sceneHandler.setActiveScene(GameScene.MULTI_MENU)).start(); } @FXML final void btnSearch() { new Thread(() -> getPlayerInfo(txtSearch.getText().trim())).start(); } @Override protected final void onLoad() { getPlayerInfo(socketModel.getName()); } @Override protected final void usePassedData(final String passedInfo) { final String query; if (passedInfo == null) { query = socketModel.getName(); } else { query = passedInfo; } new Thread(() -> getPlayerInfo(query)).start(); } public final void getPlayerInfo(final String player) { final OkHttpClient client = new OkHttpClient(); final Request request = new Request.Builder() .url(socketUrl + "/player/" + player) .build(); try { final Response response = client.newCall(request).execute(); if (response.code() != 200) { createAlert("Player not found", "The player you are searching for does not appear to exist."); return; } final ResponseBody responseBody = response.body(); assert responseBody != null; final JSONObject object = new JSONObject(responseBody.string()); final String name = object.getString("name"); final int xp = object.getInt("xp"); final int correct = object.getInt("correct"); final int incorrect = object.getInt("incorrect"); final XpClass xpUtils = xpClassFactory.createXp(xp); final int xpThrough = xpUtils.xpThroughLevel(); final int outOf = xpUtils.xpDeltaBetweenLevels(); Platform.runLater(() -> { lblUsername.setText(name); lblCorrect.setText(correct + " / " + (correct + incorrect)); lblLevel.setText(xpUtils.getLevel() + ""); lblXp.setText(xpThrough + " / " + outOf); barXp.setProgress((double) xpThrough / outOf); }); } catch (final IOException | JSONException e) { e.printStackTrace(); } } }
32.242188
110
0.658105
1951bc1d08b314a1516f1d6ccf886ab27ce4bcbb
80
package com.sample.domain.service; public abstract class BaseService { }
13.333333
36
0.7375
072504d0a7458762626e55711057393e5c8138d4
2,564
package me.mervin.core.tree; import java.util.Map; import me.mervin.core.Attribute; /** * Link.java * * @author Mervin.Wong DateTime 2014年3月21日 下午6:29:40 * @version 0.4.0 */ public class Link { //private Number adjNodeId = 0;//邻接点的ID private Vertex parent = null;//源节点 private Vertex child = null;//邻接点 public float weight = 0;//边的权重 private Attribute attr = null; //初始化 public Link(){ super(); } public Link(Vertex parent, Vertex child){ this.parent = parent; this.child = child; } public Link(Vertex parent, Vertex child, int linkWeight){ this.parent = parent; this.child = child; this.weight = linkWeight; } // GET SET public void setParent(Vertex parent){ this.parent = parent; } public void setChild(Vertex child){ this.child = child; } public void setweight(float linkWeight){ this.weight = linkWeight; } public void setAtrr(String key, String value){ if(this.attr == null){ this.attr = new Attribute(); } this.attr.set(key, value); } public void setAtrr(Map<String, String> attrs){ if(this.attr == null){ this.attr = new Attribute(); } this.attr.set(attrs); } public Vertex getParent(){ return this.parent; } public Number getParentId(){ return this.parent.getId(); } public Vertex getChild(){ return this.child; } public Number getChildId(){ return this.child.getId(); } public float getWeight(){ return this.weight; } public String getAttr(String key){ if(this.attr != null){ return this.attr.get(key); }else{ return null; } } public boolean isEmpty(){ if(this.attr != null){ return true; }else{ return false; } } public boolean containsAttrKey(String key){ if(this.attr != null){ return this.attr.containsKey(key); }else{ return false; } } public boolean containsAttrValue(String value){ if(this.attr != null){ return this.attr.containsValue(value); }else{ return false; } } /** * @Override */ public String toString(){ return this.parent.getId()+"=="+this.child.getId()+"##"+this.weight; } /** * @Override */ public int hashCode(){ return this.child.hashCode(); } /** * @Override */ public boolean equals(Object obj){ if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Link other = (Link) obj; if(!this.parent.equals(other.parent) && !this.child.equals(other.child)) return false; return true; } }
19.278195
80
0.629875
da9c036c4d735131b84d9fd76457d93c92501f81
6,857
package com.example.tempus.ui.friends; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.applandeo.Tempus.R; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Set; public class EditFriendInfoActivity extends AppCompatActivity { // friendlist.txt 파일 경로, AVD와 실제 스마트폰 모두 동일한 경로 사용 final static String FilePath= "/data/data/com.applandeo.materialcalendarsampleapp/files/friendList.txt"; Button finButton; EditText phoneNumberEditText, nameEditText, emailEditText, groupEditText, memoEditText; Integer n; Intent EFIAIntent; String user_EMAIL; String host_ip; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_friend_info); EFIAIntent = getIntent(); user_EMAIL = EFIAIntent.getStringExtra("EMAIL"); host_ip = EFIAIntent.getStringExtra("host_ip"); // 전화번호 기입 phoneNumberEditText = findViewById(R.id.phoneNumberEditText); // 지인의 이름 기입 nameEditText = findViewById(R.id.nameEditText); // 지인의 이메일 기입 emailEditText = findViewById(R.id.emailEditText); // 지인의 그룹 기입 groupEditText = findViewById(R.id.groupEditText); // 기타사항을 메모로 기입 memoEditText = findViewById(R.id.memoEditText); // 수정할 지인의 정보들을 EditText에 SetText SetText(); finButton = findViewById(R.id.finButton); finButton.setOnClickListener(v -> { // 입력받은 지인 정보를 String형으로 저장 String phoneTxt = phoneNumberEditText.getText().toString().trim(); String nameTxt = nameEditText.getText().toString().trim(); String emailTxt = emailEditText.getText().toString().trim(); String groupTxt = groupEditText.getText().toString().trim(); String memoTxt = memoEditText.getText().toString(); // 지인 정보를 하나의 변수에 저장 String friendInfoTxt = phoneTxt + "|" + nameTxt + "|" + emailTxt + "|" + groupTxt + "|" + memoTxt + "|"; /* ReadFile로 읽어온 정보 중 일부를 빼고 그 부분에 수정된 값을 집어넣고 그대로 덮어쓰기? for루프로 돌다가 n번째 줄에 이르면 그걸 바꾸는 방식 */ // friendlist.txt에 원래 들어있던 텍스트를 전부 가져와서 frBuffer에 담음 StringBuffer frBuffer = new StringBuffer(); Integer countN = 0; try{ InputStream is = new FileInputStream(FilePath); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = ""; while ((line = reader.readLine()) != null) { // 수정할 지인이면 변경된 값을, 수정할 지인이 아니면 원래의 값을 frBuffer에 담는다. if(countN == n){ frBuffer.append(friendInfoTxt); } else{ frBuffer.append(line+"\n"); } countN++; } reader.close(); is.close(); } catch (Exception e){ StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String exceptionAsStrting = sw.toString(); Log.e("FilereadEFI2", exceptionAsStrting); e.printStackTrace(); Toast.makeText(this.getApplicationContext(), "파일을 읽는데 실패했습니다.", Toast.LENGTH_SHORT).show(); } // 아직 파일에 저장 안함 try{ BufferedWriter bw = new BufferedWriter(new FileWriter(FilePath, false)); bw.write(frBuffer.toString()); Log.i("frBuffer",frBuffer.toString()); bw.close(); Toast.makeText(this,"수정 완료", Toast.LENGTH_SHORT).show(); }catch (Exception e){ e.printStackTrace(); Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); } // 지인 정보 화면으로 다시 이동 Intent intent = new Intent(EditFriendInfoActivity.this, ConfirmFriendInfoActivity.class); intent.putExtra("지인 번호", n); intent.putExtra("EMAIL", user_EMAIL); intent.putExtra("host_ip",host_ip); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 상위 스택 액티비티 모두 제거 EditFriendInfoActivity.this.finish(); startActivity(intent); }); } // 파일에서 텍스트를 읽어 옴 public String ReadFile (String path){ StringBuffer strBuffer = new StringBuffer(); try { InputStream is = new FileInputStream(path); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = ""; while ((line = reader.readLine()) != null) { strBuffer.append(line+"\n"); } reader.close(); is.close(); } catch(Exception e){ StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String exceptionAsStrting = sw.toString(); Log.e("FilereadEFI", exceptionAsStrting); e.printStackTrace(); Toast.makeText(this.getApplicationContext(), "파일을 읽는데 실패했습니다.", Toast.LENGTH_SHORT).show(); return ""; } return strBuffer.toString(); } public void SetText (){ // 파일에서 지인 정보 가져옴 String read = ReadFile(FilePath); // '-'를 기준으로 지인 정보 분류 String[] readArr = read.split("\\|"); if (readArr != null) { int nCnt = readArr.length; // readArr[0+5n]: 전화번호, readArr[1+5n]: 등록명, readArr[2+5n]: 이메일, readArr[3+5n]: 그룹명, readArr[4+5n]: 메모 for (int i=0; i<nCnt; ++i) { Log.i("ARRTAG", "arr[" + i + "] = " + readArr[i]); } // intent하면서 전달받은 값을 가져와서 지인 번호로 사용 Intent friendIntent = getIntent(); n = friendIntent.getIntExtra("지인 번호", -1); Log.i("friendNum", "전달된 지인 번호 : " + n); // TextView에 setText phoneNumberEditText.setText(readArr[0+5*n]); nameEditText.setText(readArr[1+5*n]); emailEditText.setText(readArr[2+5*n]); groupEditText.setText(readArr[3+5*n]); memoEditText.setText(readArr[4+5*n]); } else{ Toast.makeText(this.getApplicationContext(), "추가된 지인이 없습니다.", Toast.LENGTH_SHORT).show(); } } }
34.984694
116
0.571095
c287ae8626af6f955a4ea814fd37ce5e7a922b78
174
package util.exception.runtime; public class IllegalFirstParamException extends RuntimeException{ public IllegalFirstParamException(String message){ super(message); } }
21.75
65
0.827586
35857a63f0f80e7eb19ffc73d4a50b4ed10e3bc8
2,730
package kr.co.popone.fitts.model.post; import kotlin.jvm.internal.Intrinsics; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class PostCoverImage { private int coverImageId; @NotNull private String coverImagePath; @NotNull public static /* synthetic */ PostCoverImage copy$default(PostCoverImage postCoverImage, int i, String str, int i2, Object obj) { if ((i2 & 1) != 0) { i = postCoverImage.coverImageId; } if ((i2 & 2) != 0) { str = postCoverImage.coverImagePath; } return postCoverImage.copy(i, str); } public final int component1() { return this.coverImageId; } @NotNull public final String component2() { return this.coverImagePath; } @NotNull public final PostCoverImage copy(int i, @NotNull String str) { Intrinsics.checkParameterIsNotNull(str, "coverImagePath"); return new PostCoverImage(i, str); } public boolean equals(@Nullable Object obj) { if (this != obj) { if (obj instanceof PostCoverImage) { PostCoverImage postCoverImage = (PostCoverImage) obj; if (!(this.coverImageId == postCoverImage.coverImageId) || !Intrinsics.areEqual((Object) this.coverImagePath, (Object) postCoverImage.coverImagePath)) { return false; } } return false; } return true; } public int hashCode() { int i = this.coverImageId * 31; String str = this.coverImagePath; return i + (str != null ? str.hashCode() : 0); } @NotNull public String toString() { StringBuilder sb = new StringBuilder(); sb.append("PostCoverImage(coverImageId="); sb.append(this.coverImageId); sb.append(", coverImagePath="); sb.append(this.coverImagePath); sb.append(")"); return sb.toString(); } public PostCoverImage(int i, @NotNull String str) { Intrinsics.checkParameterIsNotNull(str, "coverImagePath"); this.coverImageId = i; this.coverImagePath = str; } public final int getCoverImageId() { return this.coverImageId; } public final void setCoverImageId(int i) { this.coverImageId = i; } @NotNull public final String getCoverImagePath() { return this.coverImagePath; } public final void setCoverImagePath(@NotNull String str) { Intrinsics.checkParameterIsNotNull(str, "<set-?>"); this.coverImagePath = str; } }
29.673913
169
0.593407
d1000afd555c57d85c38884f5890bce1ce5d12ef
899
package edu.prahlad.dp.sdp.flyweight; import java.time.Duration; //Unshared concrete flyweight. public class UserBannedErrorMessage implements ErrorMessage { //All state is defined here private String caseId; private String remarks; private Duration banDuration; private String msg; public UserBannedErrorMessage(String caseId) { //Load case info from DB. this.caseId = caseId; remarks = "You violated terms of use."; banDuration = Duration.ofDays(2); msg = "You are BANNED. Sorry. \nMore information:\n"; msg += caseId + "\n"; msg += remarks + "\n"; msg += "Banned For:" + banDuration.toHours() + " Hours"; } //We ignore the extrinsic state argument @Override public String getText(String code) { return msg; } public String getCaseNo() { return caseId; } }
24.297297
64
0.631813
1e5701da44c1f8b749e26d4015c210072a8096d8
2,042
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.testutil; import com.google.devtools.build.lib.util.OS; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation class which we use to attach a little meta data to test * classes. For now, we use this to attach a {@link Suite}. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface TestSpec { /** * The size of the specified test, in terms of its resource consumption and * execution time. */ Suite size() default Suite.SMALL_TESTS; /** * The name of the suite to which this test belongs. Useful for creating * test suites organised by function. */ String suite() default ""; /** * True, if the test will is not dependable because it has a chance to fail regardless of the * code's correctness. If this is the case, the test should be fixed as soon as possible. */ boolean flaky() default false; /** * True, if the test cannot run in a remote execution environment and has to run on the local * machine. */ boolean localOnly() default false; /** * An array of operating systems that the test can run under. If not specified, the test can * run under all operating systems. */ OS[] supportedOs() default {}; }
32.412698
95
0.726249
4c06231f79abfed668251f22040b8af319d74f3d
2,225
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.betwixt; /** <p><code>AttributeDescriptor</code> describes the XML attributes * to be created for a bean instance.</p> * * @author <a href="mailto:jstrachan@apache.org">James Strachan</a> * @version $Revision: 438373 $ */ public class AttributeDescriptor extends NodeDescriptor { /** Base constructor */ public AttributeDescriptor() { } /** * Creates a AttributeDescriptor with no namespace URI or prefix * * @param localName the local name for the attribute, excluding any namespace prefix */ public AttributeDescriptor(String localName) { super( localName ); } /** * Creates a AttributeDescriptor with namespace URI and qualified name * * @param localName the local name for the attribute, excluding any namespace prefix * @param qualifiedName the fully quanified name, including the namespace prefix * @param uri the namespace for the attribute - or "" for no namespace */ public AttributeDescriptor(String localName, String qualifiedName, String uri) { super(localName, qualifiedName, uri); } /** * Return something useful for logging * * @return something useful for logging */ public String toString() { return "AttributeDescriptor[qname=" + getQualifiedName() + ",class=" + getPropertyType() + "]"; } }
35.887097
88
0.693933
989a45f187a0cb9c1996b0abf29579bb6571cea2
2,806
// Copyright 2020 Goldman Sachs // // 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.finos.engine.shared.javaCompiler.test; import com.fasterxml.jackson.databind.ObjectMapper; import org.eclipse.collections.api.map.MutableMap; import org.eclipse.collections.impl.factory.Lists; import org.finos.engine.shared.javaCompiler.EngineJavaCompiler; import org.finos.engine.shared.javaCompiler.StringJavaSource; import org.junit.Assert; import org.junit.Test; import java.lang.reflect.InvocationTargetException; public class TestJavaCompiler { private final String code = "package engine.generated;" + "public class Example" + "{" + " public static String execute()\n" + " {\n" + " return \"ok\";" + " }\n" + "}"; @Test public void testSourceCompiler() throws Exception { EngineJavaCompiler c = new EngineJavaCompiler(); c.compile(Lists.mutable.with(StringJavaSource.newStringJavaSource("engine.generated", "Example", code))); Assert.assertEquals("ok", execute(c)); } @Test public void testSaveAndLoadCompiler() throws Exception { EngineJavaCompiler c = new EngineJavaCompiler(); c.compile(Lists.mutable.with(StringJavaSource.newStringJavaSource("engine.generated", "Example", code))); MutableMap<String, String> save = c.save(); EngineJavaCompiler other = new EngineJavaCompiler(); other.load(save); Assert.assertEquals("ok", execute(other)); } @Test public void testSaveJSONSerialization() throws Exception { EngineJavaCompiler c = new EngineJavaCompiler(); c.compile(Lists.mutable.with(StringJavaSource.newStringJavaSource("engine.generated", "Example", code))); MutableMap<String, String> save = c.save(); Assert.assertTrue(new ObjectMapper().writeValueAsString(save).startsWith("{\"engine.generated.Example\":\"")); } private String execute(EngineJavaCompiler c) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { Class<?> cl = c.getClassLoader().loadClass("engine.generated.Example"); return (String) cl.getMethod("execute").invoke(null); } }
38.438356
152
0.696365
d6053de724eb2eaf4d72b460459999b38e0d7469
2,416
package au.gov.amsa.ais; import java.io.File; import java.io.IOException; import java.util.List; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import rx.Observable; import au.gov.amsa.ais.message.AisShipStaticA; import au.gov.amsa.ais.rx.Streams; import au.gov.amsa.util.nmea.NmeaMessage; @State(Scope.Benchmark) public class BenchmarksAis { private static final String shipStaticA = "\\s:rEV02,c:1334337326*5A\\!ABVDM,1,1,0,2,57PBtv01sb5IH`PR221LE986222222222222220l28?554000:kQEhhDm31H20DPSmD`880,2*40"; private static final String aisPositionA = "\\s:rEV02,c:1334337326*5A\\!AIVDM,1,1,,B,18JSad001i5gcaArTICimQTT068t,0*4A"; private static final String aisPositionB = "\\s:MSQ - Mt Cootha,c:1426803365*73\\!AIVDM,1,1,,A,B7P?n900Irg8IHL4RblF?wRToP06,0*1B"; private static final List<String> nmeaLines = Streams .nmeaFromGzip(new File("src/test/resources/ais.txt.gz")).toList() .toBlocking().single(); @Benchmark public void parseShipStaticNmeaMessage() { AisNmeaMessage n = new AisNmeaMessage(shipStaticA); n.getMessage(); } @Benchmark public void parseShipStaticNmeaMessageAndExtractBitsOfInterest() { AisNmeaMessage n = new AisNmeaMessage(shipStaticA); AisShipStaticA m = (AisShipStaticA) n.getMessage(); m.getName(); m.getShipType(); m.getImo(); m.getLengthMetres(); m.getWidthMetres(); m.getCallsign(); m.getMmsi(); } @Benchmark public void parseAisPositionANmeaMessage() { AisNmeaMessage n = new AisNmeaMessage(aisPositionA); n.getMessage(); } // @Benchmark // public void parseAisPositionANmeaMessageUsingDmaLibrary() throws // SentenceException, // AisMessageException, SixbitException { // Vdm vdm = new Vdm(); // vdm.parse(aisPositionA); // AisMessage3.getInstance(vdm); // } @Benchmark public void parseAisPositionBNmeaMessage() { AisNmeaMessage n = new AisNmeaMessage(aisPositionB); n.getMessage(); } @Benchmark public void parseMany() throws IOException { // process 44K lines Observable.from(nmeaLines).map(Streams.LINE_TO_NMEA_MESSAGE) .compose(Streams.<NmeaMessage> valueIfPresent()).subscribe(); } public static void main(String[] args) { System.setProperty("a", ""); while (true) { AisNmeaMessage n = new AisNmeaMessage(aisPositionA); n.getMessage(); n = new AisNmeaMessage(shipStaticA); n.getMessage(); } } }
28.761905
164
0.745861
faf9f3c43a5e569998eef7c5bbe4422d96160f4b
1,213
public class O16MyPower { public static double myPow(double x, int n) { if (n == 0) { return 1; } if (n == 1) { return x; } if (n == -1) { return 1 / x; } double res = myPow(x, n / 2); double res2 = res * res; if ((n & 1) == 1) { if (n > 0) { return res2 * x; } else { return res2 / x; } } else { return res2; } } public static double myPow2(double x, int n) { if (x == 0) { return 0; } if (n == 0) { return 1; } long b = n; if (n < 0) { b = -b; x = 1 / x; } return pow(x, b); } public static double pow(double x, long n) { if (n == 1) { return x; } double res = pow(x, n / 2); double res2 = res * res; if ((n & 1) == 1) { return res2 * x; } else { return res2; } } public static void main(String[] args) { System.out.println(myPow2(1.00000,-2147483648)); } }
20.559322
56
0.35202
bac337064205c4c322d00db5c37b710d560673c3
521
/*When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return true if the party with the given values is successful, or false otherwise.*/ public boolean cigarParty(int cigars, boolean isWeekend) { if (isWeekend) { return (40 <= cigars); } else { return (40 <= cigars) && (cigars <=60); } }
40.076923
80
0.68906