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 |
|---|---|---|---|---|---|
37408479273b6ea752ae0ff90e20ea0e2fdfda54 | 1,462 | import tencent.ai.texsmart.*;
public class ChsNluExample2 {
public static void main(String[] args) {
String userDir = System.getProperty("user.dir");
String dataDir = args.length >= 1 ? args[0] : userDir + "/../../data/nlu/kb/";
System.out.println("Creating and initializing the NLU engine...");
NluEngine engine = new NluEngine();
int workerCount = 4;
boolean ret = engine.init(dataDir, workerCount);
if(!ret) {
System.out.println("Failed to initialize the engine");
return;
}
String options = "{\"ner\":{\"enable\":true,\"fine_grained\":false}}";
System.out.printf("Options: %s\n", options);
System.out.println("=== 解析一个中文句子 ===");
String text = "上个月30号,南昌王先生在自己家里边看流浪地球边吃煲仔饭";
NluOutput output = engine.parseText(text, options);
System.out.printf("Input text: %s\n", text);
System.out.printf("Output norm text: %s\n", output.normText());
System.out.println("细粒度分词:");
for(NluOutput.Term word : output.words()) {
System.out.printf("\t%s\t(%d,%d)\t%s\n", word.str, word.offset, word.len, word.tag);
}
System.out.println("粗粒度分词:");
for(NluOutput.Term phrase : output.phrases()) {
System.out.printf("\t%s\t(%d,%d)\t%s\n", phrase.str, phrase.offset, phrase.len, phrase.tag);
}
System.out.println("命名实体识别(NER):");
for(NluOutput.Entity ent : output.entities()) {
System.out.printf("\t%s\t(%d,%d)\t%s\t%s\n", ent.str, ent.offset, ent.len, ent.type.name, ent.meaning);
}
}
}
| 34 | 106 | 0.647743 |
b3ff2a80a2cf180dcc1ca4c74c9886b844716be8 | 1,297 | package com.ovit.nswy.member.common;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HttpServletResponseFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse rsp = (HttpServletResponse) response;
rsp.setHeader("Access-Control-Allow-Origin", getAddress());
// response.setHeader("Access-Control-Allow-Headers",
// "X-Requested-With,token");
// 加入支持自定义的header 加入元素 token 前端就可以发送自定义token过来
rsp.setHeader("Access-Control-Allow-Headers", "Content-Type,token,X-Requested-With");
rsp.setHeader("Access-Control-Allow-Credentials", "true");
rsp.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
rsp.setHeader("X-Powered-By", " 3.2.1");
rsp.setHeader("Content-Type", "application/json;charset=utf-8");
chain.doFilter(request, response);
}
private String address;
private String getAddress() {
return address;
}
private void setAddress(String address) {
this.address = address;
}
@Override
public void init(FilterConfig arg) throws ServletException {
setAddress(arg.getInitParameter("address"));
}
} | 30.162791 | 90 | 0.756361 |
9d7742566e48e569ab5be2fe24fd723132cd0fd9 | 3,225 | /**
* 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 net.cuprak.graalvm;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import java.io.IOException;
import java.net.URL;
/**
* Wraps the GraalVM classes used to invoke
*/
@Stateless
public class PolygotHelloWorld {
private Context context;
private Value jsHelloWorld;
private Value rHelloWorld;
private Value pHelloWorld;
private Value rubyHelloWorld;
private Value cHelloWorld;
@PostConstruct
public void init() {
try {
URL jsScriptUrl = PolygotHelloWorld.class.getResource("/net/cuprak/graalvm/scripts/HelloWorld.js");
URL rScriptUrl = PolygotHelloWorld.class.getResource("/net/cuprak/graalvm/scripts/HelloWorld.R");
URL pScriptUrl = PolygotHelloWorld.class.getResource("/net/cuprak/graalvm/scripts/HelloWorld.py");
URL rbScriptUrl = PolygotHelloWorld.class.getResource("/net/cuprak/graalvm/scripts/HelloWorld.rb");
URL cScriptUrl = PolygotHelloWorld.class.getResource("/net/cuprak/graalvm/scripts/hello.bc");
context = Context.newBuilder().allowAllAccess(true).build();
context.eval(Source.newBuilder("js", jsScriptUrl).build());
context.eval(Source.newBuilder("R", rScriptUrl).build());
context.eval(Source.newBuilder("python", pScriptUrl).build());
jsHelloWorld = context.eval("js","helloWorld");
rHelloWorld = context.eval("R","helloWorld");
pHelloWorld = context.eval("python","helloWorld");
rubyHelloWorld = context.eval(Source.newBuilder("ruby",rbScriptUrl).build());
cHelloWorld = context.eval(Source.newBuilder("llvm",cScriptUrl).build());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String getJavaScriptMsg(String name) {
return jsHelloWorld.execute(name).asString();
}
public String getRMsg(String name) {
return rHelloWorld.execute(name).getArrayElement(0).asString();
}
public String getPythonMsg(String name) {
return pHelloWorld.execute(name).asString();
}
public String getRubyMsg(String name) {
return rubyHelloWorld.execute(name).asString();
}
public String getCMsg(String name) {
Object obj = cHelloWorld.getMember("__sulong_byte_array_to_native").execute(name.getBytes());
Value fn = cHelloWorld.getMember("helloWorld");
Value v = fn.execute(obj);
System.out.println("Return: " + v.asString());
return v.asString();
}
}
| 37.941176 | 111 | 0.688372 |
9e1d8860f9b97a6c771791d11bdcfba5292a016e | 1,817 | /*
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
* Copyright 2018 TechMahindra
* ================================================================================
* Modifications Copyright (C) 2018 Nokia
* ================================================================================
* 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.
* ============LICENSE_END=========================================================
*/
package org.onap.appc.licmgr.objects;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class TestLicenseModel {
private LicenseModel licenseModel;
@Before
public void setUp() {
licenseModel = new LicenseModel("EntitlementPoolUuid", "LicenseKeyGroupUuid");
}
@Test
public void testGetEntitlementPoolUuid() {
Assert.assertNotNull(licenseModel.getEntitlementPoolUuid());
Assert.assertEquals(licenseModel.getEntitlementPoolUuid(), "EntitlementPoolUuid");
}
@Test
public void testGetLicenseKeyGroupUuid() {
Assert.assertNotNull(licenseModel.getLicenseKeyGroupUuid());
Assert.assertEquals(licenseModel.getLicenseKeyGroupUuid(), "LicenseKeyGroupUuid");
}
}
| 37.081633 | 90 | 0.586681 |
263b05a7a8e8a0e33fbb445cb5a50a3c6931f41d | 982 | package com.moon.ensuredemo.bank1.message;
import com.alibaba.fastjson.JSONObject;
import com.moon.ensuredemo.bank1.model.AccountChangeEvent;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* 发送转账消息
*/
@Component
public class BankMessageProducer {
@Resource
private RocketMQTemplate rocketMQTemplate;
public void sendAccountChangeEvent(AccountChangeEvent accountChangeEvent) {
// 构造消息
JSONObject jsonObject = new JSONObject();
jsonObject.put("accountChange", accountChangeEvent);
// 转成 json 字符串
Message<String> msg = MessageBuilder.withPayload(jsonObject.toJSONString()).build();
// 发送消息
rocketMQTemplate.sendMessageInTransaction("producer_ensure_transfer", "topic_ensure_transfer", msg, null);
}
}
| 30.6875 | 114 | 0.763747 |
99844a0e6b75f6ece58f67f0560d07e8b2f89ca4 | 357 | package games.rednblack.hyperrunner.component;
import games.rednblack.editor.renderer.components.BaseComponent;
public class PlayerComponent implements BaseComponent {
public int touchedPlatforms = 0;
public int diamondsCollected = 0;
@Override
public void reset() {
touchedPlatforms = 0;
diamondsCollected = 0;
}
}
| 21 | 64 | 0.722689 |
9658d7766ba753187251c0b46be6cf69dfaec902 | 3,334 | package com.cameronwebb.webbhouse;
import java.util.List;
import java.util.Map;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.cameronwebb.webbhouse.dummy.DummyContent;
import com.philips.lighting.hue.listener.PHLightListener;
import com.philips.lighting.hue.sdk.PHHueSDK;
import com.philips.lighting.model.PHBridge;
import com.philips.lighting.model.PHBridgeResource;
import com.philips.lighting.model.PHHueError;
import com.philips.lighting.model.PHLight;
import com.philips.lighting.model.PHGroup;
import com.philips.lighting.model.PHLightState;
public class MainActivity extends AppCompatActivity implements LightFragment.OnListFragmentInteractionListener {
private PHHueSDK phHueSDK;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phHueSDK = PHHueSDK.create();
Button button = (Button) findViewById(R.id.connect_button);
if (phHueSDK.getSelectedBridge() == null) {
button.setText(R.string.btn_find_bridge);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
lightHandler();
}
});
}
else {
button.setVisibility(View.GONE);
lightHandler();
}
}
public void lightHandler() {
PHBridge bridge = phHueSDK.getSelectedBridge();
if (bridge == null) {
Intent intent = new Intent(getApplicationContext(), PHHomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
intent.addFlags(0x8000); // equal to Intent.FLAG_ACTIVITY_CLEAR_TASK which is only available from API level 11
startActivity(intent);
}
else {
List<PHGroup> groups = bridge.getResourceCache().getAllGroups();
LightFragment fragment = (LightFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
fragment.updateData(groups);
}
}
@Override
protected void onDestroy() {
PHBridge bridge = phHueSDK.getSelectedBridge();
if (bridge != null) {
phHueSDK.disableHeartbeat(bridge);
}
super.onDestroy();
}
@Override
public void onListFragmentInteraction(PHGroup group) {
PHBridge bridge = phHueSDK.getSelectedBridge();
List<String> lights = group.getLightIdentifiers();
Map<String, PHLight> allLights = bridge.getResourceCache().getLights();
if (lights != null) {
for (String lightId : lights) {
PHLight light = allLights.get(lightId);
if (light != null) {
Boolean isOn = light.getLastKnownLightState().isOn();
light.getLastKnownLightState().setOn(!isOn);
bridge.updateLightState(light, light.getLastKnownLightState());
}
}
}
}
}
| 31.45283 | 126 | 0.64967 |
dc1893d8bd9b82e3f8505c4a89024aafcdc82106 | 4,300 | /*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.api.internal.tasks;
import org.gradle.api.internal.TaskInternal;
import org.gradle.api.internal.file.FileResolver;
import org.gradle.api.internal.file.FileTreeInternal;
import javax.annotation.Nullable;
public class DefaultPropertySpecFactory implements PropertySpecFactory {
private final TaskInternal task;
private final FileResolver resolver;
public DefaultPropertySpecFactory(TaskInternal task, FileResolver resolver) {
this.task = task;
this.resolver = resolver;
}
@Override
public DeclaredTaskInputFileProperty createInputFileSpec(ValidatingValue paths) {
return createInputFilesSpec(paths, ValidationActions.INPUT_FILE_VALIDATOR);
}
@Override
public DeclaredTaskInputFileProperty createInputFilesSpec(ValidatingValue paths) {
return createInputFilesSpec(paths, ValidationActions.NO_OP);
}
@Override
public DeclaredTaskInputFileProperty createInputDirSpec(ValidatingValue dirPath) {
FileTreeInternal fileTree = resolver.resolveFilesAsTree(dirPath);
return createInputFilesSpec(new FileTreeValue(dirPath, fileTree), ValidationActions.INPUT_DIRECTORY_VALIDATOR);
}
private DeclaredTaskInputFileProperty createInputFilesSpec(ValidatingValue paths, ValidationAction validationAction) {
return new DefaultTaskInputFilePropertySpec(task.getName(), resolver, paths, validationAction);
}
@Override
public DefaultTaskInputPropertySpec createInputPropertySpec(String name, ValidatingValue value) {
return new DefaultTaskInputPropertySpec(name, value);
}
@Override
public DeclaredTaskOutputFileProperty createOutputFileSpec(ValidatingValue path) {
return createOutputFilePropertySpec(path, OutputType.FILE, ValidationActions.OUTPUT_FILE_VALIDATOR);
}
@Override
public DeclaredTaskOutputFileProperty createOutputDirSpec(ValidatingValue path) {
return createOutputFilePropertySpec(path, OutputType.DIRECTORY, ValidationActions.OUTPUT_DIRECTORY_VALIDATOR);
}
@Override
public DeclaredTaskOutputFileProperty createOutputFilesSpec(ValidatingValue paths) {
return new CompositeTaskOutputPropertySpec(task.getName(), resolver, OutputType.FILE, paths, ValidationActions.OUTPUT_FILES_VALIDATOR);
}
@Override
public DeclaredTaskOutputFileProperty createOutputDirsSpec(ValidatingValue paths) {
return new CompositeTaskOutputPropertySpec(task.getName(), resolver, OutputType.DIRECTORY, paths, ValidationActions.OUTPUT_DIRECTORIES_VALIDATOR);
}
private DefaultCacheableTaskOutputFilePropertySpec createOutputFilePropertySpec(ValidatingValue path, OutputType file, ValidationAction outputFileValidator) {
return new DefaultCacheableTaskOutputFilePropertySpec(task.getName(), resolver, file, path, outputFileValidator);
}
private static class FileTreeValue implements ValidatingValue {
private final ValidatingValue delegate;
private final FileTreeInternal fileTree;
public FileTreeValue(ValidatingValue delegate, FileTreeInternal fileTree) {
this.delegate = delegate;
this.fileTree = fileTree;
}
@Nullable
@Override
public Object call() {
return fileTree;
}
@Nullable
@Override
public Object getContainerValue() {
return fileTree;
}
@Override
public void validate(String propertyName, boolean optional, ValidationAction valueValidator, TaskValidationContext context) {
delegate.validate(propertyName, optional, valueValidator, context);
}
}
}
| 38.738739 | 162 | 0.754884 |
d31f1c4db77396bdc036f4f5aee99aa691a47c4b | 1,072 | package com.github.thomasdarimont.keycloak.trustdevice.model.jpa;
import com.google.auto.service.AutoService;
import org.keycloak.Config;
import org.keycloak.connections.jpa.entityprovider.JpaEntityProvider;
import org.keycloak.connections.jpa.entityprovider.JpaEntityProviderFactory;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
@AutoService(JpaEntityProviderFactory.class)
public class TrustedDeviceJpaEntityProviderFactory implements JpaEntityProviderFactory {
private static final TrustedDeviceJpaEntityProvider INSTANCE = new TrustedDeviceJpaEntityProvider();
@Override
public JpaEntityProvider create(KeycloakSession session) {
return INSTANCE;
}
@Override
public void init(Config.Scope config) {
// NOOP
}
@Override
public void postInit(KeycloakSessionFactory factory) {
// NOOP
}
@Override
public void close() {
// NOOP
}
@Override
public String getId() {
return TrustedDeviceJpaEntityProvider.ID;
}
}
| 26.8 | 104 | 0.752799 |
bac12f7dbb9bfe044e55b341427ec7a9420f4650 | 2,243 | package io.nosqlbench.activitytype.cql.statements.rowoperators.verification;
import io.nosqlbench.engine.api.activityconfig.yaml.OpTemplate;
import io.nosqlbench.virtdata.core.bindings.BindingsTemplate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class VerifierBuilder {
public static BindingsTemplate getExpectedValuesTemplate(OpTemplate stmtDef) {
BindingsTemplate expected = new BindingsTemplate();
if (!stmtDef.getParams().containsKey("verify-fields") && !stmtDef.getParams().containsKey("verify")) {
throw new RuntimeException("Unable to create expected values template with no 'verify' param");
}
Map<String, String> reading = stmtDef.getBindings();
List<String> fields = new ArrayList<>();
String fieldSpec = stmtDef.getOptionalStringParam("verify-fields")
.or(() -> stmtDef.getOptionalStringParam("verify"))
.orElse("*");
String[] vfields = fieldSpec.split("\\s*,\\s*");
for (String vfield : vfields) {
if (vfield.equals("*")) {
reading.forEach((k, v) -> fields.add(k));
} else if (vfield.startsWith("+")) {
fields.add(vfield.substring(1));
} else if (vfield.startsWith("-")) {
fields.remove(vfield.substring(1));
} else if (vfield.matches("\\w+(\\w+->[\\w-]+)?")) {
fields.add(vfield);
} else {
throw new RuntimeException("unknown verify-fields format: '" + vfield + "'");
}
}
for (String vfield : fields) {
String[] fieldNameAndBindingName = vfield.split("\\s*->\\s*", 2);
String fieldName = fieldNameAndBindingName[0];
String bindingName = fieldNameAndBindingName.length == 1 ? fieldName : fieldNameAndBindingName[1];
if (!reading.containsKey(bindingName)) {
throw new RuntimeException("binding name '" + bindingName +
"' referenced in verify-fields, but it is not present in available bindings.");
}
expected.addFieldBinding(fieldName, reading.get(bindingName));
}
return expected;
}
}
| 41.537037 | 110 | 0.607668 |
7be4ad0580a95aab25822e9bf4703bb21e12fdd9 | 518 | package br.ufc.util;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
public class FileUtil {
public static void salvarImagem(String path, MultipartFile imagem){
File file = new File(path);
try {
FileUtils.writeByteArrayToFile(file, imagem.getBytes());
System.out.println("Salvo em: " + file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 19.185185 | 68 | 0.712355 |
c924770c331168bb9a051060f21de858b0856322 | 484 | package com.bzh.floodview.sideslip;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.bzh.floodview.R;
import com.bzh.floodview.base.activity.BaseActivity;
/**
* 关于我们
*/
public class AboutusActivity extends BaseActivity {
@Override
protected int getContentViewLayoutID() {
return R.layout.activity_aboutus;
}
@Override
protected void initView(Bundle savedInstanceState) {
}
}
| 19.36 | 56 | 0.743802 |
b5d4b93a87c87d3fb7eb807f8d69e6d969d70962 | 4,306 | package mekanism.common.block;
import java.util.Random;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import mekanism.api.chemical.gas.GasStack;
import mekanism.api.text.EnumColor;
import mekanism.common.MekanismLang;
import mekanism.common.block.prefab.BlockTile.BlockTileModel;
import mekanism.common.content.blocktype.BlockTypeTile;
import mekanism.common.registries.MekanismBlockTypes;
import mekanism.common.registries.MekanismParticleTypes;
import mekanism.common.tile.TileEntityRadioactiveWasteBarrel;
import mekanism.common.util.WorldUtils;
import mekanism.common.util.text.TextUtils;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Hand;
import net.minecraft.util.Util;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.World;
public class BlockRadioactiveWasteBarrel extends BlockTileModel<TileEntityRadioactiveWasteBarrel, BlockTypeTile<TileEntityRadioactiveWasteBarrel>> {
public BlockRadioactiveWasteBarrel() {
super(MekanismBlockTypes.RADIOACTIVE_WASTE_BARREL);
}
//TODO - 10.1: Move animate tick and player relative block hardness checks to BlockMekanism and generify the radiation scale stuff
@Override
public void animateTick(@Nonnull BlockState state, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Random random) {
TileEntityRadioactiveWasteBarrel tile = WorldUtils.getTileEntity(TileEntityRadioactiveWasteBarrel.class, world, pos);
if (tile != null) {
int count = (int) (10 * tile.getGasScale());
if (count > 0) {
//Update count to be randomized but store it instead of calculating our max number each time we loop
count = random.nextInt(count);
for (int i = 0; i < count; i++) {
double randX = pos.getX() - 0.1 + random.nextDouble() * 1.2;
double randY = pos.getY() - 0.1 + random.nextDouble() * 1.2;
double randZ = pos.getZ() - 0.1 + random.nextDouble() * 1.2;
world.addParticle(MekanismParticleTypes.RADIATION.getParticleType(), randX, randY, randZ, 0, 0, 0);
}
}
}
}
@Override
protected float getPlayerRelativeBlockHardness(@Nonnull BlockState state, @Nonnull PlayerEntity player, @Nonnull IBlockReader world, @Nonnull BlockPos pos,
@Nullable TileEntity tile) {
//Call super variant of player relative hardness to get default
float speed = super.getPlayerRelativeBlockHardness(state, player, world, pos, tile);
if (tile instanceof TileEntityRadioactiveWasteBarrel && ((TileEntityRadioactiveWasteBarrel) tile).getGasScale() > 0) {
//Our tile has some radioactive substance in it; slow down breaking it
return speed / 5F;
}
return speed;
}
@Nonnull
@Override
@Deprecated
public ActionResultType onBlockActivated(@Nonnull BlockState state, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull PlayerEntity player, @Nonnull Hand hand,
@Nonnull BlockRayTraceResult hit) {
if (!player.isSneaking()) {
return ActionResultType.PASS;
}
TileEntityRadioactiveWasteBarrel tile = WorldUtils.getTileEntity(TileEntityRadioactiveWasteBarrel.class, world, pos);
if (tile == null) {
return ActionResultType.PASS;
}
if (!world.isRemote()) {
GasStack stored = tile.getGas();
ITextComponent text;
if (stored.isEmpty()) {
text = MekanismLang.NO_GAS.translateColored(EnumColor.GRAY);
} else {
String scale = TextUtils.getPercent(tile.getGasScale());
text = MekanismLang.STORED_MB_PERCENTAGE.translateColored(EnumColor.ORANGE, EnumColor.ORANGE, stored, EnumColor.GRAY, TextUtils.format(stored.getAmount()), scale);
}
player.sendMessage(text, Util.DUMMY_UUID);
}
return ActionResultType.SUCCESS;
}
}
| 47.318681 | 179 | 0.69856 |
0443a0bb67dcf243346417938beb00b98d7f2034 | 2,308 | package com.facebook.presto.procfs;
import com.facebook.airlift.bootstrap.LifeCycleManager;
import com.facebook.airlift.log.Logger;
import com.facebook.presto.spi.connector.Connector;
import com.facebook.presto.spi.connector.ConnectorMetadata;
import com.facebook.presto.spi.connector.ConnectorRecordSetProvider;
import com.facebook.presto.spi.connector.ConnectorSplitManager;
import com.facebook.presto.spi.connector.ConnectorTransactionHandle;
import com.facebook.presto.spi.transaction.IsolationLevel;
import static com.facebook.presto.procfs.ProcFsTransactionHandle.INSTANCE;
import static java.util.Objects.requireNonNull;
import javax.inject.Inject;
public class ProcFsConnector implements Connector {
private static final Logger log = Logger.get(ProcFsConnector.class);
private final LifeCycleManager lifeCycleManager;
private final ProcFsMetadata metadata;
private final ProcFsSplitManager splitManager;
private final ProcFsRecordSetProvider recordSetProvider;
@Inject
public ProcFsConnector(
LifeCycleManager lifeCycleManager,
ProcFsMetadata metadata,
ProcFsSplitManager splitManager,
ProcFsRecordSetProvider recordSetProvider)
{
this.lifeCycleManager = requireNonNull(lifeCycleManager, "lifeCycleManager is null");
this.metadata = requireNonNull(metadata, "metadata is null");
this.splitManager = requireNonNull(splitManager, "splitManager is null");
this.recordSetProvider = requireNonNull(recordSetProvider, "recordSetProvider is null");
}
@Override
public ConnectorTransactionHandle beginTransaction(IsolationLevel isolationLevel, boolean readOnly) {
return INSTANCE;
}
@Override
public ConnectorMetadata getMetadata(ConnectorTransactionHandle transactionHandle) {
return metadata;
}
@Override
public ConnectorSplitManager getSplitManager() {
return splitManager;
}
@Override
public ConnectorRecordSetProvider getRecordSetProvider()
{
return recordSetProvider;
}
@Override
public final void shutdown()
{
try {
lifeCycleManager.stop();
}
catch (Exception e) {
log.error(e, "Error shutting down connector");
}
}
}
| 32.971429 | 105 | 0.742201 |
91afda481db9ff2e6989cfa8d737792c8f4d3689 | 719 | package com.wch.gulimall.product.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.wch.common.utils.PageUtils;
import com.wch.gulimall.product.entity.SpuInfoEntity;
import com.wch.gulimall.product.vo.SpuSaveVo;
import java.util.Map;
/**
* spu信息
*
* @author wch
* @email 2879924329@qq.com
* @date 2022-02-20 20:19:13
*/
public interface SpuInfoService extends IService<SpuInfoEntity> {
PageUtils queryPage(Map<String, Object> params);
void saveSpuInfo(SpuSaveVo spuInfo);
void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity);
PageUtils queryPageByCondition(Map<String, Object> params);
void up(Long spuId);
SpuInfoEntity getSpuInfoBySkuId(Long skuId);
}
| 23.193548 | 65 | 0.76217 |
a02a3dd3ffd6b359cc829115314566000c276bbf | 18,128 | package com.gmail.chibitopoochan.soqlui.controller;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.util.Map;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import javax.xml.stream.XMLStreamException;
import org.slf4j.Logger;
import com.gmail.chibitopoochan.soqlui.SceneManager;
import com.gmail.chibitopoochan.soqlui.config.ApplicationSettingSet;
import com.gmail.chibitopoochan.soqlui.initializer.MainControllerInitializer;
import com.gmail.chibitopoochan.soqlui.logic.ConnectionSettingLogic;
import com.gmail.chibitopoochan.soqlui.logic.ExtractFileLogic;
import com.gmail.chibitopoochan.soqlui.logic.FavoriteLogic;
import com.gmail.chibitopoochan.soqlui.logic.SOQLHistoryLogic;
import com.gmail.chibitopoochan.soqlui.model.DescribeField;
import com.gmail.chibitopoochan.soqlui.model.DescribeSObject;
import com.gmail.chibitopoochan.soqlui.model.SOQLFavorite;
import com.gmail.chibitopoochan.soqlui.model.SOQLHistory;
import com.gmail.chibitopoochan.soqlui.model.SObjectRecord;
import com.gmail.chibitopoochan.soqlui.service.ConnectService;
import com.gmail.chibitopoochan.soqlui.service.ExportService;
import com.gmail.chibitopoochan.soqlui.service.FieldProvideService;
import com.gmail.chibitopoochan.soqlui.service.SOQLExecuteService;
import com.gmail.chibitopoochan.soqlui.util.Constants.Configuration;
import com.gmail.chibitopoochan.soqlui.util.DialogUtils;
import com.gmail.chibitopoochan.soqlui.util.LogUtils;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TabPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser.ExtensionFilter;
public class MainController implements Initializable, Controller {
// クラス共通の参照
private static final Logger logger = LogUtils.getLogger(MainController.class);
private static final ResourceBundle config = ResourceBundle.getBundle(Configuration.RESOURCE);
private static final boolean USE_DECORATOR = ApplicationSettingSet.getInstance().getSetting().isUseDecorator();
// 画面上のコンポーネント
// メニュー
@FXML private Menu menuIcon;
@FXML private MenuItem menuFileProxy;
@FXML private MenuItem menuFileConnection;
@FXML private Label titleLabel;
@FXML private Button minimam;
@FXML private Button maximam;
@FXML private Button close;
// 左側上段
@FXML private ComboBox<String> connectOption;
@FXML private Button connect;
@FXML private Button disconnect;
@FXML private CheckBox useTooling;
// 左側中断
@FXML private ProgressIndicator progressIndicator;
@FXML private TableView<DescribeSObject> sObjectList;
@FXML private TableColumn<DescribeSObject, String> prefixColumn;
@FXML private TableColumn<DescribeSObject, String> sObjectColumn;
@FXML private TextField objectSearch;
// 左側下段
@FXML private TabPane fieldTabArea;
@FXML private TableView<DescribeField> fieldList;
@FXML private TextField columnSearch;
@FXML private Label objectName;
@FXML private ProgressIndicator fieldProgressIndicator;
// 中央
@FXML private Button execute;
@FXML private Button export;
@FXML private Button cancel;
@FXML private TextArea soqlArea;
@FXML private WebView soqlWebArea;
private StringProperty actualSOQL = new SimpleStringProperty(this, "actualSOQL");
@FXML private TabPane queryTabArea;
@FXML private TextField batchSize;
@FXML private CheckBox all;
@FXML private CheckBox join;
@FXML private TableView<SObjectRecord> resultTable;
@FXML private TextField resultSearch;
@FXML private TabPane tabArea;
// 右側上段
@FXML private TextField favoriteSearch;
@FXML private ListView<SOQLFavorite> favoriteList;
// 右側下段
@FXML private TextField historySearch;
@FXML private ListView<SOQLHistory> historyList;
// 下段
@FXML private ProgressBar progressBar;
@FXML private Label progressText;
// 業務ロジック
private SceneManager manager;
private ConnectionSettingLogic setting = new ConnectionSettingLogic();
private SOQLHistoryLogic history = new SOQLHistoryLogic();
private FavoriteLogic favorite = new FavoriteLogic();
private ExtractFileLogic extract = new ExtractFileLogic();
// 非同期のサービス
private ConnectService connectService = new ConnectService();
private SOQLExecuteService executionService = new SOQLExecuteService();
private FieldProvideService fieldService = new FieldProvideService();
private ExportService exportService = new ExportService();
// 状態管理
private ObservableList<DescribeSObject> objectMasterList = FXCollections.observableArrayList();
private ObservableList<DescribeField> fieldMasterList = FXCollections.observableArrayList();
private BooleanProperty withExecute = new SimpleBooleanProperty(false);
private ObservableList<String> execSoqlList = FXCollections.observableArrayList();
private StringProperty execSoqlBaseName = new SimpleStringProperty();
// 初期化
private MainControllerInitializer init;
@Override
public void initialize(URL location, ResourceBundle resources) {
this.manager = SceneManager.getInstance();
// 画面の初期化
init = new MainControllerInitializer();
init.setController(this);
init.initialize();
// 初期値を設定
Map<String, String> parameters = manager.getParameters();
if(parameters.containsKey("param")) {
loadSOQLFile(parameters);
}
// デコレーション無しの場合
if(USE_DECORATOR) {
titleLabel.setVisible(false);
minimam.setVisible(false);
maximam.setVisible(false);
close.setVisible(false);
} else {
// ウィンドウの移動を設定
titleLabel.setOnMousePressed(event -> {
manager.saveLocation(event.getScreenX(),event.getScreenY());
});
titleLabel.setOnMouseDragged(event -> {
manager.moveLocation(event.getScreenX(), event.getScreenY());
});
}
}
private void loadSOQLFile(Map<String, String> parameters) {
String fileName = parameters.get("param");
Optional<String> envName = Optional.empty();
// ファイル名のチェック
if(fileName.endsWith(".soql")) {
String fileNameExcludeExtention = fileName.substring(0, fileName.lastIndexOf(".soql"));
int indexOfLastPrefix = fileNameExcludeExtention.lastIndexOf(".");
if(indexOfLastPrefix > -1) {
envName = Optional.of(fileNameExcludeExtention.substring(indexOfLastPrefix+1));
}
// ファイルの存在チェック
File file = new File(fileName);
if(file.exists()) {
// ファイルの読み込み
try(BufferedReader br = Files.newBufferedReader(file.toPath())) {
soqlArea.setText(br.lines().collect(Collectors.joining(System.lineSeparator())));
} catch (IOException e) {
e.printStackTrace();
}
// 初期化
envName.ifPresent(env -> connectOption.getSelectionModel().select(env));
// 接続の実行
// TODO nullで問題ないか?
setWithExecute(true);
connect.getOnAction().handle(null);
}
}
logger.debug(fileName);
}
/**
* アプリケーション設定画面の表示
*/
public void openApplicationSetting() {
try {
logger.debug("Open Window [Application Setting]");
manager.sceneOpen(Configuration.VIEW_SU05, Configuration.TITLE_SU05, false);
} catch (IOException e) {
logger.error("Open window error", e);
}
}
/**
* 接続設定画面の表示
*/
public void openConnectSetting() {
try {
logger.debug("Open Window [Connection Setting]");
manager.sceneOpen(Configuration.VIEW_SU02, Configuration.TITLE_SU02, false);
} catch (IOException e) {
logger.error("Open window error", e);
}
}
/**
* プロキシ設定画面の表示
*/
public void openProxySetting() {
try {
logger.debug("Open Window [Proxy Setting]");
manager.sceneOpen(Configuration.VIEW_SU04, Configuration.TITLE_SU04, false);
} catch (IOException e) {
logger.error("Open window error", e);
}
}
/**
* ファイルへの保存
*/
public void onSave() {
// 保存先の取得
File saveFile = DialogUtils.showSaveDialog(
"untitled."+connectOption.getSelectionModel().getSelectedItem()+".soql"
,new ExtensionFilter("soql file", "soql"));
if(saveFile == null) return;
// ファイルの保存
logger.debug("Save to " + saveFile.getAbsolutePath());
try(FileWriter writer = new FileWriter(saveFile)) {
writer.write(soqlArea.getText());
DialogUtils.showAlertDialog("ファイルを保存しました。");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* ヘルプの表示
*/
public void onHelp() {
DialogUtils.showWebDialog(config.getString(Configuration.URL_HELP));
}
/**
* 概要の表示
*/
public void onAbout() {
DialogUtils.showWebDialog(config.getString(Configuration.URL_ABOUT));
}
/**
* 変更履歴の表示
*/
public void onChangeLog() {
DialogUtils.showWebDialog(config.getString(Configuration.URL_CHANGELOG));
}
/**
* ライセンスの表示
*/
public void onLicense() {
DialogUtils.showWebDialog(config.getString(Configuration.URL_LICENSE));
}
/**
* Windowの最小化
*/
public void minimam() {
manager.minimized();
}
/**
* Windowの最大化
*/
public void onChangeSize() {
manager.sizeChange();
}
/**
* アプリのクローズ
*/
public void onClose() {
manager.sceneClose();
}
/**
* 接続情報を更新
*/
@Override
public void onCloseChild() {
try {
setting.loadSettings();
} catch (IllegalStateException | IOException | XMLStreamException e) {
logger.error("Load settings error", e);
}
init.reset();
}
/**
*
* @return
*/
public TextField getResultSearch() {
return resultSearch;
}
/**
*
* @param resultSearch
*/
public void setResultSearch(TextField resultSearch) {
this.resultSearch = resultSearch;
}
/**
* @return progressBar
*/
public ProgressBar getProgressBar() {
return progressBar;
}
/**
* @param progress
*/
public void setProgressBar(ProgressBar progress) {
this.progressBar = progress;
}
/**
* @return exportService
*/
public ExportService getExportService() {
return exportService;
}
/**
* @param exportService セットする exportService
*/
public void setExportService(ExportService exportService) {
this.exportService = exportService;
}
/**
* @return export
*/
public Button getExport() {
return export;
}
/**
* @param export セットする export
*/
public void setExport(Button export) {
this.export = export;
}
/**
* @return connectOption
*/
public ComboBox<String> getConnectOption() {
return connectOption;
}
/**
* @return connect
*/
public Button getConnect() {
return connect;
}
/**
* @return disconnect
*/
public Button getDisconnect() {
return disconnect;
}
/**
* @return progressIndicator
*/
public ProgressIndicator getProgressIndicator() {
return progressIndicator;
}
/**
* @return sObjectList
*/
public TableView<DescribeSObject> getsObjectList() {
return sObjectList;
}
/**
* @return prefixColumn
*/
public TableColumn<DescribeSObject, String> getPrefixColumn() {
return prefixColumn;
}
/**
* @return sObjectColumn
*/
public TableColumn<DescribeSObject, String> getsObjectColumn() {
return sObjectColumn;
}
/**
* @return objectSearch
*/
public TextField getObjectSearch() {
return objectSearch;
}
/**
* @return fieldList
*/
public TableView<DescribeField> getFieldList() {
return fieldList;
}
/**
* @return progressIndicator
*/
public ProgressIndicator getFieldProgressIndicator() {
return fieldProgressIndicator;
}
/**
* @return columnSearch
*/
public TextField getColumnSearch() {
return columnSearch;
}
/**
* @return execute
*/
public Button getExecute() {
return execute;
}
/**
* @return soqlArea
*/
public TextArea getSoqlArea() {
return soqlArea;
}
/**
* @return batchSize
*/
public TextField getBatchSize() {
return batchSize;
}
/**
* @return all
*/
public CheckBox getAll() {
return all;
}
public CheckBox getJoin() {
return join;
}
/**
* @return resultTable
*/
public TableView<SObjectRecord> getResultTable() {
return resultTable;
}
/**
* @return setting
*/
public ConnectionSettingLogic getSetting() {
return setting;
}
/**
* @return connectService
*/
public ConnectService getConnectService() {
return connectService;
}
/**
* @return executionService
*/
public SOQLExecuteService getExecutionService() {
return executionService;
}
/**
* @return fieldService
*/
public FieldProvideService getFieldService() {
return fieldService;
}
/**
* @return objectMasterList
*/
public ObservableList<DescribeSObject> getObjectMasterList() {
return objectMasterList;
}
/**
* @return fieldMasterList
*/
public ObservableList<DescribeField> getFieldMasterList() {
return fieldMasterList;
}
/**
* @return progressText
*/
public Label getProgressText() {
return progressText;
}
/**
* @param progressText セットする progressText
*/
public void setProgressText(Label progressText) {
this.progressText = progressText;
}
/**
* @return objectName
*/
public Label getObjectName() {
return objectName;
}
/**
* @param objectName セットする objectName
*/
public void setObjectName(Label objectName) {
this.objectName = objectName;
}
/**
* @return tabArea
*/
public TabPane getTabArea() {
return tabArea;
}
/**
* @param tabArea セットする tabArea
*/
public void setTabArea(TabPane tabArea) {
this.tabArea = tabArea;
}
/**
* @return historyList
*/
public ListView<SOQLHistory> getHistoryList() {
return historyList;
}
/**
* @return historySearch
*/
public TextField getHistorySearch() {
return historySearch;
}
/**
* @return history
*/
public SOQLHistoryLogic getHistory() {
return history;
}
/**
* @param history セットする history
*/
public void setHistory(SOQLHistoryLogic history) {
this.history = history;
}
/**
* @return favoriteList
*/
public ListView<SOQLFavorite> getFavoriteList() {
return favoriteList;
}
/**
* @return favorite
*/
public FavoriteLogic getFavoriteLogic() {
return favorite;
}
/**
* @param favorite セットする favorite
*/
public void setFavorite(FavoriteLogic favorite) {
this.favorite = favorite;
}
/**
* @return cancel
*/
public Button getCancel() {
return cancel;
}
/**
* @param cancel セットする cancel
*/
public void setCancel(Button cancel) {
this.cancel = cancel;
}
/**
* @return favoriteSearch
*/
public TextField getFavoriteSearch() {
return favoriteSearch;
}
/**
* @return queryTabArea
*/
public TabPane getQueryTabArea() {
return queryTabArea;
}
/**
* @param queryTabArea セットする queryTabArea
*/
public void setQueryTabArea(TabPane queryTabArea) {
this.queryTabArea = queryTabArea;
}
/**
* @return fieldTabArea
*/
public TabPane getFieldTabArea() {
return fieldTabArea;
}
/**
* @param fieldTabArea セットする fieldTabArea
*/
public void setFieldTabArea(TabPane fieldTabArea) {
this.fieldTabArea = fieldTabArea;
}
/**
* @param fieldProgressIndicator セットする fieldProgressIndicator
*/
public void setFieldProgressIndicator(ProgressIndicator fieldProgressIndicator) {
this.fieldProgressIndicator = fieldProgressIndicator;
}
/**
* @return withExecute
*/
public boolean withExecute() {
return withExecute.get();
}
/**
* @param withExecute セットする withExecute
*/
public void setWithExecute(boolean withExecute) {
this.withExecute.set(withExecute);
}
/**
* 接続後、SOQL実行有無のプロパティ
*/
public BooleanProperty withExecuteProperty() {
return withExecute;
}
public WebView getSoqlWebArea() {
return soqlWebArea;
}
/**
* @return titleLabel
*/
public Label getTitleLabel() {
return titleLabel;
}
/**
* @param titleLabel セットする titleLabel
*/
public void setTitleLabel(Label titleLabel) {
this.titleLabel = titleLabel;
}
public StringProperty actualSOQL() {
return actualSOQL;
}
/**
* @return useTooling
*/
public CheckBox getUseTooling() {
return useTooling;
}
/**
* @param useTooling セットする useTooling
*/
public void setUseTooling(CheckBox useTooling) {
this.useTooling = useTooling;
}
/**
* @return extract
*/
public ExtractFileLogic getExtract() {
return extract;
}
/**
* @param extract セットする extract
*/
public void setExtract(ExtractFileLogic extract) {
this.extract = extract;
}
/**
* @return execSoqlList
*/
public ObservableList<String> getExecSoqlList() {
return execSoqlList;
}
/**
* @param execSoqlList セットする execSoqlList
*/
public void setExecSoqlList(ObservableList<String> execSoqlList) {
this.execSoqlList = execSoqlList;
}
/**
* @return execSoqlBaseName
*/
public StringProperty getExecSoqlBaseName() {
return execSoqlBaseName;
}
/**
* @param execSoqlBaseName セットする execSoqlBaseName
*/
public void setExecSoqlBaseName(StringProperty execSoqlBaseName) {
this.execSoqlBaseName = execSoqlBaseName;
}
}
| 22.603491 | 113 | 0.696492 |
4755fbf5e4c10e721e6c121874ee0a79dd0b2a0d | 1,887 | package org.dotwebstack.framework.frontend.ld.writer.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.OutputStream;
import java.util.Iterator;
import org.dotwebstack.framework.frontend.ld.entity.TupleEntity;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.query.Binding;
import org.eclipse.rdf4j.query.BindingSet;
import org.eclipse.rdf4j.query.TupleQueryResult;
import org.eclipse.rdf4j.query.resultio.TupleQueryResultWriter;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
public class SparqlResultsTupleEntityWriterTestBase {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Mock
OutputStream outputStream;
@Mock
TupleEntity tupleEntity;
@Mock
TupleQueryResult tupleQueryResult;
@Captor
ArgumentCaptor<byte[]> byteCaptor;
@Test
public void constructor_ThrowsException_ForMissingMediaType() {
// Assert
thrown.expect(NullPointerException.class);
// Act
new AbstractSparqlResultsTupleEntityWriter(null) {
@Override
protected TupleQueryResultWriter createWriter(OutputStream outputStream) {
return null;
}
};
}
void configureBindingSetWithValue(BindingSet bindingSet, String value) {
Iterator<Binding> iterator = mock(Iterator.class);
when(bindingSet.iterator()).thenReturn(iterator);
ValueFactory factory = SimpleValueFactory.getInstance();
Binding binding = mock(Binding.class);
when(iterator.hasNext()).thenReturn(true, false);
when(iterator.next()).thenReturn(binding);
when(binding.getName()).thenReturn("beer");
when(binding.getValue()).thenReturn(factory.createLiteral(value));
}
}
| 28.164179 | 80 | 0.772655 |
3ab16dea6769389ce22c6ea7a527e416b4496960 | 436 | package com.nutiteq.nuticomponents;
import com.carto.core.MapBounds;
public class GeocodeResult {
public String line1;
public String line2;
public double lon;
public double lat;
public MapBounds boundingBox;
public GeocodeResult(String line1, String line2, double lon, double lat, MapBounds boundingBox) {
this.line1 = line1;
this.line2 = line2;
this.lon = lon;
this.lat = lat;
this.boundingBox = boundingBox;
}
}
| 19.818182 | 98 | 0.745413 |
071071226865d67bfe7c52be0f86671f6d581167 | 329 | package no.ntnu.idi.apollo69framework.network_messages.data_transfer_objects;
public class ShotDto {
public PositionDto positionDto;
public float radius;
public ShotDto() { }
public ShotDto(PositionDto positionDto, float radius) {
this.positionDto = positionDto;
this.radius = radius;
}
}
| 21.933333 | 77 | 0.711246 |
62ae554065cc106836b7022ced9a9ca6c52ead47 | 706 | package com.dxy.facebook.login;
import android.os.Bundle;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.HttpMethod;
/**
*
* 获取用户信息请求
*
*/
public class FBUserRequest {
private static final String ME_ENDPOINT = "/me";
public static void makeUserRequest(GraphRequest.Callback callback) {
Bundle params = new Bundle();
params.putString("fields", "picture,name,id,email");
GraphRequest request = new GraphRequest(
AccessToken.getCurrentAccessToken(),
ME_ENDPOINT,
params,
HttpMethod.GET,
callback
);
request.executeAsync();
}
}
| 22.0625 | 72 | 0.626062 |
eb01ef674ff9249862a9a9d642c0cd5f64fbcb78 | 1,496 | package book.video.controller;
import book.video.boundary.YouTubeGateway;
import book.video.boundary.YouTubeVideos;
import book.video.entity.YoutubeLinks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
@Component
public class VideoServiceController {
private final YouTubeGateway youtubeGateway;
private final YouTubeVideos youtubeVideos;
@Autowired
public VideoServiceController(final YouTubeGateway
youtubeGateway, final
YouTubeVideos youtubeVideos) {
this.youtubeGateway = youtubeGateway;
this.youtubeVideos = youtubeVideos;
}
public List<String> getLinksFromGame(final String gameId, final
String gameName) {
if (youtubeVideos.isGameInserted(gameId)) {
return youtubeVideos.getYouTubeLinks(gameId);
} else {
try {
final YoutubeLinks youtubeLinks = youtubeGateway
.findYoutubeLinks(gameName);
final List<String> youtubeLinksAsString =
youtubeLinks.getYoutubeLinksAsString();
youtubeVideos.createYouTubeLinks(gameId,
youtubeLinksAsString);
return youtubeLinksAsString;
} catch (final IOException e) {
throw new IllegalArgumentException(e);
}
}
}
}
| 31.829787 | 67 | 0.654412 |
4c15fdf9d5df962222e4fe0e7298cd3fc6c81944 | 1,412 | package ru.liahim.mist.client.renderer.entity;
import ru.liahim.mist.client.model.entity.ModelBarvog;
import ru.liahim.mist.client.renderer.entity.layers.LayerBarvogSaddle;
import ru.liahim.mist.common.Mist;
import ru.liahim.mist.entity.EntityBarvog;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.util.ResourceLocation;
public class RenderBarvog extends RenderLiving<EntityBarvog> {
private static final ResourceLocation textureLoc[] = new ResourceLocation[] {
new ResourceLocation(Mist.MODID, "textures/entity/barvog/barvog_m.png"), //0
new ResourceLocation(Mist.MODID, "textures/entity/barvog/barvog_f.png"), //1
new ResourceLocation(Mist.MODID, "textures/entity/barvog/barvog_am.png"), //2
new ResourceLocation(Mist.MODID, "textures/entity/barvog/barvog_af.png"), //3
new ResourceLocation(Mist.MODID, "textures/entity/barvog/barvog_c.png") //4
};
public RenderBarvog(RenderManager manager) {
super(manager, new ModelBarvog(), 0.9F);
this.addLayer(new LayerBarvogSaddle(this));
}
@Override
protected ResourceLocation getEntityTexture(EntityBarvog entity) {
if (entity.isChild()) return entity.isAlbino() ? textureLoc[3] : textureLoc[4];
if (entity.isAlbino()) return entity.isFemale() ? textureLoc[3] : textureLoc[2];
return entity.isFemale() ? textureLoc[1] : textureLoc[0];
}
} | 44.125 | 82 | 0.775496 |
cecacc1238f539d8a62b161ea7d65a04af8a458f | 2,217 | /*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id: Method.java,v 1.2.4.1 2005/09/15 08:15:19 suresh_emailid Exp $
*/
package com.sun.org.apache.xml.internal.serializer;
/**
* This class defines the constants which are the names of the four default
* output methods.
* <p>
* Three default output methods are defined: XML, HTML, and TEXT.
* These constants can be used as an argument to the
* OutputPropertiesFactory.getDefaultMethodProperties() method to get
* the properties to create a serializer.
*
* This class is a public API.
*
* @see OutputPropertiesFactory
* @see Serializer
*
* @xsl.usage general
*/
public final class Method
{
/**
* A private constructor to prevent the creation of such a class.
*/
private Method() {
}
/**
* The output method type for XML documents: <tt>xml</tt>.
*/
public static final String XML = "xml";
/**
* The output method type for HTML documents: <tt>html</tt>.
*/
public static final String HTML = "html";
/**
* The output method for XHTML documents,
* this method type is not currently supported: <tt>xhtml</tt>.
*/
public static final String XHTML = "xhtml";
/**
* The output method type for text documents: <tt>text</tt>.
*/
public static final String TEXT = "text";
/**
* The "internal" method, just used when no method is
* specified in the style sheet, and a serializer of this type wraps either an
* XML or HTML type (depending on the first tag in the output being html or
* not)
*/
public static final String UNKNOWN = "";
}
| 28.063291 | 80 | 0.687415 |
c694836900a8d6e7438f9fddc31e6a7f0e24956a | 3,548 | package me.electroid.game.util;
/*
* 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.
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZipUtils {
/**
* Unzip a file from a url.
* @param url The url where to download the zip.
* @param targetDir The target directory for the unzipped file.
* @return The unzipped file.
* @throws IOException
*/
public static File unZip(URL url, File targetDir) throws IOException {
if (!targetDir.exists()) {
targetDir.mkdirs();
}
InputStream in = new BufferedInputStream(url.openStream(), 1024);
File zip = File.createTempFile("arc", ".zip", targetDir);
OutputStream out = new BufferedOutputStream(new FileOutputStream(zip));
copyInputStream(in, out);
out.close();
return unZip(zip, targetDir).get(0);
}
private static List<File> unZip(File theFile, File targetDir) throws IOException {
if (!theFile.exists()) throw new IOException(theFile.getAbsolutePath() + " does not exist");
if (!buildDirectory(targetDir)) throw new IOException("Could not create directory: " + targetDir);
List<File> files = new ArrayList<>();
ZipFile zipFile = new ZipFile(theFile);
for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
File file = new File(targetDir, File.separator + entry.getName());
if (!buildDirectory(file.getParentFile())) throw new IOException("Could not create directory: " + file.getParentFile());
if (!entry.isDirectory()) {
copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(file)));
} else {
if (!buildDirectory(file)) throw new IOException("Could not create directory: " + file);
}
files.add(file);
}
zipFile.close();
theFile.delete();
return files;
}
public static void copyInputStream(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len >= 0) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
in.close();
out.close();
}
public static boolean buildDirectory(File file) {
return file.exists() || file.mkdirs();
}
} | 39.422222 | 132 | 0.666009 |
2eeecb164f4b2da6a2fbdc7a864e9355c69b7bda | 26,335 | package android.support.v4.widget;
import android.content.Context;
import android.support.v4.view.C0534t;
import android.support.v4.view.ah;
import android.support.v4.view.aj;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import com.google.android.gms.C1114a.C1096c;
import com.google.android.gms.maps.GoogleMap;
import java.util.Arrays;
public class ad {
private static final Interpolator f1067v;
private int f1068a;
private int f1069b;
private int f1070c;
private float[] f1071d;
private float[] f1072e;
private float[] f1073f;
private float[] f1074g;
private int[] f1075h;
private int[] f1076i;
private int[] f1077j;
private int f1078k;
private VelocityTracker f1079l;
private float f1080m;
private float f1081n;
private int f1082o;
private int f1083p;
private C0588u f1084q;
private final C0052a f1085r;
private View f1086s;
private boolean f1087t;
private final ViewGroup f1088u;
private final Runnable f1089w;
/* renamed from: android.support.v4.widget.ad.a */
public static abstract class C0052a {
public int m217a(View view) {
return 0;
}
public int m218a(View view, int i, int i2) {
return 0;
}
public void m219a(int i) {
}
public void m220a(int i, int i2) {
}
public void m221a(View view, float f, float f2) {
}
public void m222a(View view, int i, int i2, int i3, int i4) {
}
public abstract boolean m223a(View view, int i);
public int m224b(View view) {
return 0;
}
public int m225b(View view, int i, int i2) {
return 0;
}
public void m226b(int i, int i2) {
}
public void m227b(View view, int i) {
}
public boolean m228b(int i) {
return false;
}
public int m229c(int i) {
return i;
}
}
/* renamed from: android.support.v4.widget.ad.1 */
static class C05511 implements Interpolator {
C05511() {
}
public float getInterpolation(float f) {
float f2 = f - 1.0f;
return (f2 * (((f2 * f2) * f2) * f2)) + 1.0f;
}
}
/* renamed from: android.support.v4.widget.ad.2 */
class C05522 implements Runnable {
final /* synthetic */ ad f1066a;
C05522(ad adVar) {
this.f1066a = adVar;
}
public void run() {
this.f1066a.m2405b(0);
}
}
static {
f1067v = new C05511();
}
private ad(Context context, ViewGroup viewGroup, C0052a c0052a) {
this.f1070c = -1;
this.f1089w = new C05522(this);
if (viewGroup == null) {
throw new IllegalArgumentException("Parent view may not be null");
} else if (c0052a == null) {
throw new IllegalArgumentException("Callback may not be null");
} else {
this.f1088u = viewGroup;
this.f1085r = c0052a;
ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
this.f1082o = (int) ((context.getResources().getDisplayMetrics().density * 20.0f) + 0.5f);
this.f1069b = viewConfiguration.getScaledTouchSlop();
this.f1080m = (float) viewConfiguration.getScaledMaximumFlingVelocity();
this.f1081n = (float) viewConfiguration.getScaledMinimumFlingVelocity();
this.f1084q = C0588u.m2513a(context, f1067v);
}
}
private float m2376a(float f) {
return (float) Math.sin((double) ((float) (((double) (f - 0.5f)) * 0.4712389167638204d)));
}
private float m2377a(float f, float f2, float f3) {
float abs = Math.abs(f);
return abs < f2 ? 0.0f : abs > f3 ? f <= 0.0f ? -f3 : f3 : f;
}
private int m2378a(int i, int i2, int i3) {
if (i == 0) {
return 0;
}
int width = this.f1088u.getWidth();
int i4 = width / 2;
float a = (m2376a(Math.min(1.0f, ((float) Math.abs(i)) / ((float) width))) * ((float) i4)) + ((float) i4);
i4 = Math.abs(i2);
return Math.min(i4 > 0 ? Math.round(Math.abs(a / ((float) i4)) * 1000.0f) * 4 : (int) (((((float) Math.abs(i)) / ((float) i3)) + 1.0f) * 256.0f), 600);
}
private int m2379a(View view, int i, int i2, int i3, int i4) {
int b = m2387b(i3, (int) this.f1081n, (int) this.f1080m);
int b2 = m2387b(i4, (int) this.f1081n, (int) this.f1080m);
int abs = Math.abs(i);
int abs2 = Math.abs(i2);
int abs3 = Math.abs(b);
int abs4 = Math.abs(b2);
int i5 = abs3 + abs4;
int i6 = abs + abs2;
return (int) (((b2 != 0 ? ((float) abs4) / ((float) i5) : ((float) abs2) / ((float) i6)) * ((float) m2378a(i2, b2, this.f1085r.m217a(view)))) + ((b != 0 ? ((float) abs3) / ((float) i5) : ((float) abs) / ((float) i6)) * ((float) m2378a(i, b, this.f1085r.m224b(view)))));
}
public static ad m2380a(ViewGroup viewGroup, float f, C0052a c0052a) {
ad a = m2381a(viewGroup, c0052a);
a.f1069b = (int) (((float) a.f1069b) * (1.0f / f));
return a;
}
public static ad m2381a(ViewGroup viewGroup, C0052a c0052a) {
return new ad(viewGroup.getContext(), viewGroup, c0052a);
}
private void m2382a(float f, float f2) {
this.f1087t = true;
this.f1085r.m221a(this.f1086s, f, f2);
this.f1087t = false;
if (this.f1068a == 1) {
m2405b(0);
}
}
private void m2383a(float f, float f2, int i) {
m2393e(i);
float[] fArr = this.f1071d;
this.f1073f[i] = f;
fArr[i] = f;
fArr = this.f1072e;
this.f1074g[i] = f2;
fArr[i] = f2;
this.f1075h[i] = m2392e((int) f, (int) f2);
this.f1078k |= 1 << i;
}
private boolean m2384a(float f, float f2, int i, int i2) {
float abs = Math.abs(f);
float abs2 = Math.abs(f2);
if ((this.f1075h[i] & i2) != i2 || (this.f1083p & i2) == 0 || (this.f1077j[i] & i2) == i2 || (this.f1076i[i] & i2) == i2) {
return false;
}
if (abs <= ((float) this.f1069b) && abs2 <= ((float) this.f1069b)) {
return false;
}
if (abs >= abs2 * 0.5f || !this.f1085r.m228b(i2)) {
return (this.f1076i[i] & i2) == 0 && abs > ((float) this.f1069b);
} else {
int[] iArr = this.f1077j;
iArr[i] = iArr[i] | i2;
return false;
}
}
private boolean m2385a(int i, int i2, int i3, int i4) {
int left = this.f1086s.getLeft();
int top = this.f1086s.getTop();
int i5 = i - left;
int i6 = i2 - top;
if (i5 == 0 && i6 == 0) {
this.f1084q.m2526h();
m2405b(0);
return false;
}
this.f1084q.m2515a(left, top, i5, i6, m2379a(this.f1086s, i5, i6, i3, i4));
m2405b(2);
return true;
}
private boolean m2386a(View view, float f, float f2) {
if (view == null) {
return false;
}
boolean z = this.f1085r.m224b(view) > 0;
boolean z2 = this.f1085r.m217a(view) > 0;
return (z && z2) ? (f * f) + (f2 * f2) > ((float) (this.f1069b * this.f1069b)) : z ? Math.abs(f) > ((float) this.f1069b) : z2 ? Math.abs(f2) > ((float) this.f1069b) : false;
}
private int m2387b(int i, int i2, int i3) {
int abs = Math.abs(i);
return abs < i2 ? 0 : abs > i3 ? i <= 0 ? -i3 : i3 : i;
}
private void m2388b(float f, float f2, int i) {
int i2 = 1;
if (!m2384a(f, f2, i, 1)) {
i2 = 0;
}
if (m2384a(f2, f, i, 4)) {
i2 |= 4;
}
if (m2384a(f, f2, i, 2)) {
i2 |= 2;
}
if (m2384a(f2, f, i, 8)) {
i2 |= 8;
}
if (i2 != 0) {
int[] iArr = this.f1076i;
iArr[i] = iArr[i] | i2;
this.f1085r.m226b(i2, i);
}
}
private void m2389b(int i, int i2, int i3, int i4) {
int b;
int a;
int left = this.f1086s.getLeft();
int top = this.f1086s.getTop();
if (i3 != 0) {
b = this.f1085r.m225b(this.f1086s, i, i3);
aj.m1882e(this.f1086s, b - left);
} else {
b = i;
}
if (i4 != 0) {
a = this.f1085r.m218a(this.f1086s, i2, i4);
aj.m1880d(this.f1086s, a - top);
} else {
a = i2;
}
if (i3 != 0 || i4 != 0) {
this.f1085r.m222a(this.f1086s, b, a, b - left, a - top);
}
}
private void m2390c(MotionEvent motionEvent) {
int pointerCount = motionEvent.getPointerCount();
for (int i = 0; i < pointerCount; i++) {
int pointerId = motionEvent.getPointerId(i);
if (m2395f(pointerId)) {
float x = motionEvent.getX(i);
float y = motionEvent.getY(i);
this.f1073f[pointerId] = x;
this.f1074g[pointerId] = y;
}
}
}
private void m2391d(int i) {
if (this.f1071d != null && m2399a(i)) {
this.f1071d[i] = 0.0f;
this.f1072e[i] = 0.0f;
this.f1073f[i] = 0.0f;
this.f1074g[i] = 0.0f;
this.f1075h[i] = 0;
this.f1076i[i] = 0;
this.f1077j[i] = 0;
this.f1078k &= (1 << i) ^ -1;
}
}
private int m2392e(int i, int i2) {
int i3 = 0;
if (i < this.f1088u.getLeft() + this.f1082o) {
i3 = 1;
}
if (i2 < this.f1088u.getTop() + this.f1082o) {
i3 |= 4;
}
if (i > this.f1088u.getRight() - this.f1082o) {
i3 |= 2;
}
return i2 > this.f1088u.getBottom() - this.f1082o ? i3 | 8 : i3;
}
private void m2393e(int i) {
if (this.f1071d == null || this.f1071d.length <= i) {
Object obj = new float[(i + 1)];
Object obj2 = new float[(i + 1)];
Object obj3 = new float[(i + 1)];
Object obj4 = new float[(i + 1)];
Object obj5 = new int[(i + 1)];
Object obj6 = new int[(i + 1)];
Object obj7 = new int[(i + 1)];
if (this.f1071d != null) {
System.arraycopy(this.f1071d, 0, obj, 0, this.f1071d.length);
System.arraycopy(this.f1072e, 0, obj2, 0, this.f1072e.length);
System.arraycopy(this.f1073f, 0, obj3, 0, this.f1073f.length);
System.arraycopy(this.f1074g, 0, obj4, 0, this.f1074g.length);
System.arraycopy(this.f1075h, 0, obj5, 0, this.f1075h.length);
System.arraycopy(this.f1076i, 0, obj6, 0, this.f1076i.length);
System.arraycopy(this.f1077j, 0, obj7, 0, this.f1077j.length);
}
this.f1071d = obj;
this.f1072e = obj2;
this.f1073f = obj3;
this.f1074g = obj4;
this.f1075h = obj5;
this.f1076i = obj6;
this.f1077j = obj7;
}
}
private void m2394f() {
if (this.f1071d != null) {
Arrays.fill(this.f1071d, 0.0f);
Arrays.fill(this.f1072e, 0.0f);
Arrays.fill(this.f1073f, 0.0f);
Arrays.fill(this.f1074g, 0.0f);
Arrays.fill(this.f1075h, 0);
Arrays.fill(this.f1076i, 0);
Arrays.fill(this.f1077j, 0);
this.f1078k = 0;
}
}
private boolean m2395f(int i) {
if (m2399a(i)) {
return true;
}
Log.e("ViewDragHelper", "Ignoring pointerId=" + i + " because ACTION_DOWN was not received " + "for this pointer before ACTION_MOVE. It likely happened because " + " ViewDragHelper did not receive all the events in the event stream.");
return false;
}
private void m2396g() {
this.f1079l.computeCurrentVelocity(1000, this.f1080m);
m2382a(m2377a(ah.m1646a(this.f1079l, this.f1070c), this.f1081n, this.f1080m), m2377a(ah.m1647b(this.f1079l, this.f1070c), this.f1081n, this.f1080m));
}
public int m2397a() {
return this.f1068a;
}
public void m2398a(View view, int i) {
if (view.getParent() != this.f1088u) {
throw new IllegalArgumentException("captureChildView: parameter must be a descendant of the ViewDragHelper's tracked parent view (" + this.f1088u + ")");
}
this.f1086s = view;
this.f1070c = i;
this.f1085r.m227b(view, i);
m2405b(1);
}
public boolean m2399a(int i) {
return (this.f1078k & (1 << i)) != 0;
}
public boolean m2400a(int i, int i2) {
if (this.f1087t) {
return m2385a(i, i2, (int) ah.m1646a(this.f1079l, this.f1070c), (int) ah.m1647b(this.f1079l, this.f1070c));
}
throw new IllegalStateException("Cannot settleCapturedViewAt outside of a call to Callback#onViewReleased");
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public boolean m2401a(android.view.MotionEvent r14) {
/*
r13 = this;
r0 = android.support.v4.view.C0534t.m2226a(r14);
r1 = android.support.v4.view.C0534t.m2227b(r14);
if (r0 != 0) goto L_0x000d;
L_0x000a:
r13.m2415e();
L_0x000d:
r2 = r13.f1079l;
if (r2 != 0) goto L_0x0017;
L_0x0011:
r2 = android.view.VelocityTracker.obtain();
r13.f1079l = r2;
L_0x0017:
r2 = r13.f1079l;
r2.addMovement(r14);
switch(r0) {
case 0: goto L_0x0026;
case 1: goto L_0x0128;
case 2: goto L_0x0092;
case 3: goto L_0x0128;
case 4: goto L_0x001f;
case 5: goto L_0x005a;
case 6: goto L_0x011f;
default: goto L_0x001f;
};
L_0x001f:
r0 = r13.f1068a;
r1 = 1;
if (r0 != r1) goto L_0x012d;
L_0x0024:
r0 = 1;
L_0x0025:
return r0;
L_0x0026:
r0 = r14.getX();
r1 = r14.getY();
r2 = 0;
r2 = r14.getPointerId(r2);
r13.m2383a(r0, r1, r2);
r0 = (int) r0;
r1 = (int) r1;
r0 = r13.m2414d(r0, r1);
r1 = r13.f1086s;
if (r0 != r1) goto L_0x0048;
L_0x0040:
r1 = r13.f1068a;
r3 = 2;
if (r1 != r3) goto L_0x0048;
L_0x0045:
r13.m2408b(r0, r2);
L_0x0048:
r0 = r13.f1075h;
r0 = r0[r2];
r1 = r13.f1083p;
r1 = r1 & r0;
if (r1 == 0) goto L_0x001f;
L_0x0051:
r1 = r13.f1085r;
r3 = r13.f1083p;
r0 = r0 & r3;
r1.m220a(r0, r2);
goto L_0x001f;
L_0x005a:
r0 = r14.getPointerId(r1);
r2 = r14.getX(r1);
r1 = r14.getY(r1);
r13.m2383a(r2, r1, r0);
r3 = r13.f1068a;
if (r3 != 0) goto L_0x007f;
L_0x006d:
r1 = r13.f1075h;
r1 = r1[r0];
r2 = r13.f1083p;
r2 = r2 & r1;
if (r2 == 0) goto L_0x001f;
L_0x0076:
r2 = r13.f1085r;
r3 = r13.f1083p;
r1 = r1 & r3;
r2.m220a(r1, r0);
goto L_0x001f;
L_0x007f:
r3 = r13.f1068a;
r4 = 2;
if (r3 != r4) goto L_0x001f;
L_0x0084:
r2 = (int) r2;
r1 = (int) r1;
r1 = r13.m2414d(r2, r1);
r2 = r13.f1086s;
if (r1 != r2) goto L_0x001f;
L_0x008e:
r13.m2408b(r1, r0);
goto L_0x001f;
L_0x0092:
r0 = r13.f1071d;
if (r0 == 0) goto L_0x001f;
L_0x0096:
r0 = r13.f1072e;
if (r0 == 0) goto L_0x001f;
L_0x009a:
r2 = r14.getPointerCount();
r0 = 0;
r1 = r0;
L_0x00a0:
if (r1 >= r2) goto L_0x0107;
L_0x00a2:
r3 = r14.getPointerId(r1);
r0 = r13.m2395f(r3);
if (r0 != 0) goto L_0x00b0;
L_0x00ac:
r0 = r1 + 1;
r1 = r0;
goto L_0x00a0;
L_0x00b0:
r0 = r14.getX(r1);
r4 = r14.getY(r1);
r5 = r13.f1071d;
r5 = r5[r3];
r5 = r0 - r5;
r6 = r13.f1072e;
r6 = r6[r3];
r6 = r4 - r6;
r0 = (int) r0;
r4 = (int) r4;
r4 = r13.m2414d(r0, r4);
if (r4 == 0) goto L_0x010c;
L_0x00cc:
r0 = r13.m2386a(r4, r5, r6);
if (r0 == 0) goto L_0x010c;
L_0x00d2:
r0 = 1;
L_0x00d3:
if (r0 == 0) goto L_0x010e;
L_0x00d5:
r7 = r4.getLeft();
r8 = (int) r5;
r8 = r8 + r7;
r9 = r13.f1085r;
r10 = (int) r5;
r8 = r9.m225b(r4, r8, r10);
r9 = r4.getTop();
r10 = (int) r6;
r10 = r10 + r9;
r11 = r13.f1085r;
r12 = (int) r6;
r10 = r11.m218a(r4, r10, r12);
r11 = r13.f1085r;
r11 = r11.m224b(r4);
r12 = r13.f1085r;
r12 = r12.m217a(r4);
if (r11 == 0) goto L_0x0101;
L_0x00fd:
if (r11 <= 0) goto L_0x010e;
L_0x00ff:
if (r8 != r7) goto L_0x010e;
L_0x0101:
if (r12 == 0) goto L_0x0107;
L_0x0103:
if (r12 <= 0) goto L_0x010e;
L_0x0105:
if (r10 != r9) goto L_0x010e;
L_0x0107:
r13.m2390c(r14);
goto L_0x001f;
L_0x010c:
r0 = 0;
goto L_0x00d3;
L_0x010e:
r13.m2388b(r5, r6, r3);
r5 = r13.f1068a;
r6 = 1;
if (r5 == r6) goto L_0x0107;
L_0x0116:
if (r0 == 0) goto L_0x00ac;
L_0x0118:
r0 = r13.m2408b(r4, r3);
if (r0 == 0) goto L_0x00ac;
L_0x011e:
goto L_0x0107;
L_0x011f:
r0 = r14.getPointerId(r1);
r13.m2391d(r0);
goto L_0x001f;
L_0x0128:
r13.m2415e();
goto L_0x001f;
L_0x012d:
r0 = 0;
goto L_0x0025;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v4.widget.ad.a(android.view.MotionEvent):boolean");
}
public boolean m2402a(View view, int i, int i2) {
this.f1086s = view;
this.f1070c = -1;
boolean a = m2385a(i, i2, 0, 0);
if (!(a || this.f1068a != 0 || this.f1086s == null)) {
this.f1086s = null;
}
return a;
}
public boolean m2403a(boolean z) {
if (this.f1068a == 2) {
int i;
boolean g = this.f1084q.m2525g();
int b = this.f1084q.m2520b();
int c = this.f1084q.m2521c();
int left = b - this.f1086s.getLeft();
int top = c - this.f1086s.getTop();
if (left != 0) {
aj.m1882e(this.f1086s, left);
}
if (top != 0) {
aj.m1880d(this.f1086s, top);
}
if (!(left == 0 && top == 0)) {
this.f1085r.m222a(this.f1086s, b, c, left, top);
}
if (g && b == this.f1084q.m2522d() && c == this.f1084q.m2523e()) {
this.f1084q.m2526h();
i = 0;
} else {
boolean z2 = g;
}
if (i == 0) {
if (z) {
this.f1088u.post(this.f1089w);
} else {
m2405b(0);
}
}
}
return this.f1068a == 2;
}
public int m2404b() {
return this.f1082o;
}
void m2405b(int i) {
this.f1088u.removeCallbacks(this.f1089w);
if (this.f1068a != i) {
this.f1068a = i;
this.f1085r.m219a(i);
if (this.f1068a == 0) {
this.f1086s = null;
}
}
}
public void m2406b(MotionEvent motionEvent) {
int i = 0;
int a = C0534t.m2226a(motionEvent);
int b = C0534t.m2227b(motionEvent);
if (a == 0) {
m2415e();
}
if (this.f1079l == null) {
this.f1079l = VelocityTracker.obtain();
}
this.f1079l.addMovement(motionEvent);
float x;
float y;
View d;
int i2;
switch (a) {
case GoogleMap.MAP_TYPE_NONE /*0*/:
x = motionEvent.getX();
y = motionEvent.getY();
i = motionEvent.getPointerId(0);
d = m2414d((int) x, (int) y);
m2383a(x, y, i);
m2408b(d, i);
i2 = this.f1075h[i];
if ((this.f1083p & i2) != 0) {
this.f1085r.m220a(i2 & this.f1083p, i);
}
case GoogleMap.MAP_TYPE_NORMAL /*1*/:
if (this.f1068a == 1) {
m2396g();
}
m2415e();
case GoogleMap.MAP_TYPE_SATELLITE /*2*/:
if (this.f1068a != 1) {
i2 = motionEvent.getPointerCount();
while (i < i2) {
a = motionEvent.getPointerId(i);
if (m2395f(a)) {
float x2 = motionEvent.getX(i);
float y2 = motionEvent.getY(i);
float f = x2 - this.f1071d[a];
float f2 = y2 - this.f1072e[a];
m2388b(f, f2, a);
if (this.f1068a != 1) {
d = m2414d((int) x2, (int) y2);
if (m2386a(d, f, f2) && m2408b(d, a)) {
}
}
m2390c(motionEvent);
}
i++;
}
m2390c(motionEvent);
} else if (m2395f(this.f1070c)) {
i = motionEvent.findPointerIndex(this.f1070c);
x = motionEvent.getX(i);
i2 = (int) (x - this.f1073f[this.f1070c]);
i = (int) (motionEvent.getY(i) - this.f1074g[this.f1070c]);
m2389b(this.f1086s.getLeft() + i2, this.f1086s.getTop() + i, i2, i);
m2390c(motionEvent);
}
case GoogleMap.MAP_TYPE_TERRAIN /*3*/:
if (this.f1068a == 1) {
m2382a(0.0f, 0.0f);
}
m2415e();
case C1096c.MapAttrs_cameraZoom /*5*/:
i = motionEvent.getPointerId(b);
x = motionEvent.getX(b);
y = motionEvent.getY(b);
m2383a(x, y, i);
if (this.f1068a == 0) {
m2408b(m2414d((int) x, (int) y), i);
i2 = this.f1075h[i];
if ((this.f1083p & i2) != 0) {
this.f1085r.m220a(i2 & this.f1083p, i);
}
} else if (m2412c((int) x, (int) y)) {
m2408b(this.f1086s, i);
}
case C1096c.MapAttrs_liteMode /*6*/:
a = motionEvent.getPointerId(b);
if (this.f1068a == 1 && a == this.f1070c) {
b = motionEvent.getPointerCount();
while (i < b) {
int pointerId = motionEvent.getPointerId(i);
if (pointerId != this.f1070c) {
if (m2414d((int) motionEvent.getX(i), (int) motionEvent.getY(i)) == this.f1086s && m2408b(this.f1086s, pointerId)) {
i = this.f1070c;
if (i == -1) {
m2396g();
}
}
}
i++;
}
i = -1;
if (i == -1) {
m2396g();
}
}
m2391d(a);
default:
}
}
public boolean m2407b(int i, int i2) {
if (!m2399a(i2)) {
return false;
}
boolean z = (i & 1) == 1;
boolean z2 = (i & 2) == 2;
float f = this.f1073f[i2] - this.f1071d[i2];
float f2 = this.f1074g[i2] - this.f1072e[i2];
return (z && z2) ? (f * f) + (f2 * f2) > ((float) (this.f1069b * this.f1069b)) : z ? Math.abs(f) > ((float) this.f1069b) : z2 ? Math.abs(f2) > ((float) this.f1069b) : false;
}
boolean m2408b(View view, int i) {
if (view == this.f1086s && this.f1070c == i) {
return true;
}
if (view == null || !this.f1085r.m223a(view, i)) {
return false;
}
this.f1070c = i;
m2398a(view, i);
return true;
}
public boolean m2409b(View view, int i, int i2) {
return view != null && i >= view.getLeft() && i < view.getRight() && i2 >= view.getTop() && i2 < view.getBottom();
}
public View m2410c() {
return this.f1086s;
}
public boolean m2411c(int i) {
int length = this.f1071d.length;
for (int i2 = 0; i2 < length; i2++) {
if (m2407b(i, i2)) {
return true;
}
}
return false;
}
public boolean m2412c(int i, int i2) {
return m2409b(this.f1086s, i, i2);
}
public int m2413d() {
return this.f1069b;
}
public View m2414d(int i, int i2) {
for (int childCount = this.f1088u.getChildCount() - 1; childCount >= 0; childCount--) {
View childAt = this.f1088u.getChildAt(this.f1085r.m229c(childCount));
if (i >= childAt.getLeft() && i < childAt.getRight() && i2 >= childAt.getTop() && i2 < childAt.getBottom()) {
return childAt;
}
}
return null;
}
public void m2415e() {
this.f1070c = -1;
m2394f();
if (this.f1079l != null) {
this.f1079l.recycle();
this.f1079l = null;
}
}
}
| 31.35119 | 277 | 0.476932 |
0e2bd7f40976ea15b6dacb9fcb5499fb19d8c294 | 5,176 | package org.chenile.stm.model;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.chenile.stm.STMFlowStore;
import org.chenile.stm.State;
import org.chenile.stm.action.STMAction;
import org.chenile.stm.exception.STMException;
import java.util.Set;
public class StateDescriptor implements TransientActionsAwareDescriptor{
protected String id;
protected boolean initialState;
protected STMAction<?> entryAction;
protected boolean finalState;
protected Map<String,String> metadata = new HashMap<String, String>();
public boolean isFinalState() {
return finalState;
}
public void addMetaData(String name, String value){
metadata.put(name, value);
}
public Map<String, String> getMetadata(){
return Collections.unmodifiableMap(metadata);
}
public void setFinalState(boolean endState) {
this.finalState = endState;
}
public STMAction<?> getEntryAction() {
return entryAction;
}
public void setEntryAction(STMAction<?> entryAction) {
this.entryAction = entryAction;
}
public STMAction<?> getExitAction() {
return exitAction;
}
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
public void setExitAction(STMAction<?> exitAction) {
this.exitAction = exitAction;
}
protected STMAction<?> exitAction;
/**
* Is this state manual? (or a view state?)
*/
protected boolean manualState = false;
public boolean isManualState() {
return manualState;
}
public void setManualState(boolean manualState) {
this.manualState = manualState;
}
private Map<String,Transition> transitions = new HashMap<String, Transition>();
private String flowId;
public String getFlowId() {
return flowId;
}
public void setFlowId(String flowId) {
this.flowId = flowId;
}
public StateDescriptor() {
super();
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setInitialState(boolean initialState) {
this.initialState = initialState;
}
public boolean isInitialState() {
return initialState;
}
public void setTransitions(Map<String,Transition> transitions) {
this.transitions = transitions;
}
// @XmlTransient
public Map<String,Transition> getTransitions() {
return transitions;
}
public void addTransition(Transition transition) throws STMException {
// ensure that the transitions have explicit newStateId etc.
if(transition.getNewFlowId() == null) transition.setNewFlowId(this.flowId);
if (transition.getNewStateId() == null) transition.setNewStateId(this.id);
// for retrieval transitions the new state cannot be the same as the old state
if (transition.isRetrievalTransition() && transition.getNewStateId().equals(this.id)){
throw new STMException("Retrieval transitions must have a \"to state\" that is different from the \"from state\"",
STMException.INVALID_TRANSITION);
}
transitions.put(transition.getEventId(), transition);
}
@Override
public String toString() {
return "StateDescriptor [id=" + id + ", initialState=" + initialState
+ ", transitions=" + transitions + "]";
}
public boolean checkIfonlyRetrievalTransitions() {
for (Transition t: transitions.values()){
if(!t.isRetrievalTransition()) return false;
}
return true;
}
public void validate() throws STMException{
for (Transition t: transitions.values()){
if(t.isRetrievalTransition() && transitions.size() != 1) {
throw new STMException("Invalid state definition for id " + id,STMException.INVALID_STATE);
}
}
}
public void validate(STMFlowStore flowStore) throws STMException{
validate();
for (Transition t: transitions.values()){
// make sure that each transition points to a new state that is defined in the state machine
State newState = new State(t.getNewStateId(),t.getNewFlowId());
StateDescriptor s = flowStore.getStateInfo(newState);
if (s == null)
throw new STMException("New State " + newState + " pointed by transition " + t.getEventId() +
" is not defined in the flow store.", STMException.INVALID_STATE,new State(getId(),getFlowId()));
}
}
public Set<String> getAllTransitionsIds(){
return transitions.keySet();
}
public void merge(StateDescriptor sd) {
if (exitAction != null && sd.getExitAction() != null){
System.err.println("Warning: Exit action of " + sd.getId() + " seems to be duplicated!!");
}
if (sd.getTransitions() != null)
this.transitions.putAll(sd.getTransitions()); // merge the transitions
if (transitions != null && transitions.size() > 0 )
this.finalState = false;
else
this.finalState = true;
}
public String toXml(){
StringBuilder sb = new StringBuilder();
sb.append("<state>\n");
sb.append("<id>" + id + "</id>\n");
sb.append("<metadata>\n");
for(Entry<String, String> entry:metadata.entrySet()){
sb.append("<"+entry.getKey()+" value="+entry.getValue()+">\n");
}
sb.append("</metadata>\n");
sb.append("<transitions>");
for (Transition t: transitions.values()){
sb.append(t.toXml());
}
sb.append("</transitions>");
sb.append("</state>\n");
return sb.toString();
}
} | 26.408163 | 117 | 0.710781 |
2c126311764f16c9f15a42d0afa0987218dde982 | 2,575 | package edu.wpi.first.smartdashboard;
import edu.wpi.first.smartdashboard.gui.DashboardFrame;
import edu.wpi.first.smartdashboard.robot.Robot;
import edu.wpi.first.wpilibj.tables.ITable;
import edu.wpi.first.wpilibj.tables.ITableListener;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
/**
* Logs all information received to a CSV file.
*
* @author pmalmsten
*/
public class LogToCSV implements ITableListener {
private static final String s_lineSeparator = System.getProperty("line.separator");
private long m_startTime;
private FileWriter m_fw;
private final DashboardFrame frame;
public LogToCSV(DashboardFrame frame) {
this.frame = frame;
}
/*
* Prepares this LogToCSV object to begin writing to the specified file. The
* specified file is opened in write mode (any existing content is blown
* away).
*
* @param path The path of the CSV file to write to.
*/
public void start(String path) {
if (m_fw == null) {
try {
m_startTime = System.currentTimeMillis();
m_fw = new FileWriter(path);
m_fw.write("Time (ms),Name,Value" + s_lineSeparator);
m_fw.flush();
Robot.getTable().addTableListenerEx(this,
ITable.NOTIFY_IMMEDIATE | ITable.NOTIFY_LOCAL | ITable.NOTIFY_NEW
| ITable.NOTIFY_UPDATE);
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null,
"An error occurred when attempting to " + "open the output CSV file for writing. "
+ "Please check the file path preference.", "Unable to Open CSV File",
JOptionPane.ERROR_MESSAGE);
frame.getPrefs().logToCSV.setValue(false);
}
}
}
/*
* If logging was previously enabled, this method flushes and releases the
* file handle to the CSV file. Logging will no longer occur.
*/
public void stop() {
if (m_fw == null) {
return;
}
try {
m_fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
Robot.getTable().removeTableListener(this);
m_fw = null;
}
@Override
public void valueChanged(ITable source, String key, Object value, boolean isNew) {
if (!(value instanceof ITable) && m_fw != null) {
try {
long timeStamp = System.currentTimeMillis() - m_startTime;
m_fw.write(timeStamp + "," + "\"" + key + "\"," + "\"" + value + "\"" + s_lineSeparator);
m_fw.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
| 29.94186 | 97 | 0.648932 |
1e5239f709b63c928663a724b015da22599177a8 | 1,026 | package com.decompiler.entities.constantpool;
import com.decompiler.bytecode.analysis.types.StackType;
import com.decompiler.entities.AbstractConstantPoolEntry;
import com.decompiler.util.bytestream.ByteData;
import com.decompiler.util.output.Dumper;
public class ConstantPoolEntryInteger extends AbstractConstantPoolEntry implements ConstantPoolEntryLiteral {
private static final long OFFSET_OF_BYTES = 1;
private final int value;
public ConstantPoolEntryInteger(ConstantPool cp, ByteData data) {
super(cp);
this.value = data.getS4At(OFFSET_OF_BYTES);
}
@Override
public long getRawByteLength() {
return 5;
}
@Override
public void dump(Dumper d) {
d.print("CONSTANT_Integer value=" + value);
}
public int getValue() {
return value;
}
@Override
public StackType getStackType() {
return StackType.INT;
}
@Override
public String toString() {
return ("CONSTANT_Integer value=" + value);
}
}
| 24.428571 | 109 | 0.69883 |
6b1e17fd88571006ea3f0f30b69ac1efa073f4c8 | 1,126 | package com.google.android.gms.internal.ads;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
/* compiled from: com.google.android.gms:play-services-ads-lite@@19.4.0 */
public abstract class zzyg extends zzgt implements zzyh {
public zzyg() {
super("com.google.android.gms.ads.internal.client.IOnAdMetadataChangedListener");
}
public static zzyh zzh(IBinder iBinder) {
if (iBinder == null) {
return null;
}
IInterface queryLocalInterface = iBinder.queryLocalInterface("com.google.android.gms.ads.internal.client.IOnAdMetadataChangedListener");
if (queryLocalInterface instanceof zzyh) {
return (zzyh) queryLocalInterface;
}
return new zzyj(iBinder);
}
/* access modifiers changed from: protected */
public final boolean zza(int i, Parcel parcel, Parcel parcel2, int i2) throws RemoteException {
if (i != 1) {
return false;
}
onAdMetadataChanged();
parcel2.writeNoException();
return true;
}
}
| 32.171429 | 144 | 0.668739 |
f6f198e6835d169b59261759dd840281851b9d99 | 2,537 | package net.qiujuer.widget.airpanel;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
/**
* @author qiujuer Email:qiujuer@live.cn
* @version 1.0.0
*/
@SuppressWarnings("WeakerAccess")
public final class Util {
public static boolean DEBUG = BuildConfig.DEBUG;
public static void log(String format, Object... args) {
if (DEBUG)
Log.d("AirPanel", String.format(format, args));
}
public static void showKeyboard(final View view) {
view.requestFocus();
InputMethodManager inputManager =
(InputMethodManager) view.getContext().getSystemService(
Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(view, 0);
}
public static void hideKeyboard(final View view) {
InputMethodManager imm =
(InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
static int getDefaultPanelHeight(Context context, AirAttribute attribute) {
int defaultHeight = (int) ((attribute.panelMaxHeight + attribute.panelMinHeight) * 0.5f);
defaultHeight = PanelSharedPreferences.get(context, defaultHeight);
return defaultHeight;
}
static void updateLocalPanelHeight(Context context, int height) {
PanelSharedPreferences.save(context, height);
}
private static class PanelSharedPreferences {
private final static String FILE_NAME = "AirPanel.sp";
private final static String KEY_PANEL_HEIGHT = "panelHeight";
private volatile static SharedPreferences SP;
public static void save(final Context context, final int keyboardHeight) {
sp(context).edit()
.putInt(KEY_PANEL_HEIGHT, keyboardHeight)
.apply();
}
private static SharedPreferences sp(final Context context) {
if (SP == null) {
synchronized (PanelSharedPreferences.class) {
if (SP == null) {
SP = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
}
}
}
return SP;
}
public static int get(final Context context, final int defaultHeight) {
return sp(context).getInt(KEY_PANEL_HEIGHT, defaultHeight);
}
}
}
| 34.283784 | 102 | 0.646039 |
1500cab9364be9b1853f0c98a62890542a6df14b | 4,966 | package com.itracker.android.ui.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.itracker.android.R;
import com.itracker.android.utils.LogUtils;
import java.util.ArrayList;
/**
* Created by bbo on 1/15/16.
*/
public class TimelinesView extends RelativeLayout {
public static final String TAG = LogUtils.makeLogTag(TimelinesView.class);
private final int DEFAULT_OVERSCROLL_SIZE = 32;
private View mOverScrollView;
private TextView mEmptyView;
private ListView mListView;
private View mShadowOverlay;
private int mOverScrollSize;
private Drawable mOverScrollBackground;
public TimelinesView(Context context) {
this(context, null);
}
public TimelinesView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TimelinesView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TimelinesView, defStyleAttr, 0);
mOverScrollSize = a.getDimensionPixelSize(R.styleable.TimelinesView_overScrollSize, dpToPx(context, DEFAULT_OVERSCROLL_SIZE));
mOverScrollBackground = a.getDrawable(R.styleable.TimelinesView_overScrollBackground);
a.recycle();
initViews();
}
public ListView getListView() {
return mListView;
}
public View getContentView() {
ListAdapter adapter = mListView.getAdapter();
if (adapter != null && adapter.getCount() > 0) {
return mListView;
}
return mEmptyView;
}
public View getOverScrollView() {
return mOverScrollView;
}
private void initViews() {
mOverScrollView = new View(getContext());
mOverScrollView.setId(generateViewId());
int padding = dpToPx(getContext(), 16);
mEmptyView = new TextView(getContext());
mEmptyView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mEmptyView.setId(android.R.id.empty);
mEmptyView.setGravity(Gravity.CENTER);
mEmptyView.setPadding(padding, padding, padding, padding);
mEmptyView.setText(R.string.need_time_for_timelines);
mListView = new ListView(getContext());
mListView.setId(generateViewId());
mListView.setDivider(null);
mListView.setEmptyView(mEmptyView);
mShadowOverlay = new View(getContext());
mShadowOverlay.setId(generateViewId());
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mOverScrollSize);
params.addRule(ALIGN_PARENT_TOP);
mOverScrollView.setLayoutParams(params);
mOverScrollView.setBackground(mOverScrollBackground);
params = new LayoutParams(LayoutParams.MATCH_PARENT, dpToPx(getContext(), 16));
params.addRule(ALIGN_PARENT_BOTTOM);
mShadowOverlay.setLayoutParams(params);
mShadowOverlay.setBackground(getResources().getDrawable(R.drawable.timelinesview_bottom_shadow));
params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.addRule(BELOW, mOverScrollView.getId());
params.addRule(ALIGN_PARENT_BOTTOM);
mListView.setLayoutParams(params);
mEmptyView.setLayoutParams(params);
addView(mOverScrollView);
addView(mListView);
addView(mEmptyView);
addView(mShadowOverlay);
}
public static class TimelineItemAdapter extends ArrayAdapter<TimelineItem.Timeline> {
public TimelineItemAdapter(Context context) {
super(context, 0, new ArrayList<>());
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TimelineItem itemView = (TimelineItem) convertView;
if (itemView == null) {
itemView = (TimelineItem) LayoutInflater.from(getContext()).inflate(R.layout.item_timeline, parent, false);
itemView.init();
}
itemView.populateView(getItem(position), position == getCount() - 1);
return itemView;
}
public void selectItem(int position) {
for (int i = 0; i < getCount(); ++i) {
TimelineItem.Timeline timeline = getItem(i);
timeline.select(i == position);
}
}
}
private static int dpToPx(Context context, int dps) {
return Math.round(context.getResources().getDisplayMetrics().density * dps);
}
}
| 34.013699 | 134 | 0.687878 |
1a607762ed7a316d3acff267a92113456d36106e | 28,254 | /*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* 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.optaplanner.examples.vehiclerouting.persistence;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FilenameUtils;
import org.optaplanner.examples.common.persistence.AbstractTxtSolutionImporter;
import org.optaplanner.examples.vehiclerouting.domain.Customer;
import org.optaplanner.examples.vehiclerouting.domain.Depot;
import org.optaplanner.examples.vehiclerouting.domain.Vehicle;
import org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution;
import org.optaplanner.examples.vehiclerouting.domain.location.AirLocation;
import org.optaplanner.examples.vehiclerouting.domain.location.DistanceType;
import org.optaplanner.examples.vehiclerouting.domain.location.Location;
import org.optaplanner.examples.vehiclerouting.domain.location.RoadLocation;
import org.optaplanner.examples.vehiclerouting.domain.location.segmented.HubSegmentLocation;
import org.optaplanner.examples.vehiclerouting.domain.location.segmented.RoadSegmentLocation;
import org.optaplanner.examples.vehiclerouting.domain.timewindowed.TimeWindowedCustomer;
import org.optaplanner.examples.vehiclerouting.domain.timewindowed.TimeWindowedDepot;
import org.optaplanner.examples.vehiclerouting.domain.timewindowed.TimeWindowedVehicleRoutingSolution;
public class VehicleRoutingImporter extends AbstractTxtSolutionImporter<VehicleRoutingSolution> {
public static void main(String[] args) {
VehicleRoutingImporter importer = new VehicleRoutingImporter();
importer.convert("vrpweb/basic/air/A-n33-k6.vrp", "cvrp-32customers.xml");
importer.convert("vrpweb/basic/air/A-n55-k9.vrp", "cvrp-54customers.xml");
importer.convert("vrpweb/basic/air/F-n72-k4.vrp", "cvrp-72customers.xml");
importer.convert("vrpweb/timewindowed/air/Solomon_025_C101.vrp", "cvrptw-25customers.xml");
importer.convert("vrpweb/timewindowed/air/Solomon_100_R101.vrp", "cvrptw-100customers-A.xml");
importer.convert("vrpweb/timewindowed/air/Solomon_100_R201.vrp", "cvrptw-100customers-B.xml");
importer.convert("vrpweb/timewindowed/air/Homberger_0400_R1_4_1.vrp", "cvrptw-400customers.xml");
importer.convert("vrpweb/basic/road-unknown/bays-n29-k5.vrp", "road-cvrp-29customers.xml");
}
public VehicleRoutingImporter() {
super(new VehicleRoutingDao());
}
public VehicleRoutingImporter(boolean withoutDao) {
super(withoutDao);
}
@Override
public String getInputFileSuffix() {
return VehicleRoutingFileIO.FILE_EXTENSION;
}
@Override
public TxtInputBuilder<VehicleRoutingSolution> createTxtInputBuilder() {
return new VehicleRoutingInputBuilder();
}
public static class VehicleRoutingInputBuilder extends TxtInputBuilder<VehicleRoutingSolution> {
private VehicleRoutingSolution solution;
private boolean timewindowed;
private int customerListSize;
private int vehicleListSize;
private int capacity;
private Map<Long, Location> locationMap;
private List<Depot> depotList;
@Override
public VehicleRoutingSolution readSolution() throws IOException {
String firstLine = readStringValue();
if (firstLine.matches("\\s*NAME\\s*:.*")) {
// Might be replaced by TimeWindowedVehicleRoutingSolution later on
solution = new VehicleRoutingSolution();
solution.setId(0L);
solution.setName(removePrefixSuffixFromLine(firstLine, "\\s*NAME\\s*:", ""));
readVrpWebFormat();
} else if (splitBySpacesOrTabs(firstLine).length == 3) {
timewindowed = false;
solution = new VehicleRoutingSolution();
solution.setId(0L);
solution.setName(FilenameUtils.getBaseName(inputFile.getName()));
String[] tokens = splitBySpacesOrTabs(firstLine, 3);
customerListSize = Integer.parseInt(tokens[0]);
vehicleListSize = Integer.parseInt(tokens[1]);
capacity = Integer.parseInt(tokens[2]);
readCourseraFormat();
} else {
timewindowed = true;
solution = new TimeWindowedVehicleRoutingSolution();
solution.setId(0L);
solution.setName(firstLine);
readTimeWindowedFormat();
}
BigInteger possibleSolutionSize
= factorial(customerListSize + vehicleListSize - 1).divide(factorial(vehicleListSize - 1));
logger.info("VehicleRoutingSolution {} has {} depots, {} vehicles and {} customers with a search space of {}.",
getInputId(),
solution.getDepotList().size(),
solution.getVehicleList().size(),
solution.getCustomerList().size(),
getFlooredPossibleSolutionSize(possibleSolutionSize));
return solution;
}
// ************************************************************************
// CVRP normal format. See http://neo.lcc.uma.es/vrp/
// ************************************************************************
public void readVrpWebFormat() throws IOException {
readVrpWebHeaders();
readVrpWebLocationList();
readVrpWebCustomerList();
readVrpWebDepotList();
createVrpWebVehicleList();
readConstantLine("EOF");
}
private void readVrpWebHeaders() throws IOException {
skipOptionalConstantLines("COMMENT *:.*");
String vrpType = readStringValue("TYPE *:");
switch (vrpType) {
case "CVRP":
timewindowed = false;
break;
case "CVRPTW":
timewindowed = true;
Long solutionId = solution.getId();
String solutionName = solution.getName();
solution = new TimeWindowedVehicleRoutingSolution();
solution.setId(solutionId);
solution.setName(solutionName);
break;
default:
throw new IllegalArgumentException("The vrpType (" + vrpType + ") is not supported.");
}
customerListSize = readIntegerValue("DIMENSION *:");
String edgeWeightType = readStringValue("EDGE_WEIGHT_TYPE *:");
if (edgeWeightType.equalsIgnoreCase("EUC_2D")) {
solution.setDistanceType(DistanceType.AIR_DISTANCE);
} else if (edgeWeightType.equalsIgnoreCase("EXPLICIT")) {
solution.setDistanceType(DistanceType.ROAD_DISTANCE);
String edgeWeightFormat = readStringValue("EDGE_WEIGHT_FORMAT *:");
if (!edgeWeightFormat.equalsIgnoreCase("FULL_MATRIX")) {
throw new IllegalArgumentException("The edgeWeightFormat (" + edgeWeightFormat + ") is not supported.");
}
} else if (edgeWeightType.equalsIgnoreCase("SEGMENTED_EXPLICIT")) {
solution.setDistanceType(DistanceType.SEGMENTED_ROAD_DISTANCE);
String edgeWeightFormat = readStringValue("EDGE_WEIGHT_FORMAT *:");
if (!edgeWeightFormat.equalsIgnoreCase("HUB_AND_NEARBY_MATRIX")) {
throw new IllegalArgumentException("The edgeWeightFormat (" + edgeWeightFormat + ") is not supported.");
}
} else {
throw new IllegalArgumentException("The edgeWeightType (" + edgeWeightType + ") is not supported.");
}
solution.setDistanceUnitOfMeasurement(readOptionalStringValue("EDGE_WEIGHT_UNIT_OF_MEASUREMENT *:", "distance"));
capacity = readIntegerValue("CAPACITY *:");
}
private void readVrpWebLocationList() throws IOException {
DistanceType distanceType = solution.getDistanceType();
List<HubSegmentLocation> hubLocationList = null;
locationMap = new LinkedHashMap<>(customerListSize);
if (distanceType == DistanceType.SEGMENTED_ROAD_DISTANCE) {
int hubListSize = readIntegerValue("HUBS *:");
hubLocationList = new ArrayList<>(hubListSize);
readConstantLine("HUB_COORD_SECTION");
for (int i = 0; i < hubListSize; i++) {
String line = bufferedReader.readLine();
String[] lineTokens = splitBySpacesOrTabs(line.trim(), 3, 4);
HubSegmentLocation location = new HubSegmentLocation();
location.setId(Long.parseLong(lineTokens[0]));
location.setLatitude(Double.parseDouble(lineTokens[1]));
location.setLongitude(Double.parseDouble(lineTokens[2]));
if (lineTokens.length >= 4) {
location.setName(lineTokens[3]);
}
hubLocationList.add(location);
locationMap.put(location.getId(), location);
}
}
List<Location> customerLocationList = new ArrayList<>(customerListSize);
readConstantLine("NODE_COORD_SECTION");
for (int i = 0; i < customerListSize; i++) {
String line = bufferedReader.readLine();
String[] lineTokens = splitBySpacesOrTabs(line.trim(), 3, 4);
Location location;
switch (distanceType) {
case AIR_DISTANCE:
location = new AirLocation();
break;
case ROAD_DISTANCE:
location = new RoadLocation();
break;
case SEGMENTED_ROAD_DISTANCE:
location = new RoadSegmentLocation();
break;
default:
throw new IllegalStateException("The distanceType (" + distanceType
+ ") is not implemented.");
}
location.setId(Long.parseLong(lineTokens[0]));
location.setLatitude(Double.parseDouble(lineTokens[1]));
location.setLongitude(Double.parseDouble(lineTokens[2]));
if (lineTokens.length >= 4) {
location.setName(lineTokens[3]);
}
customerLocationList.add(location);
locationMap.put(location.getId(), location);
}
if (distanceType == DistanceType.ROAD_DISTANCE) {
readConstantLine("EDGE_WEIGHT_SECTION");
for (int i = 0; i < customerListSize; i++) {
RoadLocation location = (RoadLocation) customerLocationList.get(i);
Map<RoadLocation, Double> travelDistanceMap = new LinkedHashMap<>(customerListSize);
String line = bufferedReader.readLine();
String[] lineTokens = splitBySpacesOrTabs(line.trim(), customerListSize);
for (int j = 0; j < customerListSize; j++) {
double travelDistance = Double.parseDouble(lineTokens[j]);
if (i == j) {
if (travelDistance != 0.0) {
throw new IllegalStateException("The travelDistance (" + travelDistance
+ ") should be zero.");
}
} else {
RoadLocation otherLocation = (RoadLocation) customerLocationList.get(j);
travelDistanceMap.put(otherLocation, travelDistance);
}
}
location.setTravelDistanceMap(travelDistanceMap);
}
}
if (distanceType == DistanceType.SEGMENTED_ROAD_DISTANCE) {
readConstantLine("SEGMENTED_EDGE_WEIGHT_SECTION");
int locationListSize = hubLocationList.size() + customerListSize;
for (int i = 0; i < locationListSize; i++) {
String line = bufferedReader.readLine();
String[] lineTokens = splitBySpacesOrTabs(line.trim(), 3, null);
if (lineTokens.length % 2 != 1) {
throw new IllegalArgumentException("Invalid SEGMENTED_EDGE_WEIGHT_SECTION line (" + line + ").");
}
long id = Long.parseLong(lineTokens[0]);
Location location = locationMap.get(id);
if (location == null) {
throw new IllegalArgumentException("The location with id (" + id + ") of line (" + line + ") does not exist.");
}
Map<HubSegmentLocation, Double> hubTravelDistanceMap = new LinkedHashMap<>(lineTokens.length / 2);
Map<RoadSegmentLocation, Double> nearbyTravelDistanceMap = new LinkedHashMap<>(lineTokens.length / 2);
for (int j = 1; j < lineTokens.length; j += 2) {
Location otherLocation = locationMap.get(Long.parseLong(lineTokens[j]));
double travelDistance = Double.parseDouble(lineTokens[j + 1]);
if (otherLocation instanceof HubSegmentLocation) {
hubTravelDistanceMap.put((HubSegmentLocation) otherLocation, travelDistance);
} else {
nearbyTravelDistanceMap.put((RoadSegmentLocation) otherLocation, travelDistance);
}
}
if (location instanceof HubSegmentLocation) {
HubSegmentLocation hubSegmentLocation = (HubSegmentLocation) location;
hubSegmentLocation.setHubTravelDistanceMap(hubTravelDistanceMap);
hubSegmentLocation.setNearbyTravelDistanceMap(nearbyTravelDistanceMap);
} else {
RoadSegmentLocation roadSegmentLocation = (RoadSegmentLocation) location;
roadSegmentLocation.setHubTravelDistanceMap(hubTravelDistanceMap);
roadSegmentLocation.setNearbyTravelDistanceMap(nearbyTravelDistanceMap);
}
}
}
List<Location> locationList;
if (distanceType == DistanceType.SEGMENTED_ROAD_DISTANCE) {
locationList = new ArrayList<>(hubLocationList.size() + customerListSize);
locationList.addAll(hubLocationList);
locationList.addAll(customerLocationList);
} else {
locationList = customerLocationList;
}
solution.setLocationList(locationList);
}
private void readVrpWebCustomerList() throws IOException {
readConstantLine("DEMAND_SECTION");
depotList = new ArrayList<>(customerListSize);
List<Customer> customerList = new ArrayList<>(customerListSize);
for (int i = 0; i < customerListSize; i++) {
String line = bufferedReader.readLine();
String[] lineTokens = splitBySpacesOrTabs(line.trim(), timewindowed ? 5 : 2);
long id = Long.parseLong(lineTokens[0]);
int demand = Integer.parseInt(lineTokens[1]);
// Depots have no demand
if (demand == 0) {
Depot depot = timewindowed ? new TimeWindowedDepot() : new Depot();
depot.setId(id);
Location location = locationMap.get(id);
if (location == null) {
throw new IllegalArgumentException("The depot with id (" + id
+ ") has no location (" + location + ").");
}
depot.setLocation(location);
if (timewindowed) {
TimeWindowedDepot timeWindowedDepot = (TimeWindowedDepot) depot;
timeWindowedDepot.setReadyTime(Long.parseLong(lineTokens[2]));
timeWindowedDepot.setDueTime(Long.parseLong(lineTokens[3]));
long serviceDuration = Long.parseLong(lineTokens[4]);
if (serviceDuration != 0L) {
throw new IllegalArgumentException("The depot with id (" + id
+ ") has a serviceDuration (" + serviceDuration + ") that is not 0.");
}
}
depotList.add(depot);
} else {
Customer customer = timewindowed ? new TimeWindowedCustomer() : new Customer();
customer.setId(id);
Location location = locationMap.get(id);
if (location == null) {
throw new IllegalArgumentException("The customer with id (" + id
+ ") has no location (" + location + ").");
}
customer.setLocation(location);
customer.setDemand(demand);
if (timewindowed) {
TimeWindowedCustomer timeWindowedCustomer = (TimeWindowedCustomer) customer;
timeWindowedCustomer.setReadyTime(Long.parseLong(lineTokens[2]));
timeWindowedCustomer.setDueTime(Long.parseLong(lineTokens[3]));
timeWindowedCustomer.setServiceDuration(Long.parseLong(lineTokens[4]));
}
// Notice that we leave the PlanningVariable properties on null
customerList.add(customer);
}
}
solution.setCustomerList(customerList);
solution.setDepotList(depotList);
}
private void readVrpWebDepotList() throws IOException {
readConstantLine("DEPOT_SECTION");
int depotCount = 0;
long id = readLongValue();
while (id != -1) {
depotCount++;
id = readLongValue();
}
if (depotCount != depotList.size()) {
throw new IllegalStateException("The number of demands with 0 demand (" + depotList.size()
+ ") differs from the number of depots (" + depotCount + ").");
}
}
private void createVrpWebVehicleList() throws IOException {
String inputFileName = inputFile.getName();
if (inputFileName.toLowerCase().startsWith("tutorial")) {
vehicleListSize = readIntegerValue("VEHICLES *:");
} else {
String inputFileNameRegex = "^.+\\-k(\\d+)\\.vrp$";
if (!inputFileName.matches(inputFileNameRegex)) {
throw new IllegalArgumentException("The inputFileName (" + inputFileName
+ ") does not match the inputFileNameRegex (" + inputFileNameRegex + ").");
}
String vehicleListSizeString = inputFileName.replaceAll(inputFileNameRegex, "$1");
try {
vehicleListSize = Integer.parseInt(vehicleListSizeString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("The inputFileName (" + inputFileName
+ ") has a vehicleListSizeString (" + vehicleListSizeString + ") that is not a number.", e);
}
}
createVehicleList();
}
private void createVehicleList() {
List<Vehicle> vehicleList = new ArrayList<>(vehicleListSize);
long id = 0;
for (int i = 0; i < vehicleListSize; i++) {
Vehicle vehicle = new Vehicle();
vehicle.setId(id);
id++;
vehicle.setCapacity(capacity);
vehicle.setDepot(depotList.get(0));
vehicleList.add(vehicle);
}
solution.setVehicleList(vehicleList);
}
// ************************************************************************
// CVRP coursera format. See https://class.coursera.org/optimization-001/
// ************************************************************************
public void readCourseraFormat() throws IOException {
solution.setDistanceType(DistanceType.AIR_DISTANCE);
solution.setDistanceUnitOfMeasurement("distance");
List<Location> locationList = new ArrayList<>(customerListSize);
depotList = new ArrayList<>(1);
List<Customer> customerList = new ArrayList<>(customerListSize);
locationMap = new LinkedHashMap<>(customerListSize);
for (int i = 0; i < customerListSize; i++) {
String line = bufferedReader.readLine();
String[] lineTokens = splitBySpacesOrTabs(line.trim(), 3, 4);
AirLocation location = new AirLocation();
location.setId((long) i);
location.setLatitude(Double.parseDouble(lineTokens[1]));
location.setLongitude(Double.parseDouble(lineTokens[2]));
if (lineTokens.length >= 4) {
location.setName(lineTokens[3]);
}
locationList.add(location);
if (i == 0) {
Depot depot = new Depot();
depot.setId((long) i);
depot.setLocation(location);
depotList.add(depot);
} else {
Customer customer = new Customer();
customer.setId((long) i);
customer.setLocation(location);
int demand = Integer.parseInt(lineTokens[0]);
customer.setDemand(demand);
// Notice that we leave the PlanningVariable properties on null
// Do not add a customer that has no demand
if (demand != 0) {
customerList.add(customer);
}
}
}
solution.setLocationList(locationList);
solution.setDepotList(depotList);
solution.setCustomerList(customerList);
createVehicleList();
}
// ************************************************************************
// CVRPTW normal format. See http://neo.lcc.uma.es/vrp/
// ************************************************************************
public void readTimeWindowedFormat() throws IOException {
readTimeWindowedHeaders();
readTimeWindowedDepotAndCustomers();
createVehicleList();
}
private void readTimeWindowedHeaders() throws IOException {
solution.setDistanceType(DistanceType.AIR_DISTANCE);
solution.setDistanceUnitOfMeasurement("distance");
readEmptyLine();
readConstantLine("VEHICLE");
readConstantLine("NUMBER +CAPACITY");
String[] lineTokens = splitBySpacesOrTabs(readStringValue(), 2);
vehicleListSize = Integer.parseInt(lineTokens[0]);
capacity = Integer.parseInt(lineTokens[1]);
readEmptyLine();
readConstantLine("CUSTOMER");
readConstantLine("CUST\\s+NO\\.\\s+XCOORD\\.\\s+YCOORD\\.\\s+DEMAND\\s+READY\\s+TIME\\s+DUE\\s+DATE\\s+SERVICE\\s+TIME");
readEmptyLine();
}
private void readTimeWindowedDepotAndCustomers() throws IOException {
String line = bufferedReader.readLine();
int locationListSizeEstimation = 25;
List<Location> locationList = new ArrayList<>(locationListSizeEstimation);
depotList = new ArrayList<>(1);
TimeWindowedDepot depot = null;
List<Customer> customerList = new ArrayList<>(locationListSizeEstimation);
boolean first = true;
while (line != null && !line.trim().isEmpty()) {
String[] lineTokens = splitBySpacesOrTabs(line.trim(), 7);
long id = Long.parseLong(lineTokens[0]);
AirLocation location = new AirLocation();
location.setId(id);
location.setLatitude(Double.parseDouble(lineTokens[1]));
location.setLongitude(Double.parseDouble(lineTokens[2]));
locationList.add(location);
int demand = Integer.parseInt(lineTokens[3]);
long readyTime = Long.parseLong(lineTokens[4]) * 1000L;
long dueTime = Long.parseLong(lineTokens[5]) * 1000L;
long serviceDuration = Long.parseLong(lineTokens[6]) * 1000L;
if (first) {
depot = new TimeWindowedDepot();
depot.setId(id);
depot.setLocation(location);
if (demand != 0) {
throw new IllegalArgumentException("The depot with id (" + id
+ ") has a demand (" + demand + ").");
}
depot.setReadyTime(readyTime);
depot.setDueTime(dueTime);
if (serviceDuration != 0) {
throw new IllegalArgumentException("The depot with id (" + id
+ ") has a serviceDuration (" + serviceDuration + ").");
}
depotList.add(depot);
first = false;
} else {
TimeWindowedCustomer customer = new TimeWindowedCustomer();
customer.setId(id);
customer.setLocation(location);
customer.setDemand(demand);
customer.setReadyTime(readyTime);
// Score constraint arrivalAfterDueTimeAtDepot is a build-in hard constraint in VehicleRoutingImporter
long maximumDueTime = depot.getDueTime()
- serviceDuration - location.getDistanceTo(depot.getLocation());
if (dueTime > maximumDueTime) {
logger.warn("The customer ({})'s dueTime ({}) was automatically reduced" +
" to maximumDueTime ({}) because of the depot's dueTime ({}).",
customer, dueTime, maximumDueTime, depot.getDueTime());
dueTime = maximumDueTime;
}
customer.setDueTime(dueTime);
customer.setServiceDuration(serviceDuration);
// Notice that we leave the PlanningVariable properties on null
// Do not add a customer that has no demand
if (demand != 0) {
customerList.add(customer);
}
}
line = bufferedReader.readLine();
}
solution.setLocationList(locationList);
solution.setDepotList(depotList);
solution.setCustomerList(customerList);
customerListSize = locationList.size();
}
}
}
| 52.225508 | 135 | 0.557868 |
24e72adc155b06cbb1dbb29d99b19ef7c3c02a30 | 3,140 | package com.icthh.xm.tmf.ms.product.keyresolver;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.icthh.xm.commons.lep.XmLepConstants;
import com.icthh.xm.commons.lep.spring.LepServiceHandler;
import com.icthh.xm.lep.api.LepKey;
import com.icthh.xm.lep.api.LepKeyResolver;
import com.icthh.xm.lep.api.LepManager;
import com.icthh.xm.lep.api.LepMethod;
import com.icthh.xm.lep.api.Version;
import com.icthh.xm.lep.core.CoreLepManager;
import com.icthh.xm.tmf.ms.product.lep.keyresolver.OptionalProfileKeyResolver;
import com.icthh.xm.tmf.ms.product.web.rest.ProductDelegate;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.context.ApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@ExtendWith(SpringExtension.class)
class OptionalProfileKeyResolverTest {
private static final String PROFILE_KEY = "profile";
private static final String PROFILE_VALUE = "TEST-PROFILE";
private static final String PROFILE_VALUE_RESOLVED = "TEST_PROFILE";
@InjectMocks
private LepServiceHandler lepServiceHandler;
@Mock
private ApplicationContext applicationContext;
@Mock
private CoreLepManager lepManager;
@Captor
private ArgumentCaptor<LepKey> baseLepKey;
@Captor
private ArgumentCaptor<LepKeyResolver> keyResolver;
@Captor
private ArgumentCaptor<LepMethod> lepMethod;
@Captor
private ArgumentCaptor<Version> version;
@Test
void shouldResolveLepByHeader() throws Throwable {
Method method = ProductDelegate.class.getMethod("listProduct", String.class, Integer.class, Integer.class);
when(applicationContext.getBean(LepManager.class)).thenReturn(lepManager);
OptionalProfileKeyResolver resolver = new OptionalProfileKeyResolver();
when(applicationContext.getBean(OptionalProfileKeyResolver.class)).thenReturn(resolver);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(PROFILE_KEY, PROFILE_VALUE);
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
lepServiceHandler.onMethodInvoke(ProductDelegate.class,
new ProductDelegate(), method, new Object[]{null});
verify(lepManager)
.processLep(baseLepKey.capture(), version.capture(), keyResolver.capture(), lepMethod.capture());
LepKey resolvedKey = resolver.resolve(baseLepKey.getValue(), lepMethod.getValue(), null);
assertEquals(
String.join(XmLepConstants.EXTENSION_KEY_SEPARATOR,
"service", "GetProducts", PROFILE_VALUE_RESOLVED), resolvedKey.getId());
}
}
| 37.380952 | 115 | 0.774841 |
b99de18e0c45b4f9b509e9ad91fb14bacd597dcf | 445 | package io.quarkus.qe;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import io.opentracing.Tracer;
@Path("/client")
public class ClientResource {
@Inject
Tracer tracer;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String get() {
tracer.activeSpan().log("ClientResource called");
return "I'm a client";
}
}
| 18.541667 | 57 | 0.68764 |
6ae2e4c0d03ae27c8f0c8fc5e4d943f121ab41c8 | 2,036 | package seedu.address.model.schedule;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import seedu.address.logic.parser.exceptions.ParseException;
public class EventRecurrenceTest {
@Test
public void checkWhichRecurrence_validInput_success() throws Exception {
assertEquals(EventRecurrence.DAILY, EventRecurrence.checkWhichRecurrence("Daily"));
assertEquals(EventRecurrence.WEEKLY, EventRecurrence.checkWhichRecurrence("Weekly"));
assertEquals(EventRecurrence.NONE, EventRecurrence.checkWhichRecurrence("None"));
}
@Test
public void checkWhichRecurrence_invalidInput_throwsIllegalArgumentException() {
assertThrows(ParseException.class, () -> EventRecurrence.checkWhichRecurrence(""));
assertThrows(ParseException.class, () -> EventRecurrence.checkWhichRecurrence(" "));
assertThrows(ParseException.class, () -> EventRecurrence.checkWhichRecurrence("123"));
assertThrows(ParseException.class, () -> EventRecurrence.checkWhichRecurrence("hahahah"));
}
@Test
public void checkWhichRecurRule_validInput_success() throws Exception {
assertEquals(EventRecurrence.DAILY, EventRecurrence.checkWhichRecurRule("FREQ=DAILY;INTERVAL=1"));
assertEquals(EventRecurrence.WEEKLY, EventRecurrence.checkWhichRecurRule("FREQ=WEEKLY;INTERVAL=1"));
assertEquals(EventRecurrence.NONE, EventRecurrence.checkWhichRecurRule("FREQ=YEARLY;INTERVAL=1"));
}
@Test
public void checkWhichRecurRulee_invalidInput_throwsParseException() {
assertThrows(ParseException.class, () -> EventRecurrence.checkWhichRecurRule(" "));
assertThrows(ParseException.class, () -> EventRecurrence.checkWhichRecurRule(""));
assertThrows(ParseException.class, () -> EventRecurrence.checkWhichRecurRule("123"));
assertThrows(ParseException.class, () -> EventRecurrence.checkWhichRecurRule("hahahah"));
}
}
| 47.348837 | 108 | 0.757367 |
737e5082399cb34330b8134c7a3c4a6b871d09ce | 2,606 | package br.com.zup.livraria.livraria.controller.form;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Future;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import br.com.zup.livraria.livraria.entity.Author;
import br.com.zup.livraria.livraria.entity.Book;
import br.com.zup.livraria.livraria.entity.Category;
import br.com.zup.livraria.livraria.notation.UniqueValue;
public class BookForm {
@NotBlank
@UniqueValue(domainClass = Book.class, fieldName = "title")
private String title;
@NotBlank
@Size(max = 500)
private String resume;
private String sumary;
@NotNull
@DecimalMin(value = "20")
private BigDecimal price;
@NotNull
@Min(value = 100)
private Integer numberOfPages;
@NotBlank
@UniqueValue(domainClass = Book.class, fieldName = "isbn")
private String isbn;
@JsonFormat(pattern = "dd/MM/yyyy")
@DateTimeFormat(pattern = "dd/MM/yyyy")
@Future
private LocalDate releaseDate;
@NotNull
private Long category;
@NotNull
private Long author;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getResume() {
return resume;
}
public void setResume(String resume) {
this.resume = resume;
}
public String getSumary() {
return sumary;
}
public void setSumary(String sumary) {
this.sumary = sumary;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getNumberOfPages() {
return numberOfPages;
}
public void setNumberOfPages(Integer numberOfPages) {
this.numberOfPages = numberOfPages;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public LocalDate getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(LocalDate releaseDate) {
this.releaseDate = releaseDate;
}
public Long getCategory() {
return category;
}
public void setCategory(Long category) {
this.category = category;
}
public Long getAuthor() {
return author;
}
public void setAuthor(Long author) {
this.author = author;
}
public Book convert(Author author, Category category) {
return new Book(title, resume, sumary, price, numberOfPages, isbn, releaseDate, category, author);
}
}
| 22.084746 | 100 | 0.747889 |
9d4867ebc3f15cf093f562fe572788ca859fc6f5 | 1,308 | package com.tinymooc.handler.user.service.impl;
import com.tinymooc.common.base.impl.BaseServiceImpl;
import com.tinymooc.common.domain.Level;
import com.tinymooc.common.domain.User;
import com.tinymooc.handler.user.service.UserService;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by 哓哓 on 2015/11/26 0026.
*/
@Transactional
@Service
public class UserServiceImpl extends BaseServiceImpl implements UserService {
/**
* 获取用户基本信息
*/
@Override
public User getUserInfo(String userId) {
User user = (User)getCurrentSession().createCriteria(User.class)
.add(Restrictions.eq("userId",userId)).setMaxResults(1)
.uniqueResult();
return user;
}
/**
* 获取用户等级
*/
@Override
public Level getUserLevel(int credit) {
Level level = (Level)getCurrentSession().createCriteria(Level.class)
.add(Restrictions.le("lvCondition", credit))
.add(Restrictions.eq("type","用户"))
.addOrder(Order.desc("lvCondition")).setFirstResult(0)
.setMaxResults(1).uniqueResult();
return level;
}
}
| 29.727273 | 77 | 0.678899 |
370c34e0377662658de5e1549feaf351ed0f344e | 4,803 | package com.skeqi.mes.controller.yp.oa;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.skeqi.mes.service.yp.oa.WaitingForMyApprovalService;
import com.skeqi.mes.util.Rjson;
import com.skeqi.mes.util.aop.OptionalLog;
import com.skeqi.mes.util.yp.EqualsUtil;
/**
* 待我审批
*
* @author yinp
* @data 2021年5月10日
*/
@RestController
@RequestMapping("/api/oa/waitingForMyApproval")
public class WaitingForMyApprovalController {
@Autowired
WaitingForMyApprovalService service;
/**
* 查询
*
* @param request
* @return
*/
@RequestMapping("/list")
public Rjson list(HttpServletRequest request) {
try {
int pageNum = EqualsUtil.pageNum(request);
int pageSize = EqualsUtil.pageSize(request);
int userId = EqualsUtil.integer(request, "userId", "用户ID", true);
String userName = EqualsUtil.string(request, "userName", "用户名", true);
String startDate = EqualsUtil.string(request, "startDate", "开始日期", false);
String endDate = EqualsUtil.string(request, "endDate", "结束日期", false);
String listNo = EqualsUtil.string(request, "listNo", "单号", false);
String type = EqualsUtil.string(request, "type", "单据类型", false);
Integer applicantId = EqualsUtil.integer(request, "applicantId", "申请人ID", false);
JSONObject json = new JSONObject();
json.put("userId", userId);
json.put("userName", userName);
json.put("startDate", startDate);
json.put("endDate", endDate);
json.put("listNo", listNo);
json.put("type", type);
json.put("applicantId", applicantId);
PageHelper.startPage(pageNum, pageSize);
List<JSONObject> list = service.list(json);
PageInfo<JSONObject> pageInfo = null;
if (list != null) {
pageInfo = new PageInfo<JSONObject>(list, 5);
}
return Rjson.success(pageInfo);
} catch (Exception e) {
e.printStackTrace();
return Rjson.error(e.getMessage());
}
}
/**
* 查询明细
*
* @param request
* @return
*/
@RequestMapping("/queryDetails")
public Rjson queryDetails(HttpServletRequest request) {
try {
String listNo = EqualsUtil.string(request, "listNo", "单号", true);
Integer userId = EqualsUtil.integer(request, "userId", "操作人", true);
JSONObject json = service.queryDetails(listNo, userId);
return Rjson.success(json);
} catch (Exception e) {
e.printStackTrace();
return Rjson.error(e.getMessage());
}
}
/**
* 审批
*
* @param request
* @return
*/
@OptionalLog(module = "OA", module2 = "待我审批", method = "审批")
@Transactional
@RequestMapping("/Approved")
public Rjson Approved(HttpServletRequest request) {
try {
String listNo = EqualsUtil.string(request, "listNo", "单号", true);
Integer userId = EqualsUtil.integer(request, "userId", "用户ID", true);
String type = EqualsUtil.string(request, "type", "结果", true);
String dis = EqualsUtil.string(request, "dis", "备注", false);
String formData = EqualsUtil.string(request, "formData", "表单", false);
JSONObject json = new JSONObject();
json.put("listNo", listNo);
json.put("userId", userId);
json.put("type", type);
json.put("dis", dis);
json.put("formData", formData);
service.Approved(json);
return Rjson.success();
} catch (Exception e) {
e.printStackTrace();
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return Rjson.error(e.getMessage());
}
}
/**
* 查询所有用户
*
* @param request
* @return
*/
@RequestMapping("/findUserAll")
public Rjson findUserAll() {
try {
List<JSONObject> list = service.findUserAll();
return Rjson.success(list);
} catch (Exception e) {
e.printStackTrace();
return Rjson.error(e.getMessage());
}
}
/**
* 更新表单
* @param request
* @return
*/
@RequestMapping("/updateForm")
public Rjson updateForm(HttpServletRequest request) {
try {
String listNo = EqualsUtil.string(request, "listNo", "单据号", true);
Integer userId = EqualsUtil.integer(request, "userId", "用户ID", true);
String form = EqualsUtil.string(request, "form", "表单", true);
JSONObject json = new JSONObject();
json.put("listNo", listNo);
json.put("userId", userId);
json.put("form", form);
service.updateForm(json);
return Rjson.success();
} catch (Exception e) {
e.printStackTrace();
return Rjson.error(e.getMessage());
}
}
}
| 26.983146 | 84 | 0.696856 |
0104e98d25bfb40311b45b56a930b0313f86c4b1 | 889 | package application.model.fxcircuitry;
import application.model.util.Point;
import javafx.scene.shape.Line;
public class Wire extends Line {
NodeCircle source, target = null;
public Wire(NodeCircle node) {
source = node;
setMouseTransparent(true);
setStrokeWidth(getStrokeWidth() + 3);
}
public NodeCircle getTarget() {
return target;
}
public void setTarget(NodeCircle target) {
this.target = target;
}
public void bindStart(Point p) {
startXProperty().bindBidirectional(p.xProperty());
startYProperty().bindBidirectional(p.yProperty());
}
public void setEnd(double x, double y) {
setEndX(x);
setEndY(y);
}
public void bindEnd(Point p) {
endXProperty().bindBidirectional(p.xProperty());
endYProperty().bindBidirectional(p.yProperty());
}
}
| 23.394737 | 58 | 0.642295 |
63d2c78fd5f51c7c139202ce8d032dab75cbd9b7 | 3,232 | /*
* 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.qpid.jms;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.jms.Connection;
import org.apache.qpid.jms.support.AmqpTestSupport;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Test for creation of several open connections in a series of randomly
* sized batches over time.
*/
public class JmsConnectionInRandomBatchesTest extends AmqpTestSupport {
private final List<Connection> batch = new ArrayList<Connection>();
private final Random batchSizeGenerator = new Random();
private final int RANDOM_SIZE_MARKER = -1;
private final int MAX_BATCH_SIZE = 20;
private final int MAX_BATCH_ITERATIONS = 10;
@Override
@Before
public void setUp() throws Exception {
batchSizeGenerator.setSeed(System.nanoTime());
super.setUp();
}
@Override
@After
public void tearDown() throws Exception {
doCloseConnectionBatch();
super.tearDown();
}
@Test(timeout = 60 * 1000)
public void testSingleBatch() throws Exception {
doCreateConnectionBatch(MAX_BATCH_SIZE);
}
@Test(timeout = 60 * 1000)
public void testCreateManyBatches() throws Exception {
doCreateConnectionInBatches(MAX_BATCH_ITERATIONS, MAX_BATCH_SIZE);
}
@Test(timeout = 60 * 1000)
public void testCreateRandomSizedBatches() throws Exception {
doCreateConnectionInBatches(MAX_BATCH_ITERATIONS, RANDOM_SIZE_MARKER);
}
private void doCreateConnectionInBatches(int count, int size) throws Exception {
for (int i = 0; i < count; ++i) {
if (size != RANDOM_SIZE_MARKER) {
doCreateConnectionBatch(size);
} else {
doCreateConnectionBatch(getNextBatchSize());
}
doCloseConnectionBatch();
}
}
private void doCreateConnectionBatch(int size) throws Exception {
for (int i = 0; i < size; ++i) {
batch.add(createAmqpConnection());
batch.get(i).start();
}
}
private void doCloseConnectionBatch() {
for (Connection connection : batch) {
try {
connection.close();
} catch (Exception ex) {
}
}
batch.clear();
}
private int getNextBatchSize() {
return batchSizeGenerator.nextInt(MAX_BATCH_SIZE) + 1;
}
}
| 30.780952 | 84 | 0.672649 |
62eb670338ac5c2b841c00ea9563023fe0e22c35 | 2,672 | package com.googlecode.jslint4java;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.empty;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import org.junit.Test;
import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import com.google.common.io.Closeables;
import com.google.common.io.Resources;
public class UnicodeBomInputStreamTest {
@Test
public void basicSanity() throws Exception {
// UTF-8 BOM + "12345"
ByteArrayInputStream in = new ByteArrayInputStream(new byte[] { (byte) 0xEF, (byte) 0xBB,
(byte) 0xBF, 0x31, 0x32, 0x33, 0x34, 0x35 });
UnicodeBomInputStream in2 = new UnicodeBomInputStream(in);
try {
in2.skipBOM();
assertThat(in2.read(), is(0x31));
} finally {
Closeables.closeQuietly(in2);
}
}
@Test
public void basicSanityFromResource() throws Exception {
InputStream is = UnicodeBomInputStreamTest.class.getResourceAsStream("bom.js");
UnicodeBomInputStream is2 = new UnicodeBomInputStream(is);
try {
is2.skipBOM();
// Should start with a double slash then space.
assertThat(is2.read(), is(0x2f));
assertThat(is2.read(), is(0x2f));
assertThat(is2.read(), is(0x20));
} finally {
Closeables.closeQuietly(is2);
}
}
@Test
public void basicSanityFromResourceReader() throws Exception {
UnicodeBomInputStream is2 = new UnicodeBomInputStream(getBomJs());
is2.skipBOM();
String s = CharStreams.toString(new InputStreamReader(is2, Charsets.UTF_8));
String nl = System.getProperty("line.separator");
assertThat(s, is("// This file starts with a UTF-8 BOM." + nl + "alert(\"Hello BOM\");" + nl));
}
@Test
public void canLintWithBom() throws Exception {
UnicodeBomInputStream is2 = new UnicodeBomInputStream(getBomJs());
is2.skipBOM();
InputStreamReader isr = new InputStreamReader(is2, Charsets.UTF_8);
JSLint jsLint = new JSLintBuilder().fromDefault();
jsLint.addOption(Option.PREDEF, "alert");
JSLintResult result = jsLint.lint("bom.js", isr);
assertThat(result.getIssues(), empty());
}
private InputStream getBomJs() throws IOException {
URL url = Resources.getResource(UnicodeBomInputStreamTest.class, "bom.js");
return Resources.newInputStreamSupplier(url).getInput();
}
}
| 35.157895 | 103 | 0.661677 |
91ff08adee5fec377723e6a18acb01fbebdfc79f | 11,409 | /*
* MergeHero: Differing and Merging Folders & Files
*
* Copyright © 2004, Dynamsoft, Inc. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.opensource.org/licenses/gpl-3.0.html.
*/
package MergeHero;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* @author Lincoln Burrows
*
*/
public class ThreeWayMergeJDialog extends javax.swing.JDialog implements ActionListener, KeyListener
{
private JPanel jPanelGroupBox;
private JTextField jTextFieldBase;
private JButton jButtonBaseBrowse;
private JButton jButtonYourBrowse;
private JButton jButtonTheirBrowse;
private JTextField jTextFieldTheir;
private JLabel jLabelTheir;
private JButton jButtonCancel;
private JButton jButtonOk;
private JTextField jTextFieldYour;
private JLabel jLabelYour;
private JLabel jLabelBase;
private JFileChooser fc = new JFileChooser();
private String m_strBaseFile = "";
private String m_strTheirFile = "";
private String m_strYourFile = "";
public static boolean bDoOk = false;
/**
* Auto-generated main method to display this JDialog
*/
public static void main(String[] args) {
JFrame frame = new JFrame();
ThreeWayMergeJDialog.createAndShowGUI(frame);
}
public ThreeWayMergeJDialog(JFrame frame) {
super(frame, true);
initGUI();
bDoOk = false;
}
private void initGUI() {
try {
this.setName("ThreeWayMerge");
this.setTitle("Three-Way Merge");
this.getContentPane().setLayout(null);
{
jPanelGroupBox = new JPanel();
jPanelGroupBox.setLayout(null);
this.getContentPane().add(jPanelGroupBox);
jPanelGroupBox.setBorder(BorderFactory.createTitledBorder("Files To Merge"));
jPanelGroupBox.setBounds(6, 11, 422, 120);
jPanelGroupBox.setOpaque(false);
{
jTextFieldYour = new JTextField();
jPanelGroupBox.add(jTextFieldYour);
jTextFieldYour.addKeyListener(this);
jTextFieldYour.setBounds(88, 89, 230, 24);
}
{
jLabelYour = new JLabel();
jPanelGroupBox.add(jLabelYour);
jLabelYour.setText("Your File:");
jLabelYour.setBounds(6, 89, 72, 20);
}
{
jLabelBase = new JLabel();
jPanelGroupBox.add(jLabelBase);
jLabelBase.setText("Base File:");
jLabelBase.setBounds(8, 29, 72, 20);
}
{
jTextFieldBase = new JTextField();
jPanelGroupBox.add(jTextFieldBase);
jTextFieldBase.addKeyListener(this);
jTextFieldBase.setBounds(89, 25, 230, 24);
}
{
jButtonBaseBrowse = new JButton();
jPanelGroupBox.add(jButtonBaseBrowse);
jButtonBaseBrowse.setText("Browse");
jButtonBaseBrowse.setMnemonic(KeyEvent.VK_R);
jButtonBaseBrowse.setActionCommand("Base Browse");
jButtonBaseBrowse.addActionListener(this);
jButtonBaseBrowse.setBounds(332, 25, 80, 24);
}
{
jButtonYourBrowse = new JButton();
jPanelGroupBox.add(jButtonYourBrowse);
jButtonYourBrowse.setText("Browse");
jButtonYourBrowse.setMnemonic(KeyEvent.VK_O);
jButtonYourBrowse.setActionCommand("Your Browse");
jButtonYourBrowse.addActionListener(this);
jButtonYourBrowse.setBounds(332, 89, 80, 24);
}
{
jLabelTheir = new JLabel();
jPanelGroupBox.add(jLabelTheir);
jLabelTheir.setText("Their File:");
jLabelTheir.setBounds(7, 59, 72, 20);
}
{
jTextFieldTheir = new JTextField();
jPanelGroupBox.add(jTextFieldTheir);
jTextFieldTheir.addKeyListener(this);
jTextFieldTheir.setBounds(89, 58, 230, 24);
}
{
jButtonTheirBrowse = new JButton();
jPanelGroupBox.add(jButtonTheirBrowse);
jButtonTheirBrowse.setText("Browse");
jButtonTheirBrowse.setMnemonic(KeyEvent.VK_W);
jButtonTheirBrowse.setActionCommand("Their Browse");
jButtonTheirBrowse.addActionListener(this);
jButtonTheirBrowse.setBounds(332, 58, 80, 24);
}
}
{
jButtonOk = new JButton();
this.getContentPane().add(jButtonOk);
jButtonOk.setText("Ok");
jButtonOk.setActionCommand("Ok");
jButtonOk.setEnabled(false);
jButtonOk.addActionListener(this);
jButtonOk.setBounds(433, 19, 75, 24);
}
{
jButtonCancel = new JButton();
this.getContentPane().add(jButtonCancel);
jButtonCancel.setText("Cancel");
jButtonCancel.setActionCommand("Cancel");
jButtonCancel.addActionListener(this);
jButtonCancel.setBounds(433, 48, 75, 24);
}
this.setSize(523, 171);
} catch (Exception e) {
e.printStackTrace();
}
}
// Create the GUI and show it. For thread safety,
// this method should be invoked from the event-dispatching thread.
public static void createAndShowGUI(JFrame frame)
{
// Make sure we have nice window decorations.
//JDialog.setDefaultLookAndFeelDecorated(true);
// Create and set up the window.
ThreeWayMergeJDialog threeWayMergeDiffJDlg = new ThreeWayMergeJDialog(frame);
//threeWayMergeDiffJDlg.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
// Display the window.
threeWayMergeDiffJDlg.setResizable(false);
threeWayMergeDiffJDlg.setVisible(true);
}
public void keyTyped(KeyEvent e)
{
m_strBaseFile = jTextFieldBase.getText();
m_strYourFile = jTextFieldYour.getText();
m_strTheirFile = jTextFieldTheir.getText();
EnableOkBtn();
}
public void keyPressed(KeyEvent e)
{
m_strBaseFile = jTextFieldBase.getText();
m_strYourFile = jTextFieldYour.getText();
m_strTheirFile = jTextFieldTheir.getText();
EnableOkBtn();
}
public void keyReleased(KeyEvent e)
{
m_strBaseFile = jTextFieldBase.getText();
m_strYourFile = jTextFieldYour.getText();
m_strTheirFile = jTextFieldTheir.getText();
EnableOkBtn();
}
public void actionPerformed(ActionEvent e)
{
if ("Base Browse".compareToIgnoreCase(e.getActionCommand()) == 0)
{
openFileChoose();
int iRet = fc.showOpenDialog(this);
if (iRet == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
m_strBaseFile = file.getPath();
jTextFieldBase.setText(m_strBaseFile);
}
EnableOkBtn();
}
else if ("Their Browse".compareToIgnoreCase(e.getActionCommand()) == 0)
{
openFileChoose();
int iRet = fc.showOpenDialog(this);
if (iRet == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
m_strTheirFile = file.getPath();
jTextFieldTheir.setText(m_strTheirFile);
}
EnableOkBtn();
}
else if ("Your Browse".compareToIgnoreCase(e.getActionCommand()) == 0)
{
openFileChoose();
int iRet = fc.showOpenDialog(this);
if (iRet == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
m_strYourFile = file.getPath();
jTextFieldYour.setText(m_strYourFile);
}
EnableOkBtn();
}
else if ("Ok".compareToIgnoreCase(e.getActionCommand()) == 0)
{
if (!EnableOkBtn())
{
return;
}
else if (!isValidFile(m_strBaseFile) || !isValidFile(m_strYourFile) ||
!isValidFile(m_strTheirFile))
{
return;
}
else if (m_strBaseFile.compareToIgnoreCase(m_strYourFile) == 0 ||
m_strBaseFile.compareToIgnoreCase(m_strTheirFile) == 0 ||
m_strTheirFile.compareToIgnoreCase(m_strYourFile) == 0)
{
JOptionPane.showMessageDialog(this, "The same file is selected.",
this.getTitle(), JOptionPane.ERROR_MESSAGE);
return;
}
else
{
MergeHeroApp.theApp.m_aryFiles.clear();
MergeHeroApp.theApp.m_aryFiles.add(m_strBaseFile);
MergeHeroApp.theApp.m_aryFiles.add(m_strTheirFile);
MergeHeroApp.theApp.m_aryFiles.add(m_strYourFile);
MergeHeroApp.theApp.m_bDirDiff = false;
bDoOk = true;
dispose();
}
}
else if ("Cancel".compareToIgnoreCase(e.getActionCommand()) == 0)
{
dispose();
}
}
private boolean isValidFile(String strPath)
{
File file = new File(strPath);
if (!file.exists() || !file.isFile())
{
JOptionPane.showMessageDialog(this, "Invalid input " + strPath,
this.getTitle(), JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
private void openFileChoose()
{
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
}
public boolean EnableOkBtn()
{
m_strBaseFile = jTextFieldBase.getText();
m_strYourFile = jTextFieldYour.getText();
m_strTheirFile = jTextFieldTheir.getText();
m_strBaseFile.trim();
m_strYourFile.trim();
m_strTheirFile.trim();
if (m_strBaseFile.length() == 0 || m_strYourFile.length() == 0 ||
m_strTheirFile.length() == 0)
{
jButtonOk.setEnabled(false);
return false;
}
else
{
jButtonOk.setEnabled(true);
return true;
}
}
}
| 33.955357 | 100 | 0.587256 |
1b3fe40e6d8905def95998bf8b502f1cb5938798 | 10,311 | package cn.lastwhisper.modular.service.impl;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import cn.lastwhisper.core.annotation.LogAnno;
import cn.lastwhisper.modular.vo.EasyUIDataGridResult;
import cn.lastwhisper.modular.vo.EasyUIOptionalTreeNode;
import cn.lastwhisper.modular.vo.GlobalResult;
import cn.lastwhisper.modular.mapper.RoleMapper;
import cn.lastwhisper.modular.mapper.UserMapper;
import cn.lastwhisper.modular.pojo.Role;
import cn.lastwhisper.modular.pojo.User;
import cn.lastwhisper.modular.service.UserService;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
*
* @ClassName: UserServiceImpl
* @Description: 用户相关
* @author: 最后的轻语_dd43
* @date: 2019年4月30日
*/
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Autowired
private JedisPool jedisPool;
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@Override
public User findUserByCodeAndPwd(String user_code, String user_pwd) {
// 密码加密
user_pwd = encrypt(user_pwd, user_code);
System.out.println(user_pwd);
// 获取数据库用户信息
return userMapper.selectUserBycodeAndpwd(user_code, user_pwd);
}
/**
* 加密
*
* @param source 密码
* @param salt 账号
*/
private String encrypt(String source, String salt) {
int hashIterations = 2;
Md5Hash md5 = new Md5Hash(source, salt, hashIterations);
return md5.toString();
}
@RequiresPermissions("用户管理")
@Override
public GlobalResult addUser(User user) {
if (user == null) {
return new GlobalResult(400, "用户信息为空,添加失败!", null);
}
// 密码不为空时,对密码进行加密
if ("".equals(user.getUser_pwd())) {
user.setUser_pwd(null);
} else {
String user_pwd = encrypt(user.getUser_pwd(), user.getUser_code());
user.setUser_pwd(user_pwd);
}
Integer integer = userMapper.insertUser(user);
if (integer == 0) {
return new GlobalResult(400, "用户添加失败", null);
} else {
return new GlobalResult(200, "用户添加成功", null);
}
}
@RequiresPermissions("用户管理")
@Override
public GlobalResult updateUser(User user) {
if (user == null) {
return new GlobalResult(400, "用户信息为空,修改失败!", 400);
}
// 密码不为空时,对密码进行加密
if ("".equals(user.getUser_pwd())) {
user.setUser_pwd(null);
} else {
String user_pwd = encrypt(user.getUser_pwd(), user.getUser_code());
user.setUser_pwd(user_pwd);
}
Integer integer = userMapper.updateUser(user);
if (integer == 0) {
return new GlobalResult(400, "用户信息更新失败", null);
} else {
return new GlobalResult(200, "用户信息更新成功", null);
}
}
@RequiresPermissions("用户管理")
@Override
public GlobalResult deleteUser(Integer user_id) {
try (Jedis jedis = jedisPool.getResource()) {
if (user_id == null) {
return new GlobalResult(400, "用户id为空,添加失败!", 400);
}
Integer integer = userMapper.deleteUserById(user_id);
if (integer == 0) {
return new GlobalResult(400, "用户删除失败", null);
} else {
// 删除用户下的所有角色
userMapper.deleteUserRole(user_id);
// 删除用户下的所有缓存
jedis.del("menusEasyui_" + user_id);
jedis.del("menusList_" + user_id);
return new GlobalResult(200, "用户删除成功", null);
}
}
}
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@Override
public EasyUIDataGridResult findUserlistByPage(User user, Integer page, Integer rows) {
PageHelper.startPage(page, rows);
List<User> list = userMapper.selectUserlistByPage(user);
PageInfo<User> pageInfo = new PageInfo<>(list);
EasyUIDataGridResult result = new EasyUIDataGridResult();
result.setTotal((int) pageInfo.getTotal());
result.setRows(pageInfo.getList());
return result;
}
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@Override
public List<User> findUserName(String q) {
return userMapper.selectUserName(q);
}
@LogAnno(operateType = "更新用户密码")
@Override
public GlobalResult updatePwd(User user, String oldPwd, String newPwd) {
String msg = "用户未登录";
// 用户登录了
if (user != null) {
String encryptOldPwd = encrypt(oldPwd, user.getUser_code());
// 用户密码正确
if (encryptOldPwd.equals(user.getUser_pwd())) {
String user_pwd = encrypt(newPwd, user.getUser_code());
Integer row = userMapper.updatePwdById(user.getUser_id(), user_pwd);
if (row > 0) {
return new GlobalResult(200, "密码修改成功", null);
} else {
msg = "密码修改失败";
}
} else {
msg = "密码错误";
}
}
return new GlobalResult(400, msg, null);
}
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@Override
public List<EasyUIOptionalTreeNode> findUserRole(Integer user_id) {
// 1.获取当前用户的所有角色
List<Role> userRoleList = userMapper.selectUserRole(user_id);
// 2.获取系统中所有角色
List<Role> roleList = roleMapper.selectRoleList();
// 3.设置返回值
List<EasyUIOptionalTreeNode> treeList = new ArrayList<EasyUIOptionalTreeNode>();
EasyUIOptionalTreeNode t1 = null;
// 4.封装返回值将用户对应的角色设置为true
for (Role role : roleList) {
t1 = new EasyUIOptionalTreeNode();
t1.setId(role.getUuid() + "");
t1.setText(role.getName());
// 如果用户拥有这个角色,设为true
for (Role userRole : userRoleList) {
if (userRole.getUuid().equals(role.getUuid())) {
t1.setChecked(true);
}
}
treeList.add(t1);
}
return treeList;
}
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@Override
public List<Role> findUserRoleByUserid(Integer user_id) {
return userMapper.selectUserRole(user_id);
}
@LogAnno(operateType = "更新用户对应角色")
@Override
public GlobalResult updateUserRole(Integer user_id, String checkedIds) {
try (Jedis jedis = jedisPool.getResource()) {
// 先删除用户下的所有角色
userMapper.deleteUserRole(user_id);
if (checkedIds != null) {
String[] ids = checkedIds.split(",");
for (String roleuuid : ids) {
// 设置用户的角色
userMapper.insertUserRole(user_id, Integer.parseInt(roleuuid));
}
}
// 清除缓存
jedis.del("menusEasyui_" + user_id);
jedis.del("menusList_" + user_id);
System.out.println("更新用户对应的角色 ,清除缓存");
} catch (Exception e) {
e.printStackTrace();
}
return GlobalResult.build(200, "保存成功");
}
/**
* 导出excel文件
*/
@LogAnno(operateType = "excel导出用户信息")
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@Override
public void export(OutputStream os, User user) {
// 获取所有供应商信息
List<User> UserList = userMapper.selectUserlistByPage(user);
// 1.创建excel工作薄
HSSFWorkbook wk = new HSSFWorkbook();
// 2.创建一个工作表
HSSFSheet sheet = wk.createSheet("系统用户");
// 3.写入表头
HSSFRow row = sheet.createRow(0);
// 表头
String[] headerName = { "账号", "密码", "真实姓名 ", "出生日期 " };
// 列宽
int[] columnWidths = { 6000, 6000, 6000, 6000 };
HSSFCell cell = null;
for (int i = 0; i < headerName.length; i++) {
// 创建表头单元格
cell = row.createCell(i);
// 向表头单元格写值
cell.setCellValue(headerName[i]);
sheet.setColumnWidth(i, columnWidths[i]);
}
// 4.向内容单元格写值
int i = 1;
for (User u : UserList) {
row = sheet.createRow(i);
row.createCell(0).setCellValue(u.getUser_code());// 账号
row.createCell(1).setCellValue("********");// 密码
if (u.getUser_name() != null) {
row.createCell(2).setCellValue(u.getUser_name());// "真实姓名
}
if (u.getUser_birthday() != null) {
HSSFCellStyle style_date = wk.createCellStyle();
DataFormat df = wk.createDataFormat();
style_date.setDataFormat(df.getFormat("yyyy-MM-dd"));
row.createCell(3).setCellValue(u.getUser_birthday());// 出生日期
sheet.getRow(i).getCell(3).setCellStyle(style_date);
}
i++;
}
try {
// 写入到输出流中
wk.write(os);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭工作簿
wk.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 数据导入
*/
@LogAnno(operateType = "excel导入用户信息")
@Override
public void doImport(InputStream is) throws IOException {
HSSFWorkbook wb = null;
try {
wb = new HSSFWorkbook(is);
HSSFSheet sheet = wb.getSheetAt(0);
// 读取数据
// 最后一行的行号
int lastRow = sheet.getLastRowNum();
User user = null;
for (int i = 1; i <= lastRow; i++) {
// 账号
user = new User();
user.setUser_code(sheet.getRow(i).getCell(0).getStringCellValue());
// 判断是否已经存在,通过账号来判断
List<User> list = userMapper.selectUserByUserCode(user.getUser_code());
if (list.size() > 0) {
// 说明存在用户,需要更新
user = list.get(0);
}
HSSFCell cell = null;
// 密码
cell = sheet.getRow(i).getCell(1);
cell.setCellType(CellType.STRING);
if(!cell.getStringCellValue().equals("********")) {
user.setUser_pwd(encrypt(cell.getStringCellValue(), user.getUser_code()));
}
// 真实姓名
cell = sheet.getRow(i).getCell(2);
cell.setCellType(CellType.STRING);
user.setUser_name(sheet.getRow(i).getCell(2).getStringCellValue());
// 出生日期
cell = sheet.getRow(i).getCell(3);
cell.setCellType(CellType.NUMERIC);
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// Date birthday = df.parse(sheet.getRow(i).getCell(3).getDateCellValue());
user.setUser_birthday(sheet.getRow(i).getCell(3).getDateCellValue());
if (list.size() == 0) {
// 说明不存在用户信息,需要新增
userMapper.insertUser(user);
} else {
// 更新用户信息
userMapper.updateUserByUserCode(user);
}
}
} finally {
if (null != wb) {
try {
wb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
| 28.404959 | 89 | 0.694307 |
4d4a9b9cbee14d40f60788247a7e5c7c41c13f9a | 6,101 | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.model.internal.core;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import net.jcip.annotations.ThreadSafe;
import org.gradle.api.Nullable;
import org.gradle.model.internal.type.ModelType;
/**
* A model reference is a speculative reference to a potential model element.
* <p>
* Rule subjects/inputs are defined in terms of references, as opposed to concrete identity.
* The reference may be by type only, or by path only.
* <p>
* A reference doesn't include the notion of readonly vs. writable as the context of the reference implies this.
* Having this be part of the reference would open opportunities for mismatch of that flag in the context.
*
* @param <T> the type of the reference.
*/
@ThreadSafe
public class ModelReference<T> {
@Nullable
private final ModelPath path;
private final ModelType<T> type;
@Nullable
private final ModelPath scope;
private final ModelNode.State state;
@Nullable
private final String description;
private ModelReference(@Nullable ModelPath path, ModelType<T> type, @Nullable ModelPath scope, @Nullable ModelNode.State state, @Nullable String description) {
this.path = path;
this.type = Preconditions.checkNotNull(type, "type");
this.scope = scope;
this.description = description;
this.state = state != null ? state : ModelNode.State.GraphClosed;
}
public static ModelReference<Object> any() {
return of(ModelType.untyped());
}
public static <T> ModelReference<T> of(ModelPath path, ModelType<T> type, String description) {
return new ModelReference<T>(path, type, null, null, description);
}
public static <T> ModelReference<T> of(String path, ModelType<T> type, String description) {
return of(ModelPath.path(path), type, description);
}
public static <T> ModelReference<T> of(ModelPath path, ModelType<T> type) {
return new ModelReference<T>(path, type, null, null, null);
}
public static <T> ModelReference<T> of(ModelPath path, ModelType<T> type, ModelNode.State state) {
return new ModelReference<T>(path, type, null, state, null);
}
public static <T> ModelReference<T> of(ModelPath path, Class<T> type) {
return of(path, ModelType.of(type));
}
public static <T> ModelReference<T> of(String path, Class<T> type) {
return of(ModelPath.path(path), ModelType.of(type));
}
public static <T> ModelReference<T> of(String path, ModelType<T> type) {
return of(path == null ? null : ModelPath.path(path), type);
}
public static <T> ModelReference<T> of(Class<T> type) {
return of((ModelPath) null, ModelType.of(type));
}
public static <T> ModelReference<T> of(ModelType<T> type) {
return of((ModelPath) null, type);
}
public static ModelReference<Object> of(String path) {
return of(ModelPath.path(path), ModelType.UNTYPED);
}
public static ModelReference<Object> of(ModelPath path) {
return of(path, ModelType.UNTYPED);
}
public static ModelReference<Object> untyped(ModelPath path) {
return untyped(path, null);
}
public static ModelReference<Object> untyped(ModelPath path, String description) {
return of(path, ModelType.UNTYPED, description);
}
@Nullable
public ModelPath getPath() {
return path;
}
/**
* Return the path of the scope of the node to select, or null if scope is not relevant.
*
* <p>A node will be selected if its path or its parent's path equals the specified path.</p>
*/
@Nullable
public ModelPath getScope() {
return scope;
}
@Nullable
public String getDescription() {
return description;
}
public ModelType<T> getType() {
return type;
}
public ModelNode.State getState() {
return state;
}
public boolean isUntyped() {
return type.equals(ModelType.UNTYPED);
}
public ModelReference<T> inScope(ModelPath scope) {
if (scope.equals(this.scope)) {
return this;
}
return new ModelReference<T>(path, type, scope, state, description);
}
public ModelReference<T> withPath(ModelPath path) {
return new ModelReference<T>(path, type, scope, state, description);
}
public ModelReference<T> atState(ModelNode.State state) {
if (state.equals(this.state)) {
return this;
}
return new ModelReference<T>(path, type, scope, state, description);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ModelReference<?> that = (ModelReference<?>) o;
return Objects.equal(path, that.path) && Objects.equal(scope, that.scope) && type.equals(that.type) && state.equals(that.state);
}
@Override
public int hashCode() {
int result = path == null ? 0 : path.hashCode();
result = 31 * result + (scope == null ? 0 : scope.hashCode());
result = 31 * result + type.hashCode();
result = 31 * result + state.hashCode();
return result;
}
@Override
public String toString() {
return "ModelReference{path=" + path + ", scope=" + scope + ", type=" + type + ", state=" + state + '}';
}
}
| 32.452128 | 163 | 0.651369 |
8f80ed20decf1435ce2b96dc4bfb1f86ef833c09 | 174 | package com.perunlabs.tool.jvalgen.java.type;
import com.google.common.collect.ImmutableList;
public interface JBlock {
public ImmutableList<JStatement> jStatements();
}
| 21.75 | 49 | 0.804598 |
419deac0ecce15db10f911ab26d35407384b8536 | 500 | package ch9_09;
import static org.junit.Assert.*;
import org.junit.Test;
public class LabeledPointTest {
@Test
public void test() {
boolean result;
LabeledPoint p1 = new LabeledPoint("hoge", 1, 2);
LabeledPoint p2 = new LabeledPoint("hoge", 2, 1);
System.out.println(p1.hashCode());
System.out.println(p2.hashCode());
result = p1.equals(p1);
System.out.println(result);
assertTrue(result);
result = p1.equals(p2);
System.out.println(result);
assertFalse(result);
}
}
| 17.857143 | 51 | 0.692 |
862567cb774abc80f5f687e50c4906050e22041a | 1,382 | // Looks up author of selected books
import javax.swing.*;
class DebugNine1
{
public static void main(String[] args)
{
String[][] books = new String[6][2];
books[0][0] = "Ulysses"; books[0][1] = "James Joyce";
books[1][0] = "Lolita"; books[1][1] = "Vladimir Nabokov";
books[2][0] = "Huckleberry Finn"; books[2][1] = "Mark Twain";
books[3][0] = "Great Gatsby"; books[3][1] = "F. Scott Fitzgerald";
books[4][0] = "1984"; books[4][1] = "George Orwell";
books[5][0] = "Sound and the Fury"; books[5][1] = "William Faulkner";
String entry, shortEntry, message ="Enter the first three characters of a book title omitting \"A\" or \"The\" ";
int num, x;
boolean isFound = false;
while(!isFound)
{
entry = JOptionPane.showInputDialog(null, message );
shortEntry = entry.substring(0, 3);
for(x = 0; x < books.length; ++x)
if(books[x][0].toLowerCase().startsWith(entry.toLowerCase()))
{
isFound = true;
JOptionPane.showMessageDialog(null,books[x][0] + " was written by " + books[x][1]);
break;
}
if(!isFound)
JOptionPane.showMessageDialog(null, "Sorry - no such book in our database");
}
}
}
| 40.647059 | 120 | 0.524602 |
2f1e21d2d854baa11370c169e1cb2eb1fa4bc516 | 3,292 | package evaluation.summary;
import java.util.*;
/**
* This class offers utility methods to perform analysis on list of {@link Summary} results from testing of machine learning models.
* Currently, the only supported method is {@link #average(List)} which returns average values over a list of summaries.
*
* @author dtemraz
*/
public class SummaryAnalysis {
/**
* Returns average for overall accuracy, per class accuracy and confusion matrix for the <em>summaries</em> list.
*
* @param summaries to average
* @return average for overall accuracy, per class accuracy and confusion matrix for the <em>summaries</em> list
*/
public static Summary average(List<Summary> summaries) {
return calculateAverages(summaries);
}
// returns summary object which contains sum of all metrics in the summaries list
private static Summary calculateAverages(List<Summary> summaries) {
double overallAccuracy = 0d;
double macroAvgF1 = 0d;
double macroAvgPrecision = 0d;
double macroAvgRecall = 0d;
Map<Double, Map<Double, Integer>> confusionMatrix = new LinkedHashMap<>();
Map<Double, Double> classPrecision = new LinkedHashMap<>();
Map<Double, Double> classRecall = new LinkedHashMap<>();
Set<WronglyClassified> missedMessages = new TreeSet<>();
for (Summary summary : summaries) {
// sum concrete metric values for each summary
overallAccuracy += summary.getOverallAccuracy();
macroAvgF1 += summary.getMacroAvgF1();
macroAvgPrecision += summary.getMacroAvgPrecision();
macroAvgRecall += summary.getMacroAvgRecall();
// sum confusion matrix values for each summary
summary.getConfusionMatrix().forEach((classId, matrix) -> {
Map<Double, Integer> confusion = confusionMatrix.putIfAbsent(classId, matrix);
if (confusion != null) {
matrix.forEach((k, v) -> confusion.merge(k, v, (old, delta) -> old + delta));
}
});
// sum precision and recall values for each summary and save all missed messages
summary.getPrecision().forEach((label, precision) -> classPrecision.merge(label, precision, Double::sum));
summary.getRecall().forEach((label, recall) -> classRecall.merge(label, recall, Double::sum));
missedMessages.addAll(summary.getWronglyClassified());
}
// compute macro averaged metrics
final int n = summaries.size();
overallAccuracy /= n;
macroAvgF1 /= n;
macroAvgPrecision /= n;
macroAvgRecall /= n;
// compute average values for matrix type metrics
confusionMatrix.forEach((classId, matrix) -> matrix.replaceAll((k, v) -> v / n));
classPrecision.entrySet().forEach(e -> e.setValue(e.getValue() / n));
classRecall.entrySet().forEach(e -> e.setValue(e.getValue() / n));
// could have computed metrics from average confusion matrix but this will be a little bit more precise for smaller data sets
return new Summary(overallAccuracy, confusionMatrix, classPrecision, classRecall, macroAvgF1, macroAvgPrecision, macroAvgRecall, missedMessages);
}
}
| 45.722222 | 153 | 0.658262 |
28b073aca99734ca79171089d7642e2333376039 | 659 | package com.koch.ambeth.cache.datachange.revert;
import java.lang.reflect.Field;
import com.koch.ambeth.util.exception.RuntimeExceptionUtil;
public class FieldBasedBackup implements IBackup {
protected final Field[] fields;
protected final Object[] values;
public FieldBasedBackup(Field[] fields, Object[] values) {
this.fields = fields;
this.values = values;
}
@Override
public void restore(Object target) {
for (int b = fields.length; b-- > 0;) {
Field field = fields[b];
Object originalValue = values[b];
try {
field.set(target, originalValue);
} catch (Exception e) {
throw RuntimeExceptionUtil.mask(e);
}
}
}
} | 22.724138 | 59 | 0.708649 |
fe3546e2c5bb4265692cdb85a7fc390d564a46de | 4,962 | /*
* 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.brooklyn.core.catalog.internal;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.List;
import org.apache.brooklyn.api.catalog.CatalogItem;
import org.apache.brooklyn.api.objs.SpecParameter;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
public class CatalogItemBuilderTest {
private String symbolicName = "test";
private String version = "1.0.0";
private String javaType = "1.0.0";
private String name = "My name";
private String displayName = "My display name";
private String description = "My long description";
private String iconUrl = "http://my.icon.url";
private boolean deprecated = true;
private boolean disabled = true;
private String plan = "name: my.yaml.plan";
private List<CatalogItem.CatalogBundle> libraries = ImmutableList.<CatalogItem.CatalogBundle>of(new CatalogBundleDto(name, version, null));
private Object tag = new Object();
@Test(expectedExceptions = NullPointerException.class)
public void testCannotBuildWithoutName() {
new CatalogItemBuilder<CatalogEntityItemDto>(new CatalogEntityItemDto())
.symbolicName(null)
.build();
}
@Test(expectedExceptions = NullPointerException.class)
public void testCannotBuildWithoutVersion() {
new CatalogItemBuilder<CatalogEntityItemDto>(new CatalogEntityItemDto())
.version(null)
.build();
}
@Test
public void testNewEntityReturnCatalogEntityItemDto() {
final CatalogItem catalogItem = CatalogItemBuilder.newEntity(symbolicName, version).build();
assertTrue(catalogItem != null);
}
@Test
public void testNewLocationReturnCatalogLocationItemDto() {
final CatalogItem catalogItem = CatalogItemBuilder.newLocation(symbolicName, version).build();
assertTrue(catalogItem != null);
}
@Test
public void testNewPolicyReturnCatalogPolicyItemDto() {
final CatalogItem catalogItem = CatalogItemBuilder.newPolicy(symbolicName, version).build();
assertTrue(catalogItem != null);
}
@Test
public void testNewTemplateReturnCatalogTemplateItemDto() {
final CatalogItem<?, ?> catalogItem = CatalogItemBuilder.newTemplate(symbolicName, version).build();
assertTrue(catalogItem != null);
}
@Test
public void testEmptyLibrariesIfNotSpecified() {
final CatalogItem catalogItem = CatalogItemBuilder.newEntity(symbolicName, version).build();
assertEquals(catalogItem.getLibraries().size(), 0);
}
@Test
public void testNameReplacedByDisplayName() {
final CatalogEntityItemDto catalogItem = CatalogItemBuilder.newEntity(symbolicName, version)
.name(name)
.displayName(displayName)
.build();
assertEquals(catalogItem.getName(), displayName);
}
@Test
public void testBuiltEntity() {
final CatalogEntityItemDto catalogItem = CatalogItemBuilder.newEntity(symbolicName, version)
.javaType(javaType)
.displayName(displayName)
.description(description)
.iconUrl(iconUrl)
.deprecated(deprecated)
.disabled(disabled)
.plan(plan)
.libraries(libraries)
.tag(tag)
.build();
assertEquals(catalogItem.getSymbolicName(), symbolicName);
assertEquals(catalogItem.getVersion(), version);
assertEquals(catalogItem.getJavaType(), javaType);
assertEquals(catalogItem.getDisplayName(), displayName);
assertEquals(catalogItem.getIconUrl(), iconUrl);
assertEquals(catalogItem.isDeprecated(), deprecated);
assertEquals(catalogItem.isDisabled(), disabled);
assertEquals(catalogItem.getPlanYaml(), plan);
assertEquals(catalogItem.getLibraries(), libraries);
assertEquals(catalogItem.tags().getTags().size(), 1);
assertTrue(catalogItem.tags().getTags().contains(tag));
}
}
| 37.308271 | 143 | 0.692261 |
4994b5769474aa4ff4ee29cfd20d073773b7de6b | 1,142 | package ru.guar7387.servermodule.tasksfactory;
import org.json.JSONException;
import org.json.JSONObject;
import ru.guar7387.servermodule.api.ConnectionManager;
import ru.guar7387.servermodule.api.ConnectionRequest;
import ru.guar7387.servermodule.callbacks.Answer;
import ru.guar7387.servermodule.callbacks.AnswerCallback;
public class AddCommentTask extends AbstractTask {
private Answer result;
private final AnswerCallback callback;
public AddCommentTask(int requestCode, ConnectionRequest request, ConnectionManager connectionManager,
AnswerCallback callback) {
super(requestCode, request, connectionManager, null);
this.callback = callback;
}
@Override
public void parseJson(JSONObject answer) {
result = Answer.FAIL;
try {
if (answer.getJSONObject("response").toString().equals("{}")) {
result = Answer.OK;
}
} catch (JSONException ignored) {
}
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
callback.call(result);
}
}
| 27.190476 | 106 | 0.685639 |
05386752c7e5efc0e34c0f71921bbdc5849f3f3e | 445 | package com.stylefeng.guns.rest.common.persistence.dao;
import com.stylefeng.guns.rest.modular.film.vo.GetFilmVO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface GetFilmMapper {
List<GetFilmVO> selectGetFilmDataListByIdId(@Param("showType") int showType, @Param("sortId") int sortId, @Param("catId") int catId,@Param("sourceId") int sourceId, @Param("yearId") int yearId ,@Param("kw") String kw);
}
| 31.785714 | 222 | 0.761798 |
beb339c19d12330bd81e9002c448ba7703a4a7c8 | 11,865 | /*
* Copyright 1998-2009 University Corporation for Atmospheric Research/Unidata
*
* Portions of this software were developed by the Unidata Program at the
* University Corporation for Atmospheric Research.
*
* Access and use of this software shall impose the following obligations
* and understandings on the user. The user is granted the right, without
* any fee or cost, to use, copy, modify, alter, enhance and distribute
* this software, and any derivative works thereof, and its supporting
* documentation for any purpose whatsoever, provided that this entire
* notice appears in all copies of the software, derivative works and
* supporting documentation. Further, UCAR requests that the user credit
* UCAR/Unidata in any publications that result from the use of this
* software or in any product that includes this software. The names UCAR
* and/or Unidata, however, may not be used in any advertising or publicity
* to endorse or promote any products or commercial entity unless specific
* written permission is obtained from UCAR/Unidata. The user also
* understands that UCAR/Unidata is not obligated to provide the user with
* any support, consulting, training or assistance of any kind with regard
* to the use, operation and performance of this software nor to provide
* the user with any updates, revisions, new versions or "bug fixes."
*
* THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package thredds.catalog;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import java.io.*;
import java.net.*;
import java.util.*;
/*
LOOK: not being used, can we delet? JC 10/29/2012
VERSION notes
Havent been able to detect how to know what version parser you have. may be new feature in JAXP 1.3
Java 1.4.2 uses JAXP 1.1, which doesnt do W3S Schema validation. (see http://xml.apache.org/~edwingo/jaxp-ri-1.2.0-fcs/docs/)
when you call factory.setAttribute() get message "No attributes are implemented"
when you validate=true, get warning "Valid documents must have a <!DOCTYPE declaration.", plus lots of errors,
but no fatal errors.
It appears that "Tiger should support the latest version of JAXP...JAXP will be update to conform to the
new specifications: XML 1.1 Namespaces 1.1 SAX 2.0.1". Note they dont actually say what that is. My
JavaOne notes claim JAXP 1.3 (JSR 206). Hard to tell what they've added: access to version info and
perhaps XInclude.
JAXP 1.2 available in WSDP 1.3.
Install JAXP 1.2 into J2SE 1.4, see http://java.sun.com/webservices/docs/1.2/jaxp/Updating.html
"Version 1.4 of the Java 2 platform has a JAXP 1.1 implementation built in. (JAXP 1.1 has a smaller
application footprint, but JAXP 1.2 implements XML Schema and the transform compiler, XSLTC.)
Because the built-in libraries are accessed before any classpath entries, you can only access the
updated libraries by using the Java platform's Endorsed Standards mechanism.
There are two ways to use the endorsed standards mechanism. The first way is to copy all of the jar
files except jaxp-api.jar into <JAVA_HOME>/jre/lib/endorsed/
Note:
The jaxp-api.jar file should not be copied, because it contains high-level factory APIs that are not
subject to change.
Alternatively, you can use the java.endorsed.dirs system property to dynamically add those jar files to
the JVM when you start your program. Using that system property gives you flexibility of using different
implementations for different applications. You specify that property using
-Djava.endorsed.dirs=yourDirectoryPath.
Finally, although the endorsed directory mechanism guarantees that the specified jars will be searched
before the internal classes in the VM (which are searched before the classpath), the order in which the
jar files are searched is indeterminate. For that reason, there should be no overlaps in the classes
specified using that property. For more information, see the Endorsed Standards documentation for the
1.4 version of the Java platform."
It seems that this will make webstart delivery impossible ?
*/
/*
Cant set JAXP_SCHEMA_LANGUAGE on catalog 0.6, get:
** Non-Fatal XML Error error(s) =
*** XML parser error=cvc-elt.1: Cannot find the declaration of element 'catalog'.
so validation is not done. Problem is that in JAXP 1.2, setting JAXP_SCHEMA_LANGUAGE overrides the DTD
even when theres no schema declared!
Of cource, you dont know what version until you start parsing !!!!
"Set Schema Source" in JAXP 1.2: see http://java.sun.com/xml/jaxp/change-requests-11.html
*/
public class TestParserValidate {
// JAXP and DTD caching
private String dtdUrl = "http://www.unidata.ucar.edu/projects/THREDDS/xml/InvCatalog.0.6.dtd";
private String dtdString;
private DocumentBuilderFactory factory;
boolean debugJaxp = true, schemaValidation = true;
private String name, version;
private HashMap versionHash = new HashMap(10);
private StringBuffer errMessages = new StringBuffer();
private StringBuffer fatalMessages = new StringBuffer();
// schema validation
static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
static final String XHTML_SCHEMA = "http://www.w3.org/1999/xhtml";
// only use one DocumentBuilderFactory, so needs to be synchronized
DocumentBuilder getDocumentBuilder(boolean validate) {
/* DTD cache
try { // try to read from local file resource, eg from catalog.jar
ByteArrayOutputStream sbuff = new ByteArrayOutputStream(3000);
InputStream is = thredds.util.Resource.getFileResource( "/xml/InvCatalog.0.6.dtd");
if (is != null) {
thredds.util.IO.copy(is, sbuff);
dtdString = sbuff.toString();
} else { // otherwise, get from network and cache
dtdString = thredds.util.IO.readURLcontentsWithException(dtdUrl);
}
} catch (IOException e) {
e.printStackTrace();
} */
// Get Document Builder Factory
factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(validate);
if (schemaValidation) {
try {
factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
// factory.setAttribute(JAXP_SCHEMA_SOURCE, new File(schemaSource));
}
catch (IllegalArgumentException e) {
System.out.println("***This can happen if the parser does not support JAXP 1.2\n"+e);
}
}
if (debugJaxp) showFactoryInfo(factory);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(new MyEntityResolver());
builder.setErrorHandler(new MyErrorHandler());
if (debugJaxp) showBuilderInfo(builder);
return builder;
}
catch (ParserConfigurationException e) {
System.out.println("The underlying parser does not support the requested features.");
}
catch (FactoryConfigurationError e) {
System.out.println("Error occurred obtaining Document Builder Factory.");
}
return null;
}
static private void showFactoryInfo( DocumentBuilderFactory factory) {
System.out.println("-----------------------");
System.out.println(" factory.isValidating()="+factory.isValidating());
System.out.println(" factory.isNamespaceAware()="+factory.isNamespaceAware());
System.out.println(" factory.isIgnoringElementContentWhitespace()="+factory.isIgnoringElementContentWhitespace());
System.out.println(" factory.isExpandEntityReferences()="+factory.isExpandEntityReferences());
System.out.println(" factory.isIgnoringComments()="+factory.isIgnoringComments());
System.out.println(" factory.isCoalescing()="+factory.isCoalescing());
System.out.println("-----------------------");
}
static private void showBuilderInfo( DocumentBuilder builder) {
System.out.println("-----------------------");
System.out.println(" builder.isValidating()="+builder.isValidating());
System.out.println(" builder.isNamespaceAware()="+builder.isNamespaceAware());
System.out.println("-----------------------");
}
private class MyEntityResolver implements org.xml.sax.EntityResolver {
public org.xml.sax.InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
if (debugJaxp) System.out.println("** publicId= "+publicId+" systemId="+systemId);
return null;
/* if (systemId.equals("http://www.unidata.ucar.edu/projects/THREDDS/xml/InvCatalog.0.6.dtd")) {
version = "0.6";
return new MyInputSource();
} else if (systemId.indexOf("InvCatalog.0.6.dtd") >= 0) {
version = "0.6";
return new MyInputSource();
} else
return null; */
}
}
private class MyInputSource extends org.xml.sax.InputSource {
MyInputSource() {
setCharacterStream(new StringReader(dtdString));
}
}
private class MyErrorHandler implements org.xml.sax.ErrorHandler {
public void warning(SAXParseException e) throws SAXException {
errMessages.append("*** XML parser warning="+e.getMessage()+"\n");
}
public void error(SAXParseException e) throws SAXException {
errMessages.append("*** XML parser error="+e.getMessage()+"\n");
}
public void fatalError(SAXParseException e) throws SAXException {
fatalMessages.append("*** XML parser fatalError="+e.getMessage()+"\n");
}
}
public void read(String uriString, boolean validate) {
URI uri = null;
try {
uri = new URI( uriString);
} catch (URISyntaxException e) {
System.out.println( "**Fatal: InvCatalogFactory.readXML URISyntaxException on URL ("+
uriString+") "+e.getMessage()+"\n");
return;
}
// get ready for XML parsing
DocumentBuilder builder = getDocumentBuilder(validate);
errMessages.setLength(0);
fatalMessages.setLength(0);
version = null;
Document doc = null;
try {
doc = builder.parse(uriString);
System.out.println("JAXP Parse OK");
} catch (Exception e) {
fatalMessages.append( "**Fatal: InvCatalogFactory.readXML failed"
+"\n Exception= "+e.getClass().getName()+" "+e.getMessage()
+"\n fatalMessages= " +fatalMessages.toString()
+"\n errMessages= " +errMessages.toString()+"\n");
}
if (fatalMessages.length() > 0) {
System.out.println("**Fatal: XML error(s) =\n"+
fatalMessages.toString()+"\n");
}
if (errMessages.length() > 0) {
System.out.println("** Non-Fatal XML Error error(s) =\n"+
errMessages.toString()+"\n");
}
}
public static void main(String[] arg) {
TestParserValidate test = new TestParserValidate();
test.read("file:///C:/dev/thredds/xml/v7/ExampleJoin.xml", true );
//test.read("file:///C:/dev/thredds/xml/v7/testQualify.xml", true );
//test.read("file:///C:/dev/thredds/server/catalogBad.xml", true);
// read("http://motherlode.ucar.edu/cgi-bin/thredds/MetarServer.pl?format=qc", null);
//read("E:/metadata/netcdf/testValidate.xml",
// "http://www.ucar.edu/schemas/netcdf E:/metadata/netcdf/netcdf2.xsd");
}
} | 42.679856 | 127 | 0.711167 |
e5cacea58b459c65601dd33d6e4b4a1f1208a424 | 392 | // DocSection: delivery_api_get_types
// Tip: Find more about Java/JavaRx SDKs at https://docs.kontent.ai/javaandroid
import com.github.kentico.kontent.delivery;
DeliveryClient client = new DeliveryClient("<YOUR_PROJECT_ID>");
List<NameValuePair> params = DeliveryParameterBuilder.params().page(null, 3).build();
ContentTypesListingResponse types = client.getTypes(params);
// EndDocSection | 43.555556 | 85 | 0.80102 |
03f6075c9600ebf7ba4eafbbe9fc24d071f4c7b7 | 1,722 | package org.adorsys.encobject.types;
import org.adorsys.cryptoutils.exceptions.BaseException;
import org.adorsys.encobject.domain.ContentMetaInfo;
import java.util.HashMap;
/**
* Created by peter on 24.01.18 at 09:15.
*/
public class PersistenceLayerContentMetaInfoUtil {
private final static String KEYID = "KeyID";
private final static String ENCRYPTIONN_TYPE = "EncryptionType";
public static void setKeyID(ContentMetaInfo contentMetaInfo, KeyID keyID) {
if (contentMetaInfo == null) {
throw new BaseException("Programming error contentMetaInfo must not be null");
}
if (contentMetaInfo.getAddInfos() == null) {
contentMetaInfo.setAddInfos(new HashMap<String, Object>());
}
contentMetaInfo.getAddInfos().put(KEYID, keyID.getValue());
}
public static void setEncryptionType(ContentMetaInfo contentMetaInfo, EncryptionType encryptionType) {
if (contentMetaInfo == null) {
throw new BaseException("Programming error contentMetaInfo must not be null");
}
if (contentMetaInfo.getAddInfos() == null) {
contentMetaInfo.setAddInfos(new HashMap<String, Object>());
}
contentMetaInfo.getAddInfos().put(ENCRYPTIONN_TYPE, encryptionType);
}
public static KeyID getKeyID(ContentMetaInfo contentMetaInfo) {
String content = (String) contentMetaInfo.getAddInfos().get(KEYID);
return new KeyID(content);
}
public static EncryptionType getEncryptionnType(ContentMetaInfo contentMetaInfo) {
String encryptionType = (String) contentMetaInfo.getAddInfos().get(ENCRYPTIONN_TYPE);
return EncryptionType.valueOf(encryptionType);
}
}
| 38.266667 | 106 | 0.707317 |
26cf03327c23288068aec68f70328c3045da5dfc | 17,267 | /*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* 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.common.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.math.RoundingMode.CEILING;
import static java.math.RoundingMode.FLOOR;
import static java.math.RoundingMode.HALF_EVEN;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
/**
* A class for arithmetic on values of type {@code BigInteger}.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code int} and for {@code long} can be found in {@link IntMath} and
* {@link LongMath} respectively.
*
* @author Louis Wasserman
* @since 11.0
*/
@GwtCompatible(emulated = true)
public final class BigIntegerMath {
/**
* Returns the smallest power of two greater than or equal to {@code x}. This is equivalent to
* {@code BigInteger.valueOf(2).pow(log2(x, CEILING))}.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @since 20.0
*/
@Beta
public static BigInteger ceilingPowerOfTwo(BigInteger x) {
return BigInteger.ZERO.setBit(log2(x, RoundingMode.CEILING));
}
/**
* Returns the largest power of two less than or equal to {@code x}. This is equivalent to
* {@code BigInteger.valueOf(2).pow(log2(x, FLOOR))}.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @since 20.0
*/
@Beta
public static BigInteger floorPowerOfTwo(BigInteger x) {
return BigInteger.ZERO.setBit(log2(x, RoundingMode.FLOOR));
}
/**
* Returns {@code true} if {@code x} represents a power of two.
*/
public static boolean isPowerOfTwo(BigInteger x) {
checkNotNull(x);
return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1;
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
// TODO(kevinb): remove after this warning is disabled globally
public static int log2(BigInteger x, RoundingMode mode) {
checkPositive("x", checkNotNull(x));
int logFloor = x.bitLength() - 1;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through
case DOWN:
case FLOOR:
return logFloor;
case UP:
case CEILING:
return isPowerOfTwo(x) ? logFloor : logFloor + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
if (logFloor < SQRT2_PRECOMPUTE_THRESHOLD) {
BigInteger halfPower =
SQRT2_PRECOMPUTED_BITS.shiftRight(SQRT2_PRECOMPUTE_THRESHOLD - logFloor);
if (x.compareTo(halfPower) <= 0) {
return logFloor;
} else {
return logFloor + 1;
}
}
// Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
//
// To determine which side of logFloor.5 the logarithm is,
// we compare x^2 to 2^(2 * logFloor + 1).
BigInteger x2 = x.pow(2);
int logX2Floor = x2.bitLength() - 1;
return (logX2Floor < 2 * logFloor + 1) ? logFloor : logFloor + 1;
default:
throw new AssertionError();
}
}
/*
* The maximum number of bits in a square root for which we'll precompute an explicit half power
* of two. This can be any value, but higher values incur more class load time and linearly
* increasing memory consumption.
*/
@VisibleForTesting static final int SQRT2_PRECOMPUTE_THRESHOLD = 256;
@VisibleForTesting
static final BigInteger SQRT2_PRECOMPUTED_BITS =
new BigInteger("16a09e667f3bcc908b2fb1366ea957d3e3adec17512775099da2f590b0667322a", 16);
/**
* Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
@GwtIncompatible // TODO
@SuppressWarnings("fallthrough")
public static int log10(BigInteger x, RoundingMode mode) {
checkPositive("x", x);
if (fitsInLong(x)) {
return LongMath.log10(x.longValue(), mode);
}
int approxLog10 = (int) (log2(x, FLOOR) * LN_2 / LN_10);
BigInteger approxPow = BigInteger.TEN.pow(approxLog10);
int approxCmp = approxPow.compareTo(x);
/*
* We adjust approxLog10 and approxPow until they're equal to floor(log10(x)) and
* 10^floor(log10(x)).
*/
if (approxCmp > 0) {
/*
* The code is written so that even completely incorrect approximations will still yield the
* correct answer eventually, but in practice this branch should almost never be entered, and
* even then the loop should not run more than once.
*/
do {
approxLog10--;
approxPow = approxPow.divide(BigInteger.TEN);
approxCmp = approxPow.compareTo(x);
} while (approxCmp > 0);
} else {
BigInteger nextPow = BigInteger.TEN.multiply(approxPow);
int nextCmp = nextPow.compareTo(x);
while (nextCmp <= 0) {
approxLog10++;
approxPow = nextPow;
approxCmp = nextCmp;
nextPow = BigInteger.TEN.multiply(approxPow);
nextCmp = nextPow.compareTo(x);
}
}
int floorLog = approxLog10;
BigInteger floorPow = approxPow;
int floorCmp = approxCmp;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(floorCmp == 0);
// fall through
case FLOOR:
case DOWN:
return floorLog;
case CEILING:
case UP:
return floorPow.equals(x) ? floorLog : floorLog + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// Since sqrt(10) is irrational, log10(x) - floorLog can never be exactly 0.5
BigInteger x2 = x.pow(2);
BigInteger halfPowerSquared = floorPow.pow(2).multiply(BigInteger.TEN);
return (x2.compareTo(halfPowerSquared) <= 0) ? floorLog : floorLog + 1;
default:
throw new AssertionError();
}
}
private static final double LN_10 = Math.log(10);
private static final double LN_2 = Math.log(2);
/**
* Returns the square root of {@code x}, rounded with the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x < 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and
* {@code sqrt(x)} is not an integer
*/
@GwtIncompatible // TODO
@SuppressWarnings("fallthrough")
public static BigInteger sqrt(BigInteger x, RoundingMode mode) {
checkNonNegative("x", x);
if (fitsInLong(x)) {
return BigInteger.valueOf(LongMath.sqrt(x.longValue(), mode));
}
BigInteger sqrtFloor = sqrtFloor(x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(sqrtFloor.pow(2).equals(x)); // fall through
case FLOOR:
case DOWN:
return sqrtFloor;
case CEILING:
case UP:
int sqrtFloorInt = sqrtFloor.intValue();
boolean sqrtFloorIsExact =
(sqrtFloorInt * sqrtFloorInt == x.intValue()) // fast check mod 2^32
&& sqrtFloor.pow(2).equals(x); // slow exact check
return sqrtFloorIsExact ? sqrtFloor : sqrtFloor.add(BigInteger.ONE);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
BigInteger halfSquare = sqrtFloor.pow(2).add(sqrtFloor);
/*
* We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both x
* and halfSquare are integers, this is equivalent to testing whether or not x <=
* halfSquare.
*/
return (halfSquare.compareTo(x) >= 0) ? sqrtFloor : sqrtFloor.add(BigInteger.ONE);
default:
throw new AssertionError();
}
}
@GwtIncompatible // TODO
private static BigInteger sqrtFloor(BigInteger x) {
/*
* Adapted from Hacker's Delight, Figure 11-1.
*
* Using DoubleUtils.bigToDouble, getting a double approximation of x is extremely fast, and
* then we can get a double approximation of the square root. Then, we iteratively improve this
* guess with an application of Newton's method, which sets guess := (guess + (x / guess)) / 2.
* This iteration has the following two properties:
*
* a) every iteration (except potentially the first) has guess >= floor(sqrt(x)). This is
* because guess' is the arithmetic mean of guess and x / guess, sqrt(x) is the geometric mean,
* and the arithmetic mean is always higher than the geometric mean.
*
* b) this iteration converges to floor(sqrt(x)). In fact, the number of correct digits doubles
* with each iteration, so this algorithm takes O(log(digits)) iterations.
*
* We start out with a double-precision approximation, which may be higher or lower than the
* true value. Therefore, we perform at least one Newton iteration to get a guess that's
* definitely >= floor(sqrt(x)), and then continue the iteration until we reach a fixed point.
*/
BigInteger sqrt0;
int log2 = log2(x, FLOOR);
if (log2 < Double.MAX_EXPONENT) {
sqrt0 = sqrtApproxWithDoubles(x);
} else {
int shift = (log2 - DoubleUtils.SIGNIFICAND_BITS) & ~1; // even!
/*
* We have that x / 2^shift < 2^54. Our initial approximation to sqrtFloor(x) will be
* 2^(shift/2) * sqrtApproxWithDoubles(x / 2^shift).
*/
sqrt0 = sqrtApproxWithDoubles(x.shiftRight(shift)).shiftLeft(shift >> 1);
}
BigInteger sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1);
if (sqrt0.equals(sqrt1)) {
return sqrt0;
}
do {
sqrt0 = sqrt1;
sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1);
} while (sqrt1.compareTo(sqrt0) < 0);
return sqrt0;
}
@GwtIncompatible // TODO
private static BigInteger sqrtApproxWithDoubles(BigInteger x) {
return DoubleMath.roundToBigInteger(Math.sqrt(DoubleUtils.bigToDouble(x)), HALF_EVEN);
}
/**
* Returns the result of dividing {@code p} by {@code q}, rounding using the specified
* {@code RoundingMode}.
*
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
@GwtIncompatible // TODO
public static BigInteger divide(BigInteger p, BigInteger q, RoundingMode mode) {
BigDecimal pDec = new BigDecimal(p);
BigDecimal qDec = new BigDecimal(q);
return pDec.divide(qDec, 0, mode).toBigIntegerExact();
}
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive integers, or {@code 1}
* if {@code n == 0}.
*
* <p><b>Warning:</b> the result takes <i>O(n log n)</i> space, so use cautiously.
*
* <p>This uses an efficient binary recursive algorithm to compute the factorial with balanced
* multiplies. It also removes all the 2s from the intermediate products (shifting them back in at
* the end).
*
* @throws IllegalArgumentException if {@code n < 0}
*/
public static BigInteger factorial(int n) {
checkNonNegative("n", n);
// If the factorial is small enough, just use LongMath to do it.
if (n < LongMath.factorials.length) {
return BigInteger.valueOf(LongMath.factorials[n]);
}
// Pre-allocate space for our list of intermediate BigIntegers.
int approxSize = IntMath.divide(n * IntMath.log2(n, CEILING), Long.SIZE, CEILING);
ArrayList<BigInteger> bignums = new ArrayList<BigInteger>(approxSize);
// Start from the pre-computed maximum long factorial.
int startingNumber = LongMath.factorials.length;
long product = LongMath.factorials[startingNumber - 1];
// Strip off 2s from this value.
int shift = Long.numberOfTrailingZeros(product);
product >>= shift;
// Use floor(log2(num)) + 1 to prevent overflow of multiplication.
int productBits = LongMath.log2(product, FLOOR) + 1;
int bits = LongMath.log2(startingNumber, FLOOR) + 1;
// Check for the next power of two boundary, to save us a CLZ operation.
int nextPowerOfTwo = 1 << (bits - 1);
// Iteratively multiply the longs as big as they can go.
for (long num = startingNumber; num <= n; num++) {
// Check to see if the floor(log2(num)) + 1 has changed.
if ((num & nextPowerOfTwo) != 0) {
nextPowerOfTwo <<= 1;
bits++;
}
// Get rid of the 2s in num.
int tz = Long.numberOfTrailingZeros(num);
long normalizedNum = num >> tz;
shift += tz;
// Adjust floor(log2(num)) + 1.
int normalizedBits = bits - tz;
// If it won't fit in a long, then we store off the intermediate product.
if (normalizedBits + productBits >= Long.SIZE) {
bignums.add(BigInteger.valueOf(product));
product = 1;
productBits = 0;
}
product *= normalizedNum;
productBits = LongMath.log2(product, FLOOR) + 1;
}
// Check for leftovers.
if (product > 1) {
bignums.add(BigInteger.valueOf(product));
}
// Efficiently multiply all the intermediate products together.
return listProduct(bignums).shiftLeft(shift);
}
static BigInteger listProduct(List<BigInteger> nums) {
return listProduct(nums, 0, nums.size());
}
static BigInteger listProduct(List<BigInteger> nums, int start, int end) {
switch (end - start) {
case 0:
return BigInteger.ONE;
case 1:
return nums.get(start);
case 2:
return nums.get(start).multiply(nums.get(start + 1));
case 3:
return nums.get(start).multiply(nums.get(start + 1)).multiply(nums.get(start + 2));
default:
// Otherwise, split the list in half and recursively do this.
int m = (end + start) >>> 1;
return listProduct(nums, start, m).multiply(listProduct(nums, m, end));
}
}
/**
* Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
* {@code k}, that is, {@code n! / (k! (n - k)!)}.
*
* <p><b>Warning:</b> the result can take as much as <i>O(k log n)</i> space.
*
* @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
*/
public static BigInteger binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
}
if (k < LongMath.biggestBinomials.length && n <= LongMath.biggestBinomials[k]) {
return BigInteger.valueOf(LongMath.binomial(n, k));
}
BigInteger accum = BigInteger.ONE;
long numeratorAccum = n;
long denominatorAccum = 1;
int bits = LongMath.log2(n, RoundingMode.CEILING);
int numeratorBits = bits;
for (int i = 1; i < k; i++) {
int p = n - i;
int q = i + 1;
// log2(p) >= bits - 1, because p >= n/2
if (numeratorBits + bits >= Long.SIZE - 1) {
// The numerator is as big as it can get without risking overflow.
// Multiply numeratorAccum / denominatorAccum into accum.
accum =
accum
.multiply(BigInteger.valueOf(numeratorAccum))
.divide(BigInteger.valueOf(denominatorAccum));
numeratorAccum = p;
denominatorAccum = q;
numeratorBits = bits;
} else {
// We can definitely multiply into the long accumulators without overflowing them.
numeratorAccum *= p;
denominatorAccum *= q;
numeratorBits += bits;
}
}
return accum
.multiply(BigInteger.valueOf(numeratorAccum))
.divide(BigInteger.valueOf(denominatorAccum));
}
// Returns true if BigInteger.valueOf(x.longValue()).equals(x).
@GwtIncompatible // TODO
static boolean fitsInLong(BigInteger x) {
return x.bitLength() <= Long.SIZE - 1;
}
private BigIntegerMath() {}
}
| 36.123431 | 100 | 0.6513 |
505a07289def3322709fb525c5c381e298171657 | 6,479 | package com.eu.habbo.habbohotel.items.interactions.wired.effects;
import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.items.Item;
import com.eu.habbo.habbohotel.items.interactions.InteractionWiredEffect;
import com.eu.habbo.habbohotel.items.interactions.InteractionWiredTrigger;
import com.eu.habbo.habbohotel.rooms.Room;
import com.eu.habbo.habbohotel.rooms.RoomTile;
import com.eu.habbo.habbohotel.rooms.RoomUnit;
import com.eu.habbo.habbohotel.users.HabboItem;
import com.eu.habbo.habbohotel.wired.WiredEffectType;
import com.eu.habbo.habbohotel.wired.WiredHandler;
import com.eu.habbo.messages.ClientMessage;
import com.eu.habbo.messages.ServerMessage;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.set.hash.THashSet;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class WiredEffectTriggerStacks extends InteractionWiredEffect
{
public static final WiredEffectType type = WiredEffectType.CALL_STACKS;
private THashSet<HabboItem> items;
public WiredEffectTriggerStacks(ResultSet set, Item baseItem) throws SQLException
{
super(set, baseItem);
this.items = new THashSet<HabboItem>();
}
public WiredEffectTriggerStacks(int id, int userId, Item item, String extradata, int limitedStack, int limitedSells)
{
super(id, userId, item, extradata, limitedStack, limitedSells);
this.items = new THashSet<HabboItem>();
}
@Override
public void serializeWiredData(ServerMessage message, Room room)
{
THashSet<HabboItem> items = new THashSet<HabboItem>();
for(HabboItem item : this.items)
{
if(item.getRoomId() != this.getRoomId() || Emulator.getGameEnvironment().getRoomManager().getRoom(this.getRoomId()).getHabboItem(item.getId()) == null)
items.add(item);
}
for(HabboItem item : items)
{
this.items.remove(item);
}
message.appendBoolean(false);
message.appendInt(WiredHandler.MAXIMUM_FURNI_SELECTION);
message.appendInt(this.items.size());
for(HabboItem item : this.items)
{
message.appendInt(item.getId());
}
message.appendInt(this.getBaseItem().getSpriteId());
message.appendInt(this.getId());
message.appendString("");
message.appendInt(0);
message.appendInt(0);
message.appendInt(this.getType().code);
message.appendInt(this.getDelay());
if (this.requiresTriggeringUser())
{
List<Integer> invalidTriggers = new ArrayList<>();
room.getRoomSpecialTypes().getTriggers(this.getX(), this.getY()).forEach(new TObjectProcedure<InteractionWiredTrigger>()
{
@Override
public boolean execute(InteractionWiredTrigger object)
{
if (!object.isTriggeredByRoomUnit())
{
invalidTriggers.add(object.getBaseItem().getSpriteId());
}
return true;
}
});
message.appendInt(invalidTriggers.size());
for (Integer i : invalidTriggers)
{
message.appendInt(i);
}
}
else
{
message.appendInt(0);
}
}
@Override
public boolean saveData(ClientMessage packet, GameClient gameClient)
{
packet.readInt();
packet.readString();
this.items.clear();
int count = packet.readInt();
for(int i = 0; i < count; i++)
{
this.items.add(Emulator.getGameEnvironment().getRoomManager().getRoom(this.getRoomId()).getHabboItem(packet.readInt()));
}
this.setDelay(packet.readInt());
return true;
}
@Override
public boolean execute(RoomUnit roomUnit, Room room, Object[] stuff)
{
if ((stuff != null) && (stuff.length >= 1 && stuff[stuff.length - 1] instanceof WiredEffectTriggerStacks))
{
return false;
}
THashSet<RoomTile> usedTiles = new THashSet<RoomTile>();
boolean found;
for(HabboItem item : this.items)
{
//if(item instanceof InteractionWiredTrigger)
{
found = false;
for(RoomTile tile : usedTiles)
{
if(tile.x == item.getX() && tile.y == item.getY())
{
found = true;
break;
}
}
if(!found)
{
usedTiles.add(room.getLayout().getTile(item.getX(), item.getY()));
}
}
}
Object[] newStuff = new Object[stuff.length + 1];
System.arraycopy(stuff, 0, newStuff, 0, stuff.length);
newStuff[newStuff.length - 1] = this;
WiredHandler.executeEffectsAtTiles(usedTiles, roomUnit, room, stuff);
return true;
}
@Override
public String getWiredData()
{
String wiredData = this.getDelay() + "\t";
if(items != null && !items.isEmpty())
{
for (HabboItem item : this.items)
{
wiredData += item.getId() + ";";
}
}
return wiredData;
}
@Override
public void loadWiredData(ResultSet set, Room room) throws SQLException
{
this.items = new THashSet<HabboItem>();
String[] wiredData = set.getString("wired_data").split("\t");
if (wiredData.length >= 1)
{
this.setDelay(Integer.valueOf(wiredData[0]));
}
if (wiredData.length == 2)
{
if (wiredData[1].contains(";"))
{
for (String s : wiredData[1].split(";"))
{
HabboItem item = room.getHabboItem(Integer.valueOf(s));
if (item != null)
this.items.add(item);
}
}
}
}
@Override
public void onPickUp()
{
this.items.clear();
this.setDelay(0);
}
@Override
public WiredEffectType getType()
{
return type;
}
@Override
protected long requiredCooldown()
{
return 2500;
}
}
| 29.45 | 163 | 0.573237 |
277646dfe5397c6176dddf8e2e1af2f267bda392 | 8,032 | package uk.gov.hmcts.reform.divorce.orchestration.tasks;
import com.google.common.collect.ImmutableMap;
import feign.FeignException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import uk.gov.hmcts.reform.divorce.orchestration.client.CaseMaintenanceClient;
import uk.gov.hmcts.reform.divorce.orchestration.domain.model.ccd.CaseDetails;
import uk.gov.hmcts.reform.divorce.orchestration.domain.model.ccd.SearchResult;
import uk.gov.hmcts.reform.divorce.orchestration.framework.workflow.task.Task;
import uk.gov.hmcts.reform.divorce.orchestration.framework.workflow.task.TaskContext;
import uk.gov.hmcts.reform.divorce.orchestration.util.CcdUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.toList;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.BulkCaseConstants.BULKCASE_CREATION_ERROR;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.BulkCaseConstants.BULK_CASE_ACCEPTED_LIST_KEY;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.BulkCaseConstants.BULK_CASE_LIST_KEY;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.BulkCaseConstants.BULK_CASE_TITLE_KEY;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.BulkCaseConstants.CASE_LIST_KEY;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.BulkCaseConstants.CASE_PARTIES_FIELD;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.BulkCaseConstants.CASE_REFERENCE_FIELD;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.BulkCaseConstants.COST_ORDER_FIELD;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.BulkCaseConstants.DN_APPROVAL_DATE_FIELD;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.BulkCaseConstants.FAMILY_MAN_REFERENCE_FIELD;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.BulkCaseConstants.SEARCH_RESULT_KEY;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.BulkCaseConstants.VALUE_KEY;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.OrchestrationConstants.AUTH_TOKEN_JSON_KEY;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.OrchestrationConstants.DIVORCE_COSTS_CLAIM_GRANTED_CCD_FIELD;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.OrchestrationConstants.DN_DECISION_DATE_FIELD;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.OrchestrationConstants.D_8_CASE_REFERENCE;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.OrchestrationConstants.D_8_PETITIONER_FIRST_NAME;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.OrchestrationConstants.D_8_PETITIONER_LAST_NAME;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.OrchestrationConstants.RESP_FIRST_NAME_CCD_FIELD;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.OrchestrationConstants.RESP_LAST_NAME_CCD_FIELD;
@Component
@Slf4j
@RequiredArgsConstructor
public class BulkCaseCreateTask implements Task<Map<String, Object>> {
public static final String BULK_CASE_TITLE = "Divorce bulk Case %s";
@Value("${bulk-action.min-cases:30}")
private int minimunCasesToProcess;
private final CaseMaintenanceClient caseMaintenanceClient;
private final CcdUtil ccdUtil;
@Override
public Map<String, Object> execute(TaskContext context, Map<String, Object> payload) {
List<SearchResult> searchResultList = context.getTransientObject(SEARCH_RESULT_KEY);
if (CollectionUtils.isEmpty(searchResultList)) {
log.info("There is no cases to process");
context.setTaskFailed(true);
return Collections.emptyMap();
}
List<Object> errors = new ArrayList<>();
List<Map<String, Object>> bulkCases = new ArrayList<>();
searchResultList.forEach(searchResult -> {
try {
if (minimunCasesToProcess <= searchResult.getCases().size()) {
Map<String, Object> bulkCase = createBulkCase(searchResult);
Map<String, Object> bulkCaseResult = caseMaintenanceClient.submitBulkCase(bulkCase,
context.getTransientObject(AUTH_TOKEN_JSON_KEY));
bulkCases.add(bulkCaseResult);
} else {
log.info("Number of cases do not reach the minimum, Case list size {}", searchResult.getCases().size());
}
} catch (FeignException e) {
//Ignore bulk case creation failed. Next schedule should pickup the remaining cases
// Still need to handle timeout, as the BulkCase could be created.
errors.addAll(searchResult.getCases()
.stream()
.map(CaseDetails::getCaseId)
.collect(toList()));
log.error("Bulk case creation failed.", e);
}
});
Map<String, Object> cases = new HashMap<>();
cases.put(BULK_CASE_LIST_KEY, bulkCases);
if (!errors.isEmpty()) {
context.setTransientObject(BULKCASE_CREATION_ERROR, errors);
//Note to developers. We believe the line above adds no value whatsoever and can be easily removed.
//We've done it as part of branch and written up the details in JIRA ticket RPET-561.
}
return cases;
}
private Map<String, Object> createBulkCase(SearchResult searchResult) {
List<Map<String, Object>> caseList = searchResult.getCases()
.stream()
.map(this::createCaseInBulkCase)
.collect(toList());
List<Map<String, Object>> acceptedCasesList = caseList.stream()
.map(entry -> (Map<String, Object>) entry.get(VALUE_KEY))
.map(entry -> entry.get(CASE_REFERENCE_FIELD))
.map(entry -> ImmutableMap.of(VALUE_KEY, entry))
.collect(toList());
Map<String, Object> bulkCase = new HashMap<>();
bulkCase.put(BULK_CASE_TITLE_KEY, String.format(BULK_CASE_TITLE, ccdUtil.getCurrentDateWithCustomerFacingFormat()));
bulkCase.put(BULK_CASE_ACCEPTED_LIST_KEY, acceptedCasesList);
bulkCase.put(CASE_LIST_KEY, caseList);
return bulkCase;
}
private Map<String, Object> createCaseInBulkCase(CaseDetails caseDetails) {
Map<String, Object> caseInBulk = new HashMap<>();
caseInBulk.put(CASE_REFERENCE_FIELD, getCaseLink(caseDetails));
caseInBulk.put(CASE_PARTIES_FIELD, getCaseParties(caseDetails));
caseInBulk.put(FAMILY_MAN_REFERENCE_FIELD, caseDetails.getCaseData().get(D_8_CASE_REFERENCE));
caseInBulk.put(COST_ORDER_FIELD, caseDetails.getCaseData().get(DIVORCE_COSTS_CLAIM_GRANTED_CCD_FIELD));
caseInBulk.put(DN_APPROVAL_DATE_FIELD, caseDetails.getCaseData().get(DN_DECISION_DATE_FIELD));
return ImmutableMap.of(VALUE_KEY, caseInBulk);
}
private Map<String, Object> getCaseLink(CaseDetails caseDetails) {
return ImmutableMap.of(CASE_REFERENCE_FIELD, caseDetails.getCaseId());
}
private String getCaseParties(CaseDetails caseDetails) {
String petitionerFirstName = (String) caseDetails.getCaseData().get(D_8_PETITIONER_FIRST_NAME);
String petitionerLastName = (String) caseDetails.getCaseData().get(D_8_PETITIONER_LAST_NAME);
String respondentFirstName = (String) caseDetails.getCaseData().get(RESP_FIRST_NAME_CCD_FIELD);
String respondentLastName = (String) caseDetails.getCaseData().get(RESP_LAST_NAME_CCD_FIELD);
return String.format("%s %s vs %s %s", petitionerFirstName, petitionerLastName, respondentFirstName,
respondentLastName);
}
}
| 53.546667 | 130 | 0.747136 |
bf3fa1f1f7f3e4edf1951cf1ae57595e2292f2c7 | 20,407 | package com.mtools.core.plugin.db;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.mtools.core.plugin.entity.BetDates;
import com.mtools.core.plugin.entity.SqlParam;
import com.mtools.core.plugin.helper.AIPGException;
import com.mtools.core.plugin.helper.Auxs;
import com.mtools.core.plugin.helper.FuncUtil;
/**
* @author zhang
* sql 构建工具
* @param <T>
*/
public class DBSqlCreater<T>{
/**
* 查询字段
*/
private List<String> selectFields=new ArrayList<String>();
/**
* 关联的字段(在where条件中使用)
*/
private Map<String,String> connectFields=new HashMap<String, String>();
/**
* 需要使用like的字段(在where条件中使用)
*/
private List<String> likeFields=new ArrayList<String>();
/**
* 作为日期的条件字段(在where条件中使用)
*/
private List<String> dateFeilds=new ArrayList<String>();
/**
* 作为不等值的字段
*/
@SuppressWarnings("rawtypes")
private Map<String,String[]> notEqFeilds=new HashMap<String,String[]>();
/**
* 带查询的对象-也就是对应查询的表的pojo
*/
@SuppressWarnings("rawtypes")
private List tableObjs=new ArrayList();
/**
* 与表对应的pojo
*/
@SuppressWarnings("rawtypes")
private Class tableClz;
private boolean addZeroVal=false;
/**
* 排序字段
*/
private String orderbyField;
/**
* 查询时间段
*/
Map<String,BetDates> betDate;
/**
* 增加查询字段
* @param clz
* @param selectFieldName 对应表中的字段名
* @throws AIPGException
*/
public void addSelField(String selectFieldName) throws AIPGException{
selectFields.add(getTableCln(tableClz,selectFieldName));
}
/**
* 增加查询字段
* @param clz
* @param selectFieldName 对应表中的字段名
* @throws AIPGException
*/
public void addSelField(Class clz,String selectFieldName) throws AIPGException{
selectFields.add(getTableCln(clz,selectFieldName));
}
/**
* 增加关联条件
* 多表关联查询的时候会用上,单表查询的时候用不上
* @param clz
* @param connectFieldName1 对应表中的字段名
* @param connectFieldName2 对应表中的字段名
* @throws AIPGException
*/
public void addConnectField(Class clz,String connectFieldName1,Class clz2,String connectFieldName2) throws AIPGException{
connectFields.put(getTableCln(clz,connectFieldName1),getTableCln(clz2,connectFieldName2));
}
/**
* 指定需要使用like 的字段
* @param clz
* @param likeFieldName 对应表中的字段名
* @throws AIPGException
*/
public void addLiketField(String likeFieldName) throws AIPGException{
likeFields.add(getTableCln(tableClz,likeFieldName));
}
/**
* 指定需要使用like 的字段
* @param clz
* @param likeFieldName 对应表中的字段名
* @throws AIPGException
*/
public void addLiketField(Class clz,String likeFieldName) throws AIPGException{
likeFields.add(getTableCln(clz,likeFieldName));
}
/**
* 指定查询条件类型为日期的字段
* @param clz
* @param dateFieldName 对应表中的字段名
* @throws AIPGException
*/
public void addDateField(String dateFieldName) throws AIPGException{
dateFeilds.add(getTableCln(tableClz,dateFieldName));
}
/**
* 指定查询条件类型为日期的字段
* @param clz
* @param dateFieldName 对应表中的字段名
* @throws AIPGException
*/
public void addDateField(Class clz,String dateFieldName) throws AIPGException{
dateFeilds.add(getTableCln(clz,dateFieldName));
}
/**
* 增加关联查询的表对应的pojo
* @param obj
* @throws AIPGException
*/
public void addTableObj(Object obj) throws AIPGException{
tableObjs.add(obj);
this.tableClz=obj.getClass();
if(tableObjs.size()>1){
this.tableClz=null;
}
}
/**
* 设置不等字段
* @param fieldName 表对应的字段名
* @param values 具体不等的值
* @throws AIPGException
*/
public void addNotEqField(String fieldName,String[] values) throws AIPGException{
notEqFeilds.put(getTableCln(tableClz,fieldName), values);
}
/**
* 设置不等字段
* @param fieldName 表对应的字段名
* @param values 具体不等的值
* @throws AIPGException
*/
public void addNotEqField(Class clz,String fieldName,String[] values) throws AIPGException{
notEqFeilds.put(getTableCln(clz,fieldName), values);
}
/**
* 构建 where 语句
* @param params 参数
* @param likeFeild 需要 使用like 的字段
* @param dateFeilds 数据类型为日期的字段
* @param t 数据对象
* @return
* @throws AIPGException
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public SqlParam buildWhereSql(T t) throws AIPGException{ //得到的sql 类似 and xxxx= and xxx=xx
Map params = buildParams(t);
String dateFormat="yyyymmdd hh24:mi:ss";//数据库的日期格式
String dateFormat2="yyyyMMdd HH:mm:ss";//java的日期格式
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
StringBuffer whereSql=new StringBuffer();
List sqlparams=new ArrayList();
SqlParam sqlParam=new SqlParam();
//日期类型的参数
List dateParams=new ArrayList();
List dateKey=new ArrayList();
// //字符串类型的日期参数
// List dateStrs=new ArrayList();
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
Object value = params.get(key);
StringBuffer tempStr=new StringBuffer();
if(value!=null){
if(value instanceof String){
String val=(String)value;
if(!FuncUtil.isEmpty(val.trim())){
String dateStr = val.trim();
if(dateFeilds!=null&&dateFeilds.contains(key)){
if(dateParams.size()==1){
if(dateStr.length()==8){
dateStr+=" 00:00:00";
}
Date date=FuncUtil.parseTime(dateStr, dateFormat2);
if(date.after((Date)dateParams.get(0))){
dateParams.add(date);
dateKey.add(key);
}else{
dateParams.add(0,date);
dateKey.add(0,key);
}
}else{
dateParams.add(val.trim());
dateKey.add(key);
}
}else if(likeFields!=null&&likeFields.contains(key)){
whereSql.append(" and ").append(key).append(" like ?");
sqlparams.add("%"+val.trim()+"%");
}else if(this.notEqFeilds!=null&&this.notEqFeilds.get(key)!=null){
String[] values=this.notEqFeilds.get(key);
tempStr.append(" and (");
for(String vl:values){
tempStr.append(key).append(" <> ? and ");
sqlparams.add(vl);
}
whereSql.append(tempStr.substring(0, tempStr.length()-4)).append(")");
// System.err.println("**********"+tempStr.substring(0, tempStr.length()-4)+"**********");
}else{
whereSql.append(" and ").append(key).append(" = ?");
sqlparams.add(val.trim());
}
}
}else if(value instanceof Date){
Date date=(Date)value;
if(dateParams.size()==1){
if(dateParams.get(0) instanceof Date){
if(date.after((Date)dateParams.get(0))){
dateParams.add(date);
dateKey.add(key);
}else{
dateParams.add(0,date);
dateKey.add(0,key);
}
}else if(dateParams.get(0) instanceof Timestamp){
if(date.after((Timestamp)dateParams.get(0))){
dateParams.add(date);
dateKey.add(key);
}else{
dateParams.add(0,date);
dateKey.add(0,key);
}
}else{
throw new AIPGException("数据类型有误");
}
}else{
dateParams.add(date);
dateKey.add(key);
}
}else if(value instanceof Timestamp){
Timestamp date=(Timestamp)value;
if(dateParams.size()==1){
if(dateParams.get(0) instanceof Date){
if(date.after((Date)dateParams.get(0))){
dateParams.add(date);
dateKey.add(key);
}else{
dateParams.add(0,date);
dateKey.add(0,key);
}
}else if(dateParams.get(0) instanceof Timestamp){
if(date.after((Timestamp)dateParams.get(0))){
dateParams.add(date);
dateKey.add(key);
}else{
dateParams.add(0,date);
dateKey.add(0,key);
}
}else{
throw new AIPGException("数据类型有误");
}
}else{
dateParams.add(date);
dateKey.add(key);
}
}else if(value instanceof Integer){
whereSql.append(" and ").append(key).append(" = ?");
sqlparams.add((Integer)value);
}else if(value instanceof Float){
whereSql.append(" and ").append(key).append(" = ?");
sqlparams.add((Float)value);
}else if(value instanceof Double){
whereSql.append(" and ").append(key).append(" = ?");
sqlparams.add((Double)value);
}
}
}
//组装日期
if(dateParams.size()==1){
if(dateParams.get(0) instanceof String){
whereSql.append(" and ").append(dateKey.get(0)).append(" = to_date(?,'").append(dateFormat).append("')");
sqlparams.add(dateParams.get(0));
}else{
whereSql.append(" and ").append(dateKey.get(0)).append(" >= to_date(?,'").append(dateFormat).append("')");
whereSql.append(" and ").append(dateKey.get(0)).append(" <= to_date(?,'").append(dateFormat).append("')");
if(dateParams.get(0) instanceof Date){
Date startDate = (Date) dateParams.get(0);
sqlparams.add(FuncUtil.formatTime(startDate, dateFormat2));
sqlparams.add(FuncUtil.formatTime(FuncUtil.nextDate(startDate),dateFormat2));
}else if(dateParams.get(0) instanceof Timestamp){
Timestamp startDate = (Timestamp) dateParams.get(0);
sqlparams.add(FuncUtil.formatTime(startDate, dateFormat2));
sqlparams.add(FuncUtil.formatTime(FuncUtil.nextDate(startDate),dateFormat2));
}
}
}
if(dateParams.size()==2){
if(dateParams.get(0) instanceof String&&dateParams.get(1) instanceof String){
whereSql.append(" and ").append(dateKey.get(0)).append(" >= to_date(?,'").append(dateFormat).append("')");
whereSql.append(" and ").append(dateKey.get(1)).append(" <= to_date(?,'").append(dateFormat).append("')");
sqlparams.add(dateParams.get(0));
sqlparams.add(dateParams.get(1));
}else if((dateParams.get(0) instanceof Date||dateParams.get(0) instanceof Timestamp)&&dateParams.get(1) instanceof String){
whereSql.append(" and ").append(dateKey.get(0)).append(" >= ?");
whereSql.append(" and ").append(dateKey.get(1)).append(" <= to_date(?,'").append(dateFormat).append("')");
if(dateParams.get(0) instanceof Date){
sqlparams.add((Date)dateParams.get(0));
}else if(dateParams.get(0) instanceof Timestamp){
sqlparams.add((Timestamp)dateParams.get(0));
}
sqlparams.add(dateParams.get(1));
}else if((dateParams.get(1) instanceof Date||dateParams.get(1) instanceof Timestamp)&&dateParams.get(0) instanceof String){
whereSql.append(" and ").append(dateKey.get(0)).append(" >= to_date(?,'").append(dateFormat).append("')");
whereSql.append(" and ").append(dateKey.get(1)).append(" <= ?");
if(dateParams.get(1) instanceof Date){
sqlparams.add((Date)dateParams.get(1));
}else if(dateParams.get(1) instanceof Timestamp){
sqlparams.add((Timestamp)dateParams.get(1));
}
sqlparams.add(dateParams.get(0));
}else{
whereSql.append(" and ").append(dateKey.get(0)).append(" >= ?");
whereSql.append(" and ").append(dateKey.get(1)).append(" <= ?");
if(dateParams.get(0) instanceof Date){
sqlparams.add((Date)dateParams.get(0));
}else if(dateParams.get(0) instanceof Timestamp){
sqlparams.add((Timestamp)dateParams.get(0));
}
if(dateParams.get(1) instanceof Date){
sqlparams.add((Date)dateParams.get(1));
}else if(dateParams.get(1) instanceof Timestamp){
sqlparams.add((Timestamp)dateParams.get(1));
}
}
}
//时间段过滤
if(betDate!=null&&betDate.size()>0){
Iterator<Map.Entry<String, BetDates>> bdate = betDate.entrySet().iterator();
while (bdate.hasNext()) {
Map.Entry<String, BetDates> entry = bdate.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
if(entry.getValue().isStr()){
if(entry.getValue().isDbTimeStr()){
whereSql.append(" and ")
.append(" to_date(").append(entry.getKey()).append(",'yyyymmdd')")
.append(">= to_date(?,'yyyymmdd') and ")
.append(" to_date(").append(entry.getKey()).append(",'yyyymmdd')")
.append(" <= to_date(?,'yyyymmdd') ");
}else{
whereSql.append(" and ").append(entry.getKey())
.append(">= to_date(?,' and ")
.append(entry.getKey())
.append(" <= to_date(?,'");
}
sqlparams.add(entry.getValue().getStartDateTimeStr());
sqlparams.add(entry.getValue().getEndDateTimeStr());
}else{
if(entry.getValue().isDbTimeStr()){
whereSql.append(" and ")
.append(" to_date(").append(entry.getKey()).append(",'yyyymmdd')")
.append(">= ? and ")
.append(" to_date(").append(entry.getKey()).append(",'yyyymmdd')")
.append(" <= ? ");
}else{
whereSql.append(" and ")
.append(entry.getKey())
.append(">= ? and ")
.append(entry.getKey())
.append(" <= ? ");
}
sqlparams.add(entry.getValue().getStartDateTime());
sqlparams.add(entry.getValue().getEndDateTime());
}
}
}
if(!FuncUtil.isEmpty(orderbyField)){
whereSql.append(" order by ").append(orderbyField);
}
//返回对象
sqlParam.setSql(whereSql.toString());
sqlParam.setParams(sqlparams);
return sqlParam;
}
/**
* 构建参数
* @param t 对象
* @param addZero 当字段为整型,并且值为零的时候,是否当作参数
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public Map buildParams(T t){
Map params=new HashMap();
Map retPrms=new HashMap();
FuncUtil.cpObj2MapForDB(t, params);
Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
retPrms.put(Auxs.underscoreName(entry.getKey()), entry.getValue());
}
return retPrms;
}
/**
* 构造select 语句
* @param tableObjs 带查询的pojo
* @param selectFields 要查询的字段 为空的时候查询全部 *
* @param connectFields 关联字段
* @return
* @throws AIPGException
*/
@SuppressWarnings({ "rawtypes", "unused" })
public String buildSelect() throws AIPGException{
StringBuffer tempSql=new StringBuffer("select ");
StringBuffer selectSql=new StringBuffer();
if(selectFields!=null&&selectFields.size()>0){
for(String field:selectFields){
tempSql.append(field).append(",");
}
selectSql.append(tempSql.substring(0, tempSql.length()-1));
}else{
tempSql.append(" * ");
selectSql.append(tempSql);
}
tempSql=new StringBuffer();
tempSql.append(" from ");
for(Object table:tableObjs){
tempSql.append(DBUtil.getTableName(table))
.append(" ")
.append(DBUtil.getTableAlis(table.getClass()))
.append(",");
}
selectSql.append(tempSql.substring(0, tempSql.length()-1));
tempSql=new StringBuffer();
tempSql.append(" where 1=1");
if(connectFields!=null&&connectFields.size()>0){
Iterator<Map.Entry<String, String>> it = connectFields.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
tempSql.append(" and ").append(Auxs.underscoreName(entry.getKey())+"="+Auxs.underscoreName(entry.getValue()));
}
}
selectSql.append(tempSql);
return selectSql.toString();
}
/**
* 构造count sql 语句
* @param tableObjs 带查询的pojo
* @param selectFields 要查询的字段 为空的时候查询全部 *
* @param connectFields 关联字段
* @return
* @throws AIPGException
*/
public String buildCountSql() throws AIPGException{
StringBuffer tempSql=new StringBuffer("select 1 ");
StringBuffer selectSql=new StringBuffer();
tempSql.append(" from ");
for(Object table:tableObjs){
tempSql.append(DBUtil.getTableName(table))
.append(" ")
.append(DBUtil.getTableAlis(table.getClass()))
.append(",");
}
selectSql.append(tempSql.substring(0, tempSql.length()-1));
tempSql=new StringBuffer();
tempSql.append(" where 1=1");
if(connectFields!=null&&connectFields.size()>0){
Iterator<Map.Entry<String, String>> it = connectFields.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
tempSql.append(" and ").append(Auxs.underscoreName(entry.getKey())+"="+Auxs.underscoreName(entry.getValue()));
}
}
selectSql.append(tempSql);
return selectSql.toString();
}
/**
* 别名.字段
* @param fieldName
* @return
* @throws AIPGException
*/
public String getTableCln(Class clz,String fieldName) throws AIPGException{
if(clz!=null){
return DBUtil.getTableAlis(clz)+"."+fieldName;
}else{
return fieldName;
}
}
public boolean isAddZeroVal() {
return addZeroVal;
}
public void setAddZeroVal(boolean addZeroVal) {
this.addZeroVal = addZeroVal;
}
public String getOrderbyField() {
return orderbyField;
}
public void setOrderbyField(Class clz,String orderbyField,String ascOrDes) throws AIPGException {
if(!FuncUtil.isEmpty(ascOrDes)){
this.orderbyField = getTableCln(clz,orderbyField)+" "+ascOrDes;
}else{
setOrderbyField(clz, orderbyField);
}
}
public void setOrderbyField(String orderbyField,String ascOrDes) throws AIPGException {
if(!FuncUtil.isEmpty(ascOrDes)){
this.orderbyField = getTableCln(this.tableClz,orderbyField)+" "+ascOrDes;
}else{
setOrderbyField(this.tableClz, orderbyField);
}
}
public void setOrderbyField(Class clz,String orderbyField) throws AIPGException {
this.orderbyField = getTableCln(clz,orderbyField);
}
public void setOrderbyField(String orderbyField) throws AIPGException {
this.orderbyField = getTableCln(this.tableClz,orderbyField);
}
public Map<String, BetDates> getBetDate() {
return betDate;
}
public void setBetDate(Map<String, BetDates> betDate) {
this.betDate = betDate;
}
public Class getTableClz() {
return tableClz;
}
public void setTableClz(Class tableClz) {
this.tableClz = tableClz;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws AIPGException {
// Map params=new HashMap();
// params.put("name", "zhanggh");
// params.put("age", 26);
// params.put("thisYear","20141112");
// params.put("birthday",FuncUtil.parseStampTime("19880210", "yyyyMMdd"));
// params.put("name", "zhanggh");
// params.put("alisName", "kanckzhang");
// List<String> likeFields=new ArrayList<String>();
// likeFields.add("alisName");
//
// List<String> dateFields=new ArrayList<String>();
// dateFields.add("thisYear");
// SqlParam sqlParam=buildWhereSql(params, likeFields, null,"");
// System.err.println(sqlParam.getSql());
}
}
| 33.842454 | 132 | 0.58524 |
524f528533b04cb97692c268311112feed6805d1 | 1,309 | /*
* Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.glassfish.jaxb.runtime.v2.model.annotation;
import org.glassfish.jaxb.core.v2.model.annotation.Locatable;
import jakarta.xml.bind.annotation.XmlElementRef;
import jakarta.xml.bind.annotation.XmlElementRefs;
import java.lang.annotation.Annotation;
/**
* <p><b>Auto-generated, do not edit.</b></p>
*
*/
final class XmlElementRefsQuick
extends Quick
implements XmlElementRefs
{
private final XmlElementRefs core;
public XmlElementRefsQuick(Locatable upstream, XmlElementRefs core) {
super(upstream);
this.core = core;
}
protected Annotation getAnnotation() {
return core;
}
protected Quick newInstance(Locatable upstream, Annotation core) {
return new XmlElementRefsQuick(upstream, ((XmlElementRefs) core));
}
public Class<XmlElementRefs> annotationType() {
return XmlElementRefs.class;
}
public XmlElementRef[] value() {
return core.value();
}
}
| 24.698113 | 78 | 0.708938 |
565b73f60e75a4b4c373b055d0461a01ae1408bd | 953 | package camelinaction;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.processor.loadbalancer.SimpleLoadBalancerSupport;
/**
* A custom load balancer which will pick the first processor for gold messages,
* and the 2nd processor for other kind of messages.
* <p/>
* Notice we extend the {@link SimpleLoadBalancerSupport} which provides
* all the proper start and stop logic.
*/
public class MyCustomLoadBalancer extends SimpleLoadBalancerSupport {
public void process(Exchange exchange) throws Exception {
Processor target = chooseProcessor(exchange);
target.process(exchange);
}
protected Processor chooseProcessor(Exchange exchange) {
String type = exchange.getIn().getHeader("type", String.class);
if ("gold".equals(type)) {
return getProcessors().get(0);
} else {
return getProcessors().get(1);
}
}
}
| 30.741935 | 80 | 0.700944 |
541652e71f09ff9475ab4f2b0e3d7bfd3bc9ef0d | 1,441 | package spaceinvaders.command.client;
import static spaceinvaders.command.ProtocolEnum.TCP;
import spaceinvaders.client.ClientConfig;
import spaceinvaders.client.mvc.Controller;
import spaceinvaders.client.mvc.Model;
import spaceinvaders.client.mvc.View;
import spaceinvaders.command.Command;
import spaceinvaders.command.server.ConfigurePlayerCommand;
/** Set the id of the player, which is generated by the server. */
public class SetPlayerIdCommand extends Command {
private transient Controller executor;
private Integer id;
SetPlayerIdCommand() {
super(SetPlayerIdCommand.class.getName(),TCP);
}
/**
* @param id the id of the player.
*/
public SetPlayerIdCommand(int id) {
this();
this.id = id;
}
@Override
public void execute() {
ClientConfig config = ClientConfig.getInstance();
config.setId(id);
System.out.println("SetPlayerIdCommand: CLIENT ID: " + id); // print client ID
Model model = executor.getModel();
model.doCommand(new ConfigurePlayerCommand(config.getUserName(),config.getTeamSize(),
config.getUdpIncomingPort(), config.getPing()));
for (View view : executor.getViews()) {
view.showGame();
}
}
@Override
public void setExecutor(Object executor) {
if (executor instanceof Controller) {
this.executor = (Controller) executor;
} else {
// This should never happen.
throw new AssertionError();
}
}
}
| 27.711538 | 89 | 0.7127 |
f139351f16cadd5fbe941e5baa1bbff11ca07ae3 | 2,087 | package io.github.ykalay.rabbitmqtunnel.config;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import java.util.Objects;
/**
* Rabbitmq Pool configuration class
*
* @author ykalay
*
* @since 1.0
*/
public class RabbitmqPoolConfig {
/**
* Singleton lazy instance of {@link RabbitmqPoolConfig}
*/
private static RabbitmqPoolConfig LAZY_HOLDER;
/**
* @return singleton lazy instance of {@link RabbitmqPoolConfig}
*/
public static RabbitmqPoolConfig getInstance() {
if(Objects.isNull(LAZY_HOLDER)) {
LAZY_HOLDER = new RabbitmqPoolConfig();
}
return LAZY_HOLDER;
}
private RabbitmqPoolConfig() {init();}
private GenericObjectPoolConfig<com.rabbitmq.client.Channel> DEFAULT_POOL_CONFIG = new GenericObjectPoolConfig<>();
private GenericObjectPoolConfig<com.rabbitmq.client.Channel> poolConfig;
private void init() {
int numProcessor = Runtime.getRuntime().availableProcessors();
// Default config channel pool
DEFAULT_POOL_CONFIG.setMaxTotal(numProcessor * numProcessor);
DEFAULT_POOL_CONFIG.setMaxIdle(numProcessor * numProcessor);
DEFAULT_POOL_CONFIG.setMinIdle(numProcessor);
DEFAULT_POOL_CONFIG.setNumTestsPerEvictionRun(numProcessor * 2);
DEFAULT_POOL_CONFIG.setBlockWhenExhausted(false);
DEFAULT_POOL_CONFIG.setMinEvictableIdleTimeMillis(3600000);
DEFAULT_POOL_CONFIG.setTimeBetweenEvictionRunsMillis(1500000);
// Set is as default at the first time
if(Objects.isNull(poolConfig)) {
this.poolConfig = DEFAULT_POOL_CONFIG;
}
}
public GenericObjectPoolConfig<com.rabbitmq.client.Channel> getPoolConfig() {
// If the custom poolConfig is not given just use the DEFAULT one
if(Objects.isNull(poolConfig)) {
return DEFAULT_POOL_CONFIG;
}
return poolConfig;
}
public void setPoolConfig(GenericObjectPoolConfig<com.rabbitmq.client.Channel> poolConfig) {
this.poolConfig = poolConfig;
}
}
| 31.149254 | 119 | 0.702444 |
cc59d3051691e35cc4d882e656bdc2b9b5916c30 | 14,056 | /*
* 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
* <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.apache.solr.benchmarks.solrcloud;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.solr.benchmarks.beans.Cluster;
import org.apache.solr.benchmarks.beans.IndexBenchmark;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.CollectionAdminRequest.Create;
import org.apache.solr.client.solrj.request.CollectionAdminRequest.Delete;
import org.apache.solr.client.solrj.request.ConfigSetAdminRequest;
import org.apache.solr.client.solrj.request.HealthCheckRequest;
import org.apache.solr.client.solrj.request.RequestWriter;
import org.apache.solr.client.solrj.response.CollectionAdminResponse;
import org.apache.solr.client.solrj.response.HealthCheckResponse;
import org.apache.solr.common.cloud.SolrZkClient;
import org.apache.solr.common.cloud.ZkConfigManager;
import org.apache.solr.common.params.ConfigSetParams;
import org.apache.solr.common.params.SolrParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
public class SolrCloud {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
Zookeeper zookeeper;
public List<SolrNode> nodes = Collections.synchronizedList(new ArrayList());
private Set<String> configsets = new HashSet<>();
private Set<String> colls = new HashSet<>();
final Cluster cluster;
private final String solrPackagePath;
public SolrCloud(Cluster cluster, String solrPackagePath) throws Exception {
this.cluster = cluster;
this.solrPackagePath = solrPackagePath;
log.info("Provisioning method: " + cluster.provisioningMethod);
}
/**
* A method used for getting ready to set up the Solr Cloud.
* @throws Exception
*/
public void init() throws Exception {
if ("local".equalsIgnoreCase(cluster.provisioningMethod)) {
zookeeper = new LocalZookeeper();
int initValue = zookeeper.start();
if (initValue != 0) {
log.error("Failed to start Zookeeper!");
throw new RuntimeException("Failed to start Zookeeper!");
}
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()/2+1, new ThreadFactoryBuilder().setNameFormat("nodestarter-threadpool").build());
for (int i = 1; i <= cluster.numSolrNodes; i++) {
Callable c = () -> {
SolrNode node = new LocalSolrNode(solrPackagePath, cluster.startupParams, zookeeper);
try {
node.init();
node.start();
nodes.add(node);
log.info("Nodes started: "+nodes.size());
//try (HttpSolrClient client = new HttpSolrClient.Builder(node.getBaseUrl()).build();) {
//log.info("Health check: "+ new HealthCheckRequest().process(client) + ", Nodes started: "+nodes.size());
//} catch (Exception ex) {
// log.error("Problem starting node: "+node.getBaseUrl());
//throw new RuntimeException("Problem starting node: "+node.getBaseUrl());
//}
return node;
} catch (Exception ex) {
ex.printStackTrace();
log.error("Problem starting node: "+node.getBaseUrl());
return null;
}
};
executor.submit(c);
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.HOURS);
log.info("Looking for healthy nodes...");
List<SolrNode> healthyNodes = new ArrayList<>();
for (SolrNode node: nodes) {
try (HttpSolrClient client = new HttpSolrClient.Builder(node.getBaseUrl().substring(0, node.getBaseUrl().length()-1)).build();) {
HealthCheckRequest req = new HealthCheckRequest();
HealthCheckResponse rsp;
try {
rsp = req.process(client);
} catch (Exception ex) {
Thread.sleep(100);
rsp = req.process(client);
}
if (rsp.getNodeStatus().equalsIgnoreCase("ok") == false) {
log.error("Couldn't start node: "+node.getBaseUrl());
throw new RuntimeException("Couldn't start node: "+node.getBaseUrl());
} else {
healthyNodes.add(node);
}
} catch (Exception ex) {
ex.printStackTrace();
log.error("Problem starting node: "+node.getBaseUrl());
}
}
this.nodes = healthyNodes;
log.info("Healthy nodes: "+healthyNodes.size());
} else if ("terraform-gcp".equalsIgnoreCase(cluster.provisioningMethod)) {
System.out.println("Solr nodes: "+getSolrNodesFromTFState());
System.out.println("ZK node: "+getZkNodeFromTFState());
zookeeper = new GenericZookeeper(getZkNodeFromTFState());
for (String host: getSolrNodesFromTFState()) {
nodes.add(new GenericSolrNode(host));
}
} else if ("vagrant".equalsIgnoreCase(cluster.provisioningMethod)) {
System.out.println("Solr nodes: "+getSolrNodesFromVagrant());
System.out.println("ZK node: "+getZkNodeFromVagrant());
zookeeper = new GenericZookeeper(getZkNodeFromVagrant());
for (String host: getSolrNodesFromVagrant()) {
nodes.add(new GenericSolrNode(host));
}
}
}
List<String> getSolrNodesFromTFState() throws JsonMappingException, JsonProcessingException, IOException {
List<String> out = new ArrayList<String>();
Map<String, Object> tfstate = new ObjectMapper().readValue(FileUtils.readFileToString(new File("terraform/terraform.tfstate"), "UTF-8"), Map.class);
for (Map m: (List<Map>)((Map)((Map)tfstate.get("outputs")).get("solr_node_details")).get("value")) {
out.add(m.get("name").toString());
}
return out;
}
String getZkNodeFromTFState() throws JsonMappingException, JsonProcessingException, IOException {
Map<String, Object> tfstate = new ObjectMapper().readValue(FileUtils.readFileToString(new File("terraform/terraform.tfstate"), "UTF-8"), Map.class);
for (Map m: (List<Map>)((Map)((Map)tfstate.get("outputs")).get("zookeeper_details")).get("value")) {
return m.get("name").toString();
}
throw new RuntimeException("Couldn't get ZK node from tfstate");
}
List<String> getSolrNodesFromVagrant() throws JsonMappingException, JsonProcessingException, IOException {
List<String> out = new ArrayList<String>();
Map<String, Object> servers = new ObjectMapper().readValue(FileUtils.readFileToString(new File("vagrant/solr-servers.json"), "UTF-8"), Map.class);
for (String server: servers.keySet()) {
out.add(servers.get(server).toString());
}
return out;
}
String getZkNodeFromVagrant() throws JsonMappingException, JsonProcessingException, IOException {
Map<String, Object> servers = new ObjectMapper().readValue(FileUtils.readFileToString(new File("vagrant/zk-servers.json"), "UTF-8"), Map.class);
for (String server: servers.keySet()) {
return servers.get(server).toString();
}
throw new RuntimeException("Couldn't get ZK node from tfstate");
}
/**
* A method used for creating a collection.
*
* @param collectionName
* @param configName
* @param shards
* @param replicas
* @throws Exception
*/
public void createCollection(IndexBenchmark.Setup setup, String collectionName, String configsetName) throws Exception {
try (HttpSolrClient hsc = createClient()) {
Create create;
if (setup.replicationFactor != null) {
create = Create.createCollection(collectionName, configsetName, setup.shards, setup.replicationFactor);
create.setMaxShardsPerNode(setup.shards*(setup.replicationFactor));
} else {
create = Create.createCollection(collectionName, configsetName, setup.shards,
setup.nrtReplicas, setup.tlogReplicas, setup.pullReplicas);
create.setMaxShardsPerNode(setup.shards
* ((setup.pullReplicas==null? 0: setup.pullReplicas)
+ (setup.nrtReplicas==null? 0: setup.nrtReplicas)
+ (setup.tlogReplicas==null? 0: setup.tlogReplicas)));
}
CollectionAdminResponse resp;
if (setup.collectionCreationParams != null && setup.collectionCreationParams.isEmpty()==false) {
resp = new CreateWithAdditionalParameters(create, collectionName, setup.collectionCreationParams).process(hsc);
} else {
resp = create.process(hsc);
}
log.info("Collection created: "+ resp.jsonStr());
}
colls.add(setup.collection);
}
HttpSolrClient createClient() {
return new HttpSolrClient.Builder(nodes.get(0).getBaseUrl()).build();
}
/**
* A method for deleting a collection.
*
* @param collectionName
* @throws Exception
*/
public void deleteCollection(String collectionName) throws Exception {
try (HttpSolrClient hsc = createClient()) {
Delete delete = Delete.deleteCollection(collectionName); //Create.createCollection(collectionName, shards, replicas);
CollectionAdminResponse resp = delete.process(hsc);
log.info("Collection delete: "+resp.getCollectionStatus());
}
}
/**
* A method used to get the zookeeper url for communication with the solr
* cloud.
*
* @return String
*/
public String getZookeeperUrl() {
return zookeeper.getHost() + ":" + zookeeper.getPort();
}
/**
* A method used for shutting down the solr cloud.
* @throws Exception
*/
public void shutdown(boolean cleanup) throws Exception {
if (cluster.provisioningMethod.equalsIgnoreCase("local")) {
for (String coll : colls) {
try (HttpSolrClient hsc = createClient()) {
try {
CollectionAdminRequest.deleteCollection(coll).process(hsc);
} catch (Exception e) {
//failed but continue
}
}
}
//cleanup configsets created , if any
/*for (String configset : configsets) {
try (HttpSolrClient hsc = createClient()) {
try {
new ConfigSetAdminRequest.Delete().setConfigSetName(configset).process(hsc);
} catch (Exception e) {
//failed but continue
e.printStackTrace();
}
}
}*/
for (SolrNode node : nodes) {
node.stop();
if (cleanup) {
node.cleanup();
}
}
if (cleanup) {
zookeeper.stop();
zookeeper.cleanup();
}
}
}
public void uploadConfigSet(String configsetFile, String configsetZkName) throws Exception {
if(configsetFile==null || configsets.contains(configsetZkName)) return;
log.info("Configset: " +configsetZkName+
" does not exist. creating... ");
File f = new File(configsetFile + ".zip");
if (!f.exists()) {
throw new RuntimeException("Could not find configset file: " + configsetFile);
}
try (HttpSolrClient hsc = createClient()) {
ConfigSetAdminRequest.Create create = new ConfigSetAdminRequest.Create() {
@Override
public RequestWriter.ContentWriter getContentWriter(String expectedType) {
return new RequestWriter.ContentWriter() {
@Override
public void write(OutputStream os) throws IOException {
try (InputStream is = new FileInputStream(f)) {
IOUtils.copy(is, os);
}
}
@Override
public String getContentType() {
return "Content-Type:application/octet-stream";
}
};
}
@Override
public SolrParams getParams() {
super.action = ConfigSetParams.ConfigSetAction.UPLOAD;
return super.getParams();
}
};
try {
ConfigSetAdminRequest.Delete delete = new ConfigSetAdminRequest.Delete();
delete.setConfigSetName(configsetZkName);
delete.process(hsc);
} catch (Exception ex) {
//log.warn("Exception trying to delete configset", ex);
}
create.setMethod(SolrRequest.METHOD.POST);
create.setConfigSetName(configsetZkName);
create.process(hsc);
configsets.add(configsetZkName);
// This is a hack. We want all configsets to be trusted. Hence, unsetting the data on the znode that has trusted=false.
try (SolrZkClient zkClient = new SolrZkClient(zookeeper.getHost() + ":" + zookeeper.getPort(), 100)) {
zkClient.setData(ZkConfigManager.CONFIGS_ZKNODE + "/" + configsetZkName, (byte[]) null, true);
}
log.info("Configset: " + configsetZkName +
" created successfully ");
}
}
} | 37.185185 | 187 | 0.682129 |
9d0cbe8c1d8b92ff66b7342f64030c597e11cd1d | 13,869 | package com.example.radu5.android_sqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* Created by radu5 on 1/28/2018.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_PATH="/data/data/com.example.radu5.android_sqlite/databases/";
private String EXTERNAL_DB_PATH;
private static String DATABASE_NAME="myDatabase";
private SQLiteDatabase myDatabase;
private final Context myContext;
public DatabaseHelper(Context context)
{
super(context,DATABASE_NAME,null,1);//Creaza o baza de date goala
this.myContext=context;
Log.i("database","OPENED OR CREATED DATABASE");
}
public void createDataBase(String path) throws IOException {
EXTERNAL_DB_PATH=path;
boolean dbExists=checkDataBase();
String DB_NAME=path.substring(path.lastIndexOf("/")+1);
if(dbExists)
{
Log.i("database","Baza de date exita deja "+ DATABASE_NAME+" ,nu mai copiez "+DB_NAME);
}
else
{
this.getReadableDatabase();
try
{
Log.i("database","Copiez baza de date :"+EXTERNAL_DB_PATH +" Numita: "+DB_NAME);
copyDataBase(path);
}
catch(Exception e)
{
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase()
{
SQLiteDatabase checkDB=null;
try
{
String myPath=DB_PATH+DATABASE_NAME;
checkDB=SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READONLY);
}
catch(Exception e)
{
Log.i("database","Baza de date nu exita deja "+ DATABASE_NAME);
}
if(checkDB!=null)
{
checkDB.close();
}
return checkDB!=null ? true : false;
}
private void copyDataBase(String path) throws IOException{
InputStream myInput=new FileInputStream(path);
String outFileName=DB_PATH+DATABASE_NAME;
OutputStream myOutput=new FileOutputStream(outFileName);
byte[] buffer=new byte[1024];
int length;
while((length=myInput.read(buffer))>0)
{
myOutput.write(buffer,0,length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public SQLiteDatabase openDataBase()throws SQLException{
String myPath=DB_PATH+DATABASE_NAME;
myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
Log.i("database","Baza de date deschisa "+DATABASE_NAME);
return myDatabase;
}
public void stergeDatabase()
{
Log.i("database","Baza de date stearsa "+DATABASE_NAME);
myContext.deleteDatabase(DATABASE_NAME);
}
public void saveDatabase()
{
try{
File src=new File(DB_PATH+DATABASE_NAME);
File dest=new File(EXTERNAL_DB_PATH);
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest,false);
byte[] buf=new byte[1024];
int len;
while((len=in.read(buf))>0)
{
out.write(buf,0,len);
}
out.flush();
in.close();
out.close();
Log.i("database","Baza de date salvata "+EXTERNAL_DB_PATH);
}catch(Exception e)
{
Log.i("database","Baza de date nu a putut fi salvata "+EXTERNAL_DB_PATH);
}
}
public ArrayList<String> getColValues(String tbName,String colName)
{
ArrayList<String> arrColVal = new ArrayList<String>();
try {
Cursor c = myDatabase.rawQuery("SELECT " + colName + " FROM " + tbName+" ORDER BY "+colName+" ASC", null);
while(c.moveToNext())
{
arrColVal.add(c.getString(0));
}
c.close();
}
catch(Exception e)
{
}
return arrColVal;
}
//cazul cheie primara compozita
public ArrayList<String> getColValuesIfPk(String tbName,String colName,String fkName,String fkTable,Rand rand)
{
ArrayList<String> arrColVal = new ArrayList<String>();
String sql="SELECT "+colName+" FROM "+tbName+" WHERE "+colName+" NOT IN ( " +
"SELECT "+fkName+" FROM "+fkTable+" WHERE ";
boolean primaCheie=true;
for ( int i=0;i<rand.getCheiPrimare().size();i++)
{
if(rand.getCheiPrimare().get(i).getColumn_name().equals(fkName))
{
continue;
}
if(rand.getCheiPrimare().get(i).getType().equals("TEXT"))
{
if(primaCheie==true)
{
sql+=rand.getCheiPrimare().get(i).getColumn_name()+"="+"'"+rand.getValoriCheiPrimare().get(i)+"' ";
primaCheie=false;
}
else
{
sql+="AND "+rand.getCheiPrimare().get(i).getColumn_name()+"="+"'"+rand.getValoriCheiPrimare().get(i)+"' ";
}
}
else
{
if(primaCheie==true)
{
sql+=rand.getCheiPrimare().get(i).getColumn_name()+"="+rand.getValoriCheiPrimare().get(i)+" ";
primaCheie=false;
}
else
{
sql+="AND "+rand.getCheiPrimare().get(i).getColumn_name()+"="+rand.getValoriCheiPrimare().get(i)+" ";;
}
}
}
sql+=" ) ORDER BY "+colName+" ASC";
try {
Cursor c = myDatabase.rawQuery(sql, null);
while(c.moveToNext())
{
arrColVal.add(c.getString(0));
}
c.close();
}
catch(Exception e)
{
}
return arrColVal;
}
public void insert(String sql,int r) throws Exception
{
myDatabase.rawQuery(sql,null).moveToFirst();
}
public void delete(String sql) throws Exception
{
myDatabase.rawQuery(sql,null).moveToFirst();
}
public void updateFk(String sql) throws Exception
{
myDatabase.rawQuery(sql,null).moveToFirst();
}
public boolean checkDanglingPointer(String data,String dataType,String destCol,String desTable) throws Exception
{
if(dataType.equals("TEXT"))
{
String sql="SELECT "+destCol+" FROM "+desTable+" WHERE "+destCol+"="+"'"+data+"'";
Cursor c=myDatabase.rawQuery(sql,null);
if(c.moveToNext())//exista
{
c.close();
return false;// False = nu e dangling pointer
}
else
{
c.close();
return true;//nu exista
}
}
else//celelalte tipuri de date
{
String sql="SELECT "+destCol+" FROM "+desTable+" WHERE "+destCol+"="+data;
Cursor c=myDatabase.rawQuery(sql,null);
if (c.moveToNext())//exista
{
c.close();
return false;
} else {
c.close();
return true;//nu exista
}
}
}
public int isReferentialIntegrityEnforced()//1=true
{
int i=2;
Cursor c=myDatabase.rawQuery("PRAGMA foreign_keys",null);
try
{
c.moveToFirst();
i=c.getInt(0);
}catch(Exception e)
{
}
c.close();
return i;
}
public void enforceReferencialIntegrity(int t)
{
try {
myDatabase.execSQL("PRAGMA foreign_keys=" + t);
}catch(Exception e)
{e.printStackTrace();}
}
public ArrayList<String> getTabeleProblema()
{
Cursor c=myDatabase.rawQuery("PRAGMA foreign_key_check",null);
ArrayList<String> tables=new ArrayList<>();
Set<String> t=new HashSet<>();
try{
int tableIdx=c.getColumnIndexOrThrow("table");
while (c.moveToNext())
{
String tname=c.getString(tableIdx);
t.add(tname);
}
c.close();
}catch(Exception e)
{
}
tables.addAll(t);
return tables;
}
public ArrayList<Integer> areProblemeIntegritate(String tableName)
{
Cursor c=myDatabase.rawQuery("PRAGMA foreign_key_check("+tableName+")",null);
ArrayList<Integer> fks=new ArrayList<>();
Set<Integer> fkids=new HashSet<>();
try{
int fkidIdx=c.getColumnIndexOrThrow("fkid");
while (c.moveToNext())
{
int fkid=c.getInt(fkidIdx);
fkids.add(fkid);
}
}catch(Exception e)
{
}finally{
c.close();
}
if(fkids.isEmpty()==true)
return null;
else
{
fks.addAll(fkids);
return fks;//return list of fkids unde sunt probleme
}
}
public Cursor getTableData(String tableName)
{
Cursor c=myDatabase.rawQuery("SELECT * FROM "+tableName,null);
return c;
}
public ArrayList<Coloana> getColumns(String tableName)
{
ArrayList<Coloana> columns=new ArrayList<Coloana>();
Cursor c=myDatabase.rawQuery("PRAGMA table_info("+tableName+")",null);
try{
int nameIdx = c.getColumnIndexOrThrow("name");
int typeIdx = c.getColumnIndexOrThrow("type");
int notNullIdx = c.getColumnIndexOrThrow("notnull");
int dfltValueIdx = c.getColumnIndexOrThrow("dflt_value");
int pkIdx=c.getColumnIndexOrThrow("pk");
while(c.moveToNext())//parcurge info
{
String nume=c.getString(nameIdx);
String tip=c.getString(typeIdx);
int nn=c.getInt(notNullIdx);
boolean notNull=false;
if(nn==1)
{
notNull=true;
}
String defaultValue=c.getString(dfltValueIdx);
int pk=c.getInt(pkIdx);
boolean primaryKey=false;
if(pk!=0)
{
primaryKey=true;
}
Coloana col=new Coloana(nume,tip,notNull,defaultValue,primaryKey,pk);
columns.add(col);
}
}catch(Exception e)
{
Log.i("SQLERR","Nu am putut sa scot informatii despre coloane");
}
finally {
c.close();
}
Cursor c1=myDatabase.rawQuery("PRAGMA foreign_key_list("+tableName+")",null);
try{
int tableIdx = c1.getColumnIndexOrThrow("table");
int fromIdx = c1.getColumnIndexOrThrow("from");
int toIdx = c1.getColumnIndexOrThrow("to");
int fkidIdx=c1.getColumnIndexOrThrow("id");
int fkseqIdx=c1.getColumnIndexOrThrow("seq");
while (c1.moveToNext())
{
String table=c1.getString(tableIdx);
String from=c1.getString(fromIdx);
String to=c1.getString(toIdx);
int id=c1.getInt(fkidIdx);
int seq=c1.getInt(fkseqIdx);
for(Coloana i:columns)
{
if(i.getColumn_name().equals(from))
{
i.setFk(true);
i.setFkDestCol(to);
i.setFkDestTable(table);
i.setFk_id(id);//ex 2 chei cu id 1 (lafel) -> cheie face parte dintr-o cheie compozita
i.setFk_seq(seq);
break;
}
}
}
}
catch(Exception e)
{
Log.i("SQLERR","Nu am putut sa scot informatii despre chei straine");
}
finally {
c1.close();
}
//pentru CHECK si UNIQUE si alte constrangeri, trebuie sa fac un parse la stringu de creeare sql
return columns;
}
public ArrayList<String> getTableNames()
{
ArrayList<String> arrTblNames = new ArrayList<String>();
Cursor c = myDatabase.rawQuery("SELECT name FROM sqlite_master WHERE type='table'"+" AND name!='android_metadata' " +
"AND name!='sqlite_sequence'",
null);
if (c.moveToFirst()) {
while ( !c.isAfterLast() ) {
arrTblNames.add( c.getString( c.getColumnIndex("name")) );
c.moveToNext();
}
}
c.close();
return arrTblNames;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
Log.i("database","Baza de date creata ");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
@Override
public synchronized void close() {
if(myDatabase!=null) {
Log.i("database","Baza de date inchiza myDatabase.close()");
myDatabase.close();
}
super.close();
}
}
| 32.104167 | 126 | 0.534429 |
e69f0f84cf980fee5933b0c7e082c0d03a1c146c | 1,509 | package io.mdsl.generator;
import org.eclipse.emf.common.util.URI;
import org.eclipse.xtext.generator.IFileSystemAccess2;
import io.mdsl.apiDescription.EndpointContract;
import io.mdsl.apiDescription.ServiceSpecification;
import io.mdsl.dsl.ServiceSpecificationAdapter;
import io.mdsl.generator.freemarker.FreemarkerEngineWrapper;
import io.mdsl.generator.graphql.GraphQLOperationInputTypeNameResolver;
import io.mdsl.generator.graphql.GraphQLSimpleTypeMappingMethod;
/**
* Generates GraphQL with Freemarker template
*/
public class GraphQLGenerator extends AbstractMDSLGenerator {
@Override
protected void generateFromServiceSpecification(ServiceSpecification mdslSpecification, IFileSystemAccess2 fsa, URI inputFileURI) {
// generate graphql file per endpoint
for (EndpointContract endpoint : new ServiceSpecificationAdapter(mdslSpecification).getEndpointContracts()) {
FreemarkerEngineWrapper fmew = new FreemarkerEngineWrapper(GraphQLGenerator.class, "MDSL2GraphQL.ftl");
// pass endpoint name for which graphql shall be generated
fmew.registerCustomData("graphQLEndpointName", endpoint.getName());
// register custom methods for GraphQL template
fmew.registerCustomData("mapType", new GraphQLSimpleTypeMappingMethod());
fmew.registerCustomData("resolveOperationInputName", new GraphQLOperationInputTypeNameResolver());
fsa.generateFile(inputFileURI.trimFileExtension().lastSegment() + "_" + endpoint.getName() + ".graphql", fmew.generate(mdslSpecification));
}
}
}
| 43.114286 | 142 | 0.821074 |
fbc56a7bc77c0a5ad9a51f466f5f77b61a2e73a5 | 1,063 | package com.networknt.ac.handler;
import com.networknt.config.Config;
import com.networknt.handler.LightHttpHandler;
import com.networknt.server.Server;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This API is a sink API that means it only called by others but not calling anyone else.
*
* @author Steve Hu
*/
public class DataGetHandler implements LightHttpHandler {
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
// get the current address and port from the Server. Cannot use the server.yml value as the dynamic port might be used.
int port = Server.currentPort;
String address = Server.currentAddress;
List<String> messages = new ArrayList<>();
messages.add("API C: Message from " + address + ":" + port);
exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(messages));
}
}
| 34.290323 | 127 | 0.734713 |
99113e563bdfc81bd422f79831431c7e29d7ccf7 | 2,393 | // Copyright 2021 The KeepTry Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package tree.binarytree;
public class Leetcode426ConvertBinarySearchTreetoSortedDoublyLinkedList {
static class Node {
public int val;
public Node left;
public Node right;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right) {
val = _val;
left = _left;
right = _right;
}
}
/*
The number of nodes in the tree is in the range [0, 2000].
-1000 <= Node.val <= 1000
All the values of the tree are unique.
Question:
Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place.
return the pointer to the smallest element of the linked list.
Idea:
divide-conquer idea:
need help function to do:
- sub-tree-> double linked list
- right-tree->double linked list
- merge left list+ current node + right list
need checking null in advance
the result is the head and tail of the double linked list.
at last connect the head and tail and return the head(smallest one)
O(N) time, O(H) space used by recursion. H is height of tree.
*/
public static Node treeToDoublyList(Node root) {
if (root == null) return null;
Node[] ht = inOrder(root); // head and tail of double linked list
Node h = ht[0], t = ht[1];
h.left = t;
t.right = h;
return h;
}
public static Node[] inOrder(Node root) {
Node h, t; // head and tail
if (root.left != null) {
Node[] ht = inOrder(root.left);
h = ht[0];
ht[1].right = root;
root.left = ht[1];
} else h = root;
if (root.right != null) {
Node[] ht = inOrder(root.right);
t = ht[1];
ht[0].left = root;
root.right = ht[0];
} else t = root;
return new Node[] {h, t};
}
}
| 27.825581 | 82 | 0.645215 |
7ae306c1d30231a89fa1918b48a39f8838b218aa | 418 | package com.example;
@Marker
public class Person {
private String fullName;
private Address address;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
| 16.076923 | 46 | 0.626794 |
c8cb4b75d1c0fb36c741e94e84e125eb06afe095 | 5,676 |
package com.gmonetix.bookspivot.activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.SupportActivity;
import android.support.v4.util.Pair;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.gmonetix.bookspivot.R;
import com.gmonetix.bookspivot.model.Upload;
import com.gmonetix.bookspivot.util.Constants;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import static com.facebook.FacebookSdk.getApplicationContext;
public class firstfragment extends Fragment {
// Store instance variables
private String title;
private int page;
DatabaseReference mDatabaseReference;
ListView list;
List<Upload> uploadList;
String[] book_name = {
"Book 1",
"Book 2",
"Book 3",
// "Book 4",
// "Book 5",
// "Book 6",
// "Book 7"
} ;
Integer[] imageId = {
R.drawable.bglogin2,
R.drawable.bglogin2,
R.drawable.bglogin2,
// R.drawable.bglogin2,
// R.drawable.bglogin2,
// R.drawable.bglogin2,
// R.drawable.bglogin2
};
String[] book_upload = {
"Uploaded on jan 10, 2017",
"Uploaded on jan 10, 2017",
"Uploaded on Aug 26, 2017",
// "Uploaded on Aug 26, 2017",
//"Uploaded on Aug 26, 2017",
//"Uploaded on Aug 26, 2017",
// "Uploaded on Aug 26, 2017"
} ;
String[] book_download = {
"123 Downloads",
"123 Downloads",
"123 Downloads",
// "123 Downloads",
// "123 Downloads",
// "123 Downloads",
// "123 Downloads"
} ;
// newInstance constructor for creating fragment with arguments
public static firstfragment newInstance(int page, String title) {
firstfragment fragmentFirst = new firstfragment();
Bundle args = new Bundle();
// args.putInt("someInt", page);
args.putString("Title", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
// Store instance variables based on arguments passed
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("Title");
uploadList = new ArrayList<>();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_firstfragment, container, false);
FragmentList adapter = new
FragmentList(getActivity(), book_name, imageId , book_upload, book_download);
list=(ListView) view.findViewById(R.id.list1);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Upload upload = uploadList.get(position);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(upload.getUrl()));
startActivity(intent);
Toast.makeText(getActivity(), "You Clicked at " +book_name[+ position], Toast.LENGTH_SHORT).show();
}
});
//getting the database reference
mDatabaseReference = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS);
//retrieving upload data from firebase database
mDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
uploadList.add(upload);
}
String[] uploads = new String[uploadList.size()];
for (int i = 0; i < uploads.length; i++) {
uploads[i] = uploadList.get(i).getName();
// uploads[i]=uploadList.get(i).getAuthor();
// uploads[i]=uploadList.get(i).getEdition();
}
//displaying it to list
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, uploads);
list.setAdapter(adapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
// the following are default settings
}
| 33.192982 | 143 | 0.624912 |
81ec90009d289aa2cc2532b87956953a072ae9c8 | 2,552 | package com.taotao.cloud.order.api.vo.cart;
import cn.lili.modules.order.cart.entity.enums.DeliveryMethodEnum;
import cn.lili.modules.promotion.entity.dos.MemberCoupon;
import cn.lili.modules.promotion.entity.vos.CouponVO;
import io.swagger.v3.oas.annotations.media.Schema;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 购物车展示VO
*
* @since 2020-03-24 10:33 上午
*/
@Schema(description = "购物车展示VO")
public class CartVO extends CartBase implements Serializable {
private static final long serialVersionUID = -5651775413457562422L;
@Schema(description = "购物车中的产品列表")
private List<CartSkuVO> skuList;
@Schema(description = "sn")
private String sn;
@Schema(description = "购物车页展示时,店铺内的商品是否全选状态.1为店铺商品全选状态,0位非全选")
private Boolean checked;
@Schema(description = "满优惠活动")
private FullDiscountVO fullDiscount;
@Schema(description = "满优惠促销的商品")
private List<String> fullDiscountSkuIds;
@Schema(description = "是否满优惠")
private Boolean isFull;
@Schema(description = "使用的优惠券列表")
private List<MemberCoupon> couponList;
@Schema(description = "使用的优惠券列表")
private List<CouponVO> canReceiveCoupon;
@Schema(description = "赠品列表")
private List<String> giftList;
@Schema(description = "赠送优惠券列表")
private List<String> giftCouponList;
@Schema(description = "赠送积分")
private Integer giftPoint;
@Schema(description = "重量")
private Double weight;
@Schema(description = "购物车商品数量")
private Integer goodsNum;
@Schema(description = "购物车商品数量")
private String remark;
/**
* @see DeliveryMethodEnum
*/
@Schema(description = "配送方式")
private String deliveryMethod;
@Schema(description = "已参与的的促销活动提示,直接展示给客户")
private String promotionNotice;
public CartVO(CartSkuVO cartSkuVO) {
this.setStoreId(cartSkuVO.getStoreId());
this.setStoreName(cartSkuVO.getStoreName());
this.setSkuList(new ArrayList<>());
this.setCouponList(new ArrayList<>());
this.setGiftList(new ArrayList<>());
this.setGiftCouponList(new ArrayList<>());
this.setChecked(false);
this.isFull = false;
this.weight = 0d;
this.giftPoint = 0;
this.remark = "";
}
public void addGoodsNum(Integer goodsNum) {
if (this.goodsNum == null) {
this.goodsNum = goodsNum;
} else {
this.goodsNum += goodsNum;
}
}
/**
* 过滤购物车中已选择的sku
*
* @return
*/
public List<CartSkuVO> getCheckedSkuList() {
if (skuList != null && !skuList.isEmpty()) {
return skuList.stream().filter(CartSkuVO::getChecked).collect(Collectors.toList());
}
return skuList;
}
}
| 23.2 | 86 | 0.731975 |
8d548f9ccb1d053e78510a10f5b2a13cf6b505a5 | 762 | /*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxauth.client.model.authorize;
/**
* @author Javier Rojas Blum Date: 03.07.2012
*/
public class Claim {
private String name;
private ClaimValue claimValue;
public Claim(String name, ClaimValue claimValue) {
this.name = name;
this.claimValue = claimValue;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ClaimValue getClaimValue() {
return claimValue;
}
public void setClaimValue(ClaimValue claimValue) {
this.claimValue = claimValue;
}
} | 20.594595 | 106 | 0.641732 |
e3fb3178e27b506c58f358bb8653dd8dc687aed3 | 734 | package lee.code.code_386__Lexicographical_Numbers;
import java.util.*;
import lee.util.*;
/**
*
*
* 386.Lexicographical Numbers
*
* difficulty: Medium
* @see https://leetcode.com/problems/lexicographical-numbers/description/
* @see description_386.md
* @Similiar Topics
* @Similiar Problems
* Run solution from Unit Test:
* @see lee.codetest.code_386__Lexicographical_Numbers.CodeTest
* Run solution from Main Judge Class:
* @see lee.code.code_386__Lexicographical_Numbers.C386_MainClass
*
*/
class Solution {
public List<Integer> lexicalOrder(int n) {
return null;
}
}
class Main1 {
public static void main(String[] args) {
//new Solution();
}
}
| 20.388889 | 73 | 0.675749 |
08bc2731d4afbaed3e7285f0f15b613211d98781 | 811 | package com.jiangfw.common.lang.test.json.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
/**
* Created by jiangfw on 2019/1/8.
*/
public class JacksonUtil {
private static ObjectMapper mapper = new ObjectMapper();
public static String bean2Json(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
try {
return mapper.readValue(jsonStr, objClass);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
| 23.852941 | 70 | 0.630086 |
26a3d2c10b25b9ebf3b3b0495c84661cdf7eda92 | 2,014 | package com.skytala.eCommerce.domain.shipment.relations.shipment.command.gatewayConfig;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.DelegatorFactory;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.GenericEntityNotFoundException;
import com.skytala.eCommerce.domain.shipment.relations.shipment.event.gatewayConfig.ShipmentGatewayConfigUpdated;
import com.skytala.eCommerce.domain.shipment.relations.shipment.model.gatewayConfig.ShipmentGatewayConfig;
import com.skytala.eCommerce.framework.exceptions.RecordNotFoundException;
import com.skytala.eCommerce.framework.pubsub.Broker;
import com.skytala.eCommerce.framework.pubsub.Command;
import com.skytala.eCommerce.framework.pubsub.Event;
public class UpdateShipmentGatewayConfig extends Command {
private ShipmentGatewayConfig elementToBeUpdated;
public UpdateShipmentGatewayConfig(ShipmentGatewayConfig elementToBeUpdated){
this.elementToBeUpdated = elementToBeUpdated;
}
public ShipmentGatewayConfig getElementToBeUpdated() {
return elementToBeUpdated;
}
public void setElementToBeUpdated(ShipmentGatewayConfig elementToBeUpdated){
this.elementToBeUpdated = elementToBeUpdated;
}
@Override
public Event execute() throws RecordNotFoundException{
Delegator delegator = DelegatorFactory.getDelegator("default");
boolean success;
try{
GenericValue newValue = delegator.makeValue("ShipmentGatewayConfig", elementToBeUpdated.mapAttributeField());
delegator.store(newValue);
if(delegator.store(newValue) == 0) {
throw new RecordNotFoundException(ShipmentGatewayConfig.class);
}
success = true;
} catch (GenericEntityException e) {
e.printStackTrace();
if(e.getCause().getClass().equals(GenericEntityNotFoundException.class)) {
throw new RecordNotFoundException(ShipmentGatewayConfig.class);
}
success = false;
}
Event resultingEvent = new ShipmentGatewayConfigUpdated(success);
Broker.instance().publish(resultingEvent);
return resultingEvent;
}
}
| 37.296296 | 113 | 0.84856 |
8e27fa7861da86a4806104f09e00ee681bb6ea37 | 675 | package com.otuadraw.data.model;
import com.otuadraw.enums.ShapeEnum;
import lombok.Getter;
import lombok.Setter;
public class InkFile {
private InkTrail inkTrail;
@Getter
@Setter
private ShapeEnum guess;
@Getter
@Setter
private boolean isTempFile;
@Getter
@Setter
private boolean isDirty;
public InkFile() {
inkTrail = new InkTrail();
isTempFile = true;
}
public void clear(){
inkTrail = new InkTrail();
guess = null;
}
public InkTrail getInkTrail(){
return inkTrail.copy();
}
public void append(InkPoint inkPoint){
inkTrail.push(inkPoint);
}
}
| 16.875 | 42 | 0.623704 |
33acb16687964efcf4433a81fc2e3868dd74007d | 1,579 | /*
* Copyright (c) 2006 JMockit developers
* This file is subject to the terms of the MIT license (see LICENSE.txt).
*/
package mockit.internal.reflection;
import java.lang.reflect.*;
import javax.annotation.*;
import static mockit.internal.util.Utilities.ensureThatMemberIsAccessible;
public final class FieldReflection
{
private FieldReflection() {}
@Nullable
public static <T> T getFieldValue(@Nonnull Field field, @Nullable Object targetObject) {
ensureThatMemberIsAccessible(field);
try {
if (targetObject != null && !field.getDeclaringClass().isInstance(targetObject)) {
Field outerInstanceField = targetObject.getClass().getDeclaredField("this$0");
targetObject = getFieldValue(outerInstanceField, targetObject);
}
//noinspection unchecked
return (T) field.get(targetObject);
}
catch (IllegalAccessException | NoSuchFieldException e) { throw new RuntimeException(e); }
}
public static void setFieldValue(@Nonnull Field field, @Nullable Object targetObject, @Nullable Object value) {
ensureThatMemberIsAccessible(field);
try {
if (targetObject != null && !field.getDeclaringClass().isInstance(targetObject)) {
Field outerInstanceField = targetObject.getClass().getDeclaredField("this$0");
targetObject = getFieldValue(outerInstanceField, targetObject);
}
field.set(targetObject, value);
}
catch (IllegalAccessException | NoSuchFieldException e) { throw new RuntimeException(e); }
}
}
| 34.326087 | 114 | 0.697277 |
a803e2c4f5a4a87480172a4d6fe581513438b591 | 7,003 | package org.meowcat.mp3desktop.qin;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
BatteryManager mBatteryManager;
AudioManager mAudioManager;
WebView mWebView;
long keyDownTimestamp = 0;
public static void openApp(Context context, String packageName) {
final Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
Objects.requireNonNull(intent).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
context.startActivity(intent);
}
public static void openApp(Context context, String packageName, String activityName) {
Intent intent = new Intent().setComponent(new ComponentName(packageName, activityName));
Objects.requireNonNull(intent).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
context.startActivity(intent);
}
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBatteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mWebView = findViewById(R.id.webView);
mWebView.setBackgroundColor(0);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new JavaScript(), "java");
mWebView.getSettings().setDefaultTextEncodingName("utf-8");
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder b = new AlertDialog.Builder(mWebView.getContext());
String[] content = message.split(":",2);
b.setTitle(content[0]);
b.setMessage(content[1]);
b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
b.setCancelable(false);
b.create().show();
return true;
}
});
mWebView.loadUrl("file:///android_asset/meowcat/meowcat.html");
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (keyDownTimestamp == 0) {
keyDownTimestamp = System.currentTimeMillis();
}
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
return true;
default:
return super.onKeyDown(keyCode, event);
}
}
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_HOME:
case KeyEvent.KEYCODE_APP_SWITCH:
case KeyEvent.KEYCODE_BACK:
return true;
default:
return super.onKeyUp(keyCode, event);
}
}
public void finish() {}
@SuppressWarnings("unused")
public class JavaScript {
@JavascriptInterface
public void startApplication(final String packageName) {
try {
getPackageManager().getPackageInfo(packageName, PackageManager.GET_GIDS);
openApp(getApplicationContext(), packageName);
} catch (PackageManager.NameNotFoundException e) {
Toast.makeText(MainActivity.this, "组件" + packageName + "缺失,无法启动。", Toast.LENGTH_SHORT).show();
}
}
@JavascriptInterface
public void startApplication(final String packageName, final String activityName) {
try {
getPackageManager().getPackageInfo(packageName, PackageManager.GET_GIDS);
openApp(getApplicationContext(), packageName, activityName);
} catch (PackageManager.NameNotFoundException e) {
Toast.makeText(MainActivity.this, "组件" + packageName + "缺失,无法启动。", Toast.LENGTH_SHORT).show();
}
}
@JavascriptInterface
public String getStringInfo(final String info) {
switch (info) {
case "DeviceBrand":
return Build.BRAND;
case "DeviceModel":
return Build.MODEL;
case "DeviceSDK":
return "" + Build.VERSION.SDK_INT;
case "Version":
return BuildConfig.VERSION_NAME;
default:
return null;
}
}
@JavascriptInterface
public int getIntInfo(final String info) {
switch (info) {
case "BatteryNumber":
return mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
case "BatteryStatus":
return mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_STATUS);
case "HeadSet":
if (mAudioManager == null) {
return 0;
}
AudioDeviceInfo[] audioDevices = mAudioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
for (AudioDeviceInfo deviceInfo : audioDevices) {
if (deviceInfo.getType() == AudioDeviceInfo.TYPE_WIRED_HEADPHONES || deviceInfo.getType() == AudioDeviceInfo.TYPE_WIRED_HEADSET) {
return 1;
} else if (deviceInfo.getType() == AudioDeviceInfo.TYPE_USB_HEADSET) {
return 2;
}
}
return 0;
default:
return 0;
}
}
}
}
| 40.953216 | 155 | 0.598886 |
ddbbee37fe851629088ccfb06c73a0bf315ceedb | 447 | //,temp,HistoryServerFileSystemStateStoreService.java,201,211,temp,ZKRMStateStore.java,1140,1152
//,3
public class xxx {
@Override
public void removeTokenMasterKey(DelegationKey key)
throws IOException {
if (LOG.isDebugEnabled()) {
LOG.debug("Removing master key " + key.getKeyId());
}
Path keyPath = new Path(tokenKeysStatePath,
TOKEN_MASTER_KEY_FILE_PREFIX + key.getKeyId());
deleteFile(keyPath);
}
}; | 27.9375 | 96 | 0.709172 |
1af0f1acd5debc23a2c774b94f8967d21ea49bc1 | 14,543 | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* 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.aws.iot.edgeconnectorforkvs.videorecorder.module.camera;
import static org.mockito.BDDMockito.*;
import com.aws.iot.edgeconnectorforkvs.videorecorder.base.RecorderCameraBase.CapabilityListener;
import com.aws.iot.edgeconnectorforkvs.videorecorder.base.RecorderCameraBase.ErrorListener;
import com.aws.iot.edgeconnectorforkvs.videorecorder.base.RecorderCameraBase.NewPadListener;
import com.aws.iot.edgeconnectorforkvs.videorecorder.module.camera.RecorderCameraRtsp.SdpCallback;
import com.aws.iot.edgeconnectorforkvs.videorecorder.util.GstDao;
import org.freedesktop.gstreamer.Caps;
import org.freedesktop.gstreamer.Element;
import org.freedesktop.gstreamer.Pad;
import org.freedesktop.gstreamer.PadLinkException;
import org.freedesktop.gstreamer.Pipeline;
import org.freedesktop.gstreamer.SDPMessage;
import org.freedesktop.gstreamer.Structure;
import org.freedesktop.gstreamer.lowlevel.GstAPI.GstCallback;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class RecorderCameraRtspUnitTest {
private static final String RTSP_URL = "rtspt://test";
private static final String RTP_CAP = "application/x-rtp";
private static final String NRTP_CAP = "application/not-rtp";
@Mock
private GstDao mockGst;
@Mock
private Pipeline mockPipeline;
@Mock
private SDPMessage mockSdp;
@Mock
private Element mockRtsp;
@Mock
private Pad mockPad;
@Mock
private Caps mockCaps;
@Mock
private Structure mockProp;
private CapabilityListener capListener;
private NewPadListener padListener;
private ErrorListener errListener;
private SdpCallback sdpListener;
private Element.PAD_ADDED padAddListener;
@BeforeEach
void setupTest() {
this.capListener = (audioCnt, videoCnt) -> {
};
this.padListener = (cap, newPad) -> {
};
this.errListener = desc -> {
};
willAnswer(invocation -> {
this.sdpListener = invocation.getArgument(2);
return null;
}).given(this.mockGst).connectElement(any(), eq("on-sdp"), any(GstCallback.class));
willAnswer(invocation -> {
this.padAddListener = invocation.getArgument(1);
return null;
}).given(this.mockGst).connectElement(any(), any(Element.PAD_ADDED.class));
willReturn(mockRtsp).given(mockGst).newElement(eq("rtspsrc"));
}
@Test
void onSdpTest_invokeSdpListener_noException() {
willDoNothing().given(this.mockGst).setElement(any(), anyString(), any());
willThrow(new IllegalArgumentException()).given(this.mockGst).setElement(any(),
eq("invalid_property"), any());
RecorderCameraRtsp camera =
new RecorderCameraRtsp(this.mockGst, this.mockPipeline, RTSP_URL);
Assertions.assertDoesNotThrow(() -> camera.setProperty("invalid_property", 0));
Assertions.assertDoesNotThrow(() -> camera.setProperty("location", RTSP_URL));
camera.onBind();
Assertions.assertDoesNotThrow(() -> camera.registerListener(this.capListener,
this.padListener, this.errListener));
Assertions.assertDoesNotThrow(() -> camera.setProperty("location", RTSP_URL));
Assertions.assertDoesNotThrow(() -> camera.setProperty("invalid_property", 0));
// RTSP contains both video and audio
willReturn("m=audio\nm=video").given(this.mockSdp).toString();
Assertions.assertDoesNotThrow(
() -> this.sdpListener.callback(this.mockRtsp, this.mockSdp, null));
// RTSP contains video only
willReturn("m=video").given(this.mockSdp).toString();
Assertions.assertDoesNotThrow(
() -> this.sdpListener.callback(this.mockRtsp, this.mockSdp, null));
// RTSP contains audio only
willReturn("m=audio").given(this.mockSdp).toString();
Assertions.assertDoesNotThrow(
() -> this.sdpListener.callback(this.mockRtsp, this.mockSdp, null));
// RTSP doesn't contain video or audio
willReturn("").given(this.mockSdp).toString();
Assertions.assertDoesNotThrow(
() -> this.sdpListener.callback(this.mockRtsp, this.mockSdp, null));
camera.onUnbind();
}
@Test
void onPadAddedTest_invalidRtp_noException() {
willReturn(this.mockCaps).given(this.mockGst).getPadCaps(eq(this.mockPad));
willReturn(1).given(this.mockCaps).size();
willReturn(this.mockProp).given(this.mockGst).getCapsStructure(eq(this.mockCaps), anyInt());
RecorderCameraRtsp camera =
new RecorderCameraRtsp(this.mockGst, this.mockPipeline, RTSP_URL);
camera.registerListener(this.capListener, this.padListener, this.errListener);
camera.onBind();
// Test: not x-rtp
willReturn(NRTP_CAP).given(this.mockGst).getStructureName(eq(this.mockProp));
Assertions.assertDoesNotThrow(
() -> this.padAddListener.padAdded(this.mockRtsp, this.mockPad));
// Test: x-rtp, No media and No encode
willReturn(RTP_CAP).given(this.mockGst).getStructureName(eq(this.mockProp));
willReturn(false).given(this.mockGst).hasStructureField(eq(this.mockProp), eq("media"));
willReturn(false).given(this.mockGst).hasStructureField(eq(this.mockProp),
eq("encoding-name"));
Assertions.assertDoesNotThrow(
() -> this.padAddListener.padAdded(this.mockRtsp, this.mockPad));
// Test: x-rtp, No media
willReturn(true).given(this.mockGst).hasStructureField(eq(this.mockProp),
eq("encoding-name"));
Assertions.assertDoesNotThrow(
() -> this.padAddListener.padAdded(this.mockRtsp, this.mockPad));
// Test: x-rtp, No encode
willReturn(true).given(this.mockGst).hasStructureField(eq(this.mockProp), eq("media"));
willReturn(false).given(this.mockGst).hasStructureField(eq(this.mockProp),
eq("encoding-name"));
Assertions.assertDoesNotThrow(
() -> this.padAddListener.padAdded(this.mockRtsp, this.mockPad));
// Test x-rtp, NOT video and NOT audio
willReturn(true).given(this.mockGst).hasStructureField(eq(this.mockProp), eq("media"));
willReturn(true).given(this.mockGst).hasStructureField(eq(this.mockProp),
eq("encoding-name"));
willReturn("subtitle").given(this.mockGst).getStructureString(eq(this.mockProp),
eq("media"));
Assertions.assertDoesNotThrow(
() -> this.padAddListener.padAdded(this.mockRtsp, this.mockPad));
camera.onUnbind();
}
@Test
void onPadAddedTest_videoH264_noException() {
willReturn(this.mockCaps).given(this.mockGst).getPadCaps(eq(this.mockPad));
willReturn(1).given(this.mockCaps).size();
willReturn(this.mockProp).given(this.mockGst).getCapsStructure(eq(this.mockCaps), anyInt());
willReturn(this.mockPad).given(this.mockGst).getElementStaticPad(any(), anyString());
willReturn(RTP_CAP).given(this.mockGst).getStructureName(eq(this.mockProp));
willReturn(true).given(this.mockGst).hasStructureField(eq(this.mockProp), eq("media"));
willReturn(true).given(this.mockGst).hasStructureField(eq(this.mockProp),
eq("encoding-name"));
willReturn("video").given(this.mockGst).getStructureString(eq(this.mockProp), eq("media"));
willReturn("H264").given(this.mockGst).getStructureString(eq(this.mockProp),
eq("encoding-name"));
RecorderCameraRtsp camera =
new RecorderCameraRtsp(this.mockGst, this.mockPipeline, RTSP_URL);
camera.registerListener(this.capListener, this.padListener, this.errListener);
camera.onBind();
// Test not linked yet
willReturn(false).given(this.mockGst).isPadLinked(eq(this.mockPad));
Assertions.assertDoesNotThrow(
() -> this.padAddListener.padAdded(this.mockRtsp, this.mockPad));
// Test: link failed and PadLinkException is handled in recorder PadLinkException
PadLinkException mockPadLinkEx = mock(PadLinkException.class);
willThrow(mockPadLinkEx).given(mockGst).linkPad(any(Pad.class), any(Pad.class));
Assertions.assertDoesNotThrow(
() -> this.padAddListener.padAdded(this.mockRtsp, this.mockPad));
// Test: already linked
willReturn(true).given(this.mockGst).isPadLinked(eq(this.mockPad));
Assertions.assertDoesNotThrow(
() -> this.padAddListener.padAdded(this.mockRtsp, this.mockPad));
camera.onUnbind();
}
@Test
void onPadAddedTest_videoVp8_noException() {
willReturn(this.mockCaps).given(this.mockGst).getPadCaps(eq(this.mockPad));
willReturn(1).given(this.mockCaps).size();
willReturn(this.mockProp).given(this.mockGst).getCapsStructure(eq(this.mockCaps), anyInt());
willReturn(this.mockPad).given(this.mockGst).getElementStaticPad(any(), anyString());
willReturn(RTP_CAP).given(this.mockGst).getStructureName(eq(this.mockProp));
willReturn(true).given(this.mockGst).hasStructureField(eq(this.mockProp), eq("media"));
willReturn(true).given(this.mockGst).hasStructureField(eq(this.mockProp),
eq("encoding-name"));
willReturn("video").given(this.mockGst).getStructureString(eq(this.mockProp), eq("media"));
willReturn("VP8").given(this.mockGst).getStructureString(eq(this.mockProp),
eq("encoding-name"));
RecorderCameraRtsp camera =
new RecorderCameraRtsp(this.mockGst, this.mockPipeline, RTSP_URL);
camera.registerListener(this.capListener, this.padListener, this.errListener);
camera.onBind();
// Test not linked yet
willReturn(false).given(this.mockGst).isPadLinked(eq(this.mockPad));
Assertions.assertDoesNotThrow(
() -> this.padAddListener.padAdded(this.mockRtsp, this.mockPad));
camera.onUnbind();
}
@Test
void onPadAddedTest_audioAAC_noException() {
willReturn(this.mockCaps).given(this.mockGst).getPadCaps(eq(this.mockPad));
willReturn(1).given(this.mockCaps).size();
willReturn(this.mockProp).given(this.mockGst).getCapsStructure(eq(this.mockCaps), anyInt());
willReturn(this.mockPad).given(this.mockGst).getElementStaticPad(any(), anyString());
willReturn(RTP_CAP).given(this.mockGst).getStructureName(eq(this.mockProp));
willReturn(true).given(this.mockGst).hasStructureField(eq(this.mockProp), eq("media"));
willReturn(true).given(this.mockGst).hasStructureField(eq(this.mockProp),
eq("encoding-name"));
willReturn("audio").given(this.mockGst).getStructureString(eq(this.mockProp), eq("media"));
willReturn("MPEG4-GENERIC").given(this.mockGst).getStructureString(eq(this.mockProp),
eq("encoding-name"));
RecorderCameraRtsp camera =
new RecorderCameraRtsp(this.mockGst, this.mockPipeline, RTSP_URL);
camera.registerListener(this.capListener, this.padListener, this.errListener);
camera.onBind();
// Test not linked yet
willReturn(false).given(this.mockGst).isPadLinked(eq(this.mockPad));
Assertions.assertDoesNotThrow(
() -> this.padAddListener.padAdded(this.mockRtsp, this.mockPad));
// Test: link failed and PadLinkException is handled in recorder PadLinkException
PadLinkException mockPadLinkEx = mock(PadLinkException.class);
willThrow(mockPadLinkEx).given(mockGst).linkPad(any(Pad.class), any(Pad.class));
Assertions.assertDoesNotThrow(
() -> this.padAddListener.padAdded(this.mockRtsp, this.mockPad));
// Test: already linked
willReturn(true).given(this.mockGst).isPadLinked(eq(this.mockPad));
Assertions.assertDoesNotThrow(
() -> this.padAddListener.padAdded(this.mockRtsp, this.mockPad));
camera.onUnbind();
}
@Test
void onPadAddedTest_unsupportedEncode_noException() {
willReturn(this.mockCaps).given(this.mockGst).getPadCaps(eq(this.mockPad));
willReturn(1).given(this.mockCaps).size();
willReturn(this.mockProp).given(this.mockGst).getCapsStructure(eq(this.mockCaps), anyInt());
willReturn(RTP_CAP).given(this.mockGst).getStructureName(eq(this.mockProp));
willReturn(true).given(this.mockGst).hasStructureField(eq(this.mockProp), eq("media"));
willReturn(true).given(this.mockGst).hasStructureField(eq(this.mockProp),
eq("encoding-name"));
willReturn("unsupported").given(this.mockGst).getStructureString(eq(this.mockProp),
eq("encoding-name"));
RecorderCameraRtsp camera =
new RecorderCameraRtsp(this.mockGst, this.mockPipeline, RTSP_URL);
camera.registerListener(this.capListener, this.padListener, this.errListener);
camera.onBind();
// Test: x-rtp, video, unsupported encode
willReturn("video").given(this.mockGst).getStructureString(eq(this.mockProp), eq("media"));
Assertions.assertDoesNotThrow(
() -> this.padAddListener.padAdded(this.mockRtsp, this.mockPad));
// Test: x-rtp, audio, unsupported encode
willReturn("audio").given(this.mockGst).getStructureString(eq(this.mockProp), eq("media"));
Assertions.assertDoesNotThrow(
() -> this.padAddListener.padAdded(this.mockRtsp, this.mockPad));
camera.onUnbind();
}
}
| 46.463259 | 100 | 0.682046 |
8f715e8c2e0d422eb6c0e841535fff5410a848f2 | 4,896 | package ee.ttu.thesis.model.processor;
import static ee.ttu.thesis.util.Logger.log;
/**
*
*/
public class Result {
public static final double THRESHOLD_PERCENTAGE = 100;
private String metricName;
private String unit;
private double average;
private double median;
private double range;
private double max;
private double min;
private double diffAverage;
private double squareRootAverage;
private double standardDeviation;
public Result(String metricName, String unit, double average, double median, double range, double max, double min, double diffAverage, double squareRootAverage, double standardDeviation) {
this(average, median, range, max, min, diffAverage, squareRootAverage, standardDeviation);
this.metricName = metricName;
this.unit = unit;
}
public Result(double average, double median, double range, double max, double min, double diffAverage, double squareRootAverage, double standardDeviation) {
this.average = average;
this.median = median;
this.range = range;
this.max = max;
this.min = min;
this.diffAverage = diffAverage;
this.squareRootAverage = squareRootAverage;
this.standardDeviation = standardDeviation;
}
public double getAverage() {
return average;
}
public void setAverage(double average) {
this.average = average;
}
public double getMedian() {
return median;
}
public void setMedian(double median) {
this.median = median;
}
public double getRange() {
return range;
}
public void setRange(double range) {
this.range = range;
}
public double getMax() {
return max;
}
public void setMax(double max) {
this.max = max;
}
public double getMin() {
return min;
}
public void setMin(double min) {
this.min = min;
}
public double getDiffAverage() {
return diffAverage;
}
public void setDiffAverage(double diffAverage) {
this.diffAverage = diffAverage;
}
public double getSquareRootAverage() {
return squareRootAverage;
}
public void setSquareRootAverage(double squareRootAverage) {
this.squareRootAverage = squareRootAverage;
}
public double getStandardDeviation() {
return standardDeviation;
}
public void setStandardDeviation(double standardDeviation) {
this.standardDeviation = standardDeviation;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getMetricName() {
return metricName;
}
public void setMetricName(String metricName) {
this.metricName = metricName;
}
public void print() {
log(String.format("-----------%-30s-------------", metricName));
log(String.format("%-20s %10.2f %s", "average", average, unit));
log(String.format("%-20s %10.2f %s", "median", median, unit));
log(String.format("%-20s %10.2f %s", "range", range, unit));
log(String.format("%-20s %10.2f %s", "max", max, unit));
log(String.format("%-20s %10.2f %s", "min", min, unit));
log(String.format("%-20s %10.2f %s", "diffAverage", diffAverage, unit));
log(String.format("%-20s %10.2f", "squareRootAverage", squareRootAverage));
log(String.format("%-20s %10.2f", "standardDeviation", standardDeviation));
log(String.format("------------------------------------------------------"));
}
public void compare(Result result) {
evaluate("average",this.average, result.getAverage());
evaluate("median",this.median, result.getMedian());
evaluate("range",this.range, result.getRange());
evaluate("max",this.max, result.getMax());
evaluate("min",this.min, result.getMin());
evaluate("diffAverage",this.diffAverage, result.getDiffAverage());
evaluate("squareRootAverage",this.squareRootAverage, result.getSquareRootAverage());
evaluate("standardDeviation",this.standardDeviation, result.getStandardDeviation());
}
protected static double changePercentage(double oldValue, double newValue) {
double diff = Math.abs(oldValue - newValue);
double percentage = diff /oldValue;
if (Double.isInfinite(percentage)) {
return 0;
}
return percentage;
}
protected void evaluate(String attribute, double oldValue, double newValue) {
double percentage = changePercentage(oldValue, newValue);
percentage *= 100;
if (percentage > THRESHOLD_PERCENTAGE) {
System.out.println(String.format("Metric %-30s %-18s differed from last by %8.03f%%", this.metricName ,attribute, percentage));
}
}
}
| 29.672727 | 192 | 0.629085 |
2a0a08ca41d14ace82b95628696a3ba7ae39fe3c | 7,177 | package fr.ign.validator.validation.database;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import fr.ign.validator.Context;
import fr.ign.validator.database.Database;
import fr.ign.validator.error.CoreErrorCodes;
import fr.ign.validator.error.ErrorScope;
import fr.ign.validator.error.ValidatorError;
import fr.ign.validator.model.AttributeType;
import fr.ign.validator.model.DocumentModel;
import fr.ign.validator.model.FeatureType;
import fr.ign.validator.model.FileModel;
import fr.ign.validator.model.file.SingleTableModel;
import fr.ign.validator.model.type.StringType;
import fr.ign.validator.report.InMemoryReportBuilder;
public class AttributeUniqueValidatorTest {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private InMemoryReportBuilder reportBuilder = new InMemoryReportBuilder();
private Context context;
@Before
public void setUp() throws NoSuchAuthorityCodeException, FactoryException {
context = new Context();
context.setProjection("EPSG:4326");
context.setReportBuilder(reportBuilder);
// creates attribute "id" which is an identifier
AttributeType<String> attribute = new StringType();
attribute.setName("ID");
attribute.getConstraints().setUnique(true);
// creates attribute "relation_id" which is NOT an identifier
AttributeType<String> attribute2 = new StringType();
attribute2.setName("RELATION_ID");
// creates list of attributes
List<AttributeType<?>> attributes = new ArrayList<>();
attributes.add(attribute);
attributes.add(attribute2);
// creates a FeatureType with both attributes
FeatureType featureType = new FeatureType();
featureType.setAttributes(attributes);
// creates a FeatureType with only 'id' attribute
FeatureType featureType2 = new FeatureType();
featureType2.addAttribute(attribute);
// creates a FileModel with the first Feature Type
SingleTableModel fileModel = new SingleTableModel();
fileModel.setName("TEST");
fileModel.setFeatureType(featureType);
// reates a FileModel with the second Feature Type
SingleTableModel fileModel2 = new SingleTableModel();
fileModel2.setName("RELATION");
fileModel2.setFeatureType(featureType2);
// creates a List<FileModel> with both FileModel
List<FileModel> fileModels = new ArrayList<>();
fileModels.add(fileModel);
fileModels.add(fileModel2);
// creates a DocumentModel with the List<FileModel>
DocumentModel documentModel = new DocumentModel();
documentModel.setName("SAMPLE_MODEL");
documentModel.setFileModels(fileModels);
context.beginModel(documentModel);
}
@Test
public void testValid() throws Exception {
// creates an empty database
File path = new File(folder.getRoot(), "document_database.db");
Database database = new Database(path);
// add the table TEST into the database
database.query("CREATE TABLE TEST(id TEXT, relation_id TEXT);");
database.query("INSERT INTO TEST(id, relation_id) VALUES ('test_1', 'relation_1');");
database.query("INSERT INTO TEST(id, relation_id) VALUES ('test_2', 'relation_2');");
database.query("INSERT INTO TEST(id, relation_id) VALUES ('test_3', 'relation_1');");
database.query("INSERT INTO TEST(id, relation_id) VALUES ('test_4', 'relation_3');");
// add the table RELATION into the database
database.query("CREATE TABLE RELATION(id TEXT);");
database.query("INSERT INTO RELATION(id) VALUES ('relation_1');");
database.query("INSERT INTO RELATION(id) VALUES ('relation_2');");
database.query("INSERT INTO RELATION(id) VALUES ('relation_3');");
// check that the validator doesn't send any error
AttributeUniqueValidator identifierValidator = new AttributeUniqueValidator();
identifierValidator.validate(context, database);
Assert.assertEquals(0, reportBuilder.getErrorsByCode(CoreErrorCodes.ATTRIBUTE_NOT_UNIQUE).size());
}
@Test
public void testNotValid() throws Exception {
// creates an empty database
File path = new File(folder.getRoot(), "document_database.db");
Database database = new Database(path);
// add the table TEST into the database
database.query("CREATE TABLE TEST(id TEXT, relation_id TEXT);");
database.query("INSERT INTO TEST(id, relation_id) VALUES ('test_1', 'relation_1');");
database.query("INSERT INTO TEST(id, relation_id) VALUES ('test_2', 'relation_2');");
database.query("INSERT INTO TEST(id, relation_id) VALUES ('test_2', 'relation_1');");
database.query("INSERT INTO TEST(id, relation_id) VALUES ('test_4', 'relation_3');");
// add the table RELATION into the database
database.query("CREATE TABLE RELATION(id TEXT);");
database.query("INSERT INTO RELATION(id) VALUES ('relation_1');");
database.query("INSERT INTO RELATION(id) VALUES ('relation_2');");
database.query("INSERT INTO RELATION(id) VALUES ('relation_3');");
database.query("INSERT INTO RELATION(id) VALUES ('relation_3');");
database.query("INSERT INTO RELATION(id) VALUES ('relation_3');");
// check that the identifierValidator sends two errors
AttributeUniqueValidator identifierValidator = new AttributeUniqueValidator();
identifierValidator.validate(context, database);
Assert.assertEquals(2, reportBuilder.getErrorsByCode(CoreErrorCodes.ATTRIBUTE_NOT_UNIQUE).size());
List<ValidatorError> errors = reportBuilder.getErrorsByCode(CoreErrorCodes.ATTRIBUTE_NOT_UNIQUE);
int index = 0;
// check first error
{
ValidatorError error = errors.get(index++);
assertEquals("ID", error.getAttribute());
assertEquals("TEST", error.getFileModel());
assertEquals(ErrorScope.DIRECTORY, error.getScope());
assertEquals(
"La valeur 'test_2' est présente 2 fois pour le champ 'ID' de la table 'TEST'.",
error.getMessage()
);
assertEquals("SAMPLE_MODEL", error.getDocumentModel());
}
{
ValidatorError error = errors.get(index++);
assertEquals("ID", error.getAttribute());
assertEquals("RELATION", error.getFileModel());
assertEquals(ErrorScope.DIRECTORY, error.getScope());
assertEquals(
"La valeur 'relation_3' est présente 3 fois pour le champ 'ID' de la table 'RELATION'.",
error.getMessage()
);
assertEquals("SAMPLE_MODEL", error.getDocumentModel());
}
}
}
| 42.217647 | 106 | 0.680507 |
b3ba47128958ebf3105811f7d4393eb849fa0990 | 1,579 | /*
* Copyright (c) 2019. http://devonline.academy
*
* 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 academy.devonline.java.basic.section04_conditional;
/**
* @author devonline
* @link http://devonline.academy/java-basic
*/
public class LeapYear {
public static void main(String[] args) {
// read source data
var year = 2020;
// processing
boolean isLeap;
/*if (year % 400 == 0) {
isLeap = true;
} else if (year % 100 == 0) {
isLeap = false;
} else if (year % 4 == 0) {
isLeap = true;
} else {
isLeap = false;
}*/
// processing 2
/*if ((year % 400 == 0) || ((year % 100 != 0 && (year % 4 == 0)))) {
isLeap = true;
} else {
isLeap = false;
}*/
// processing 3
isLeap = (year % 400 == 0) || ((year % 100 != 0 && (year % 4 == 0)));
// display results
System.out.println(isLeap ? year + " is leap year" : year + " is not leap year");
}
}
| 29.240741 | 89 | 0.567448 |
3c3bdc38aec998cf52b972d8ca891f4f3c61eca8 | 7,692 | /*******************************************************************************
* 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 suonos.lucene.fields;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.SortedDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import com.github.am0e.commons.AntLib;
import gnu.trove.map.hash.TIntIntHashMap;
import suonos.app.utils.TagUtils;
import suonos.lucene.IndexModels;
import suonos.lucene.Statement;
public class IndexedFieldCountsBuilder {
Map<String, IndexedFieldTermCount[]> fieldCounts = AntLib.newHashMap();
private IndexReader ir;
private IndexModels models;
public IndexedFieldCountsBuilder(Statement stmt) {
this.ir = stmt.indexReader();
this.models = stmt.luceneIndex().models();
}
public IndexedFieldCountsBuilder addField(String fieldName, String filter) throws IOException {
final IndexedField fld = models.indexedField(fieldName);
final Map<String, IndexedFieldTermCount> valuesMap = AntLib.newHashMap();
final TIntIntHashMap ordCounts = new TIntIntHashMap();
if (filter != null) {
filter = filter.toLowerCase();
}
// Get count of segments.
//
int sz = ir.leaves().size();
for (int i = 0; i != sz; i++) {
// Get the segment reader.
//
LeafReader lr = ir.leaves().get(i).reader();
// Doc count for field. Eg "album_genres"
//
lr.getDocCount(fld.getName());
// Get all documents that have the field "album_genres"
//
Bits docs = lr.getDocsWithField(fld.getName());
ordCounts.clear();
// Enumerate the field terms.
//
if (fld.isDocValues()) {
if (fld.isMultiValue()) {
// docvalues & multivalue is a SortedSetDocValues
// Per-Document values in a SortedDocValues are
// deduplicated, dereferenced, and sorted into a dictionary
// of
// unique values. A pointer to the dictionary value
// (ordinal) can be retrieved for each document.
// Ordinals are dense and in increasing sorted order.
//
SortedSetDocValues set = lr.getSortedSetDocValues(fld.getName());
if (set != null) {
// For all documents that have the field "album_genres":
//
for (int docId = 0; docId != docs.length(); docId++) {
if (docs.get(docId)) {
// Enumerate the set of [terms] of
// "album_genres" for the document represented
// by docId.
// Each ord represents the term value.
//
set.setDocument(docId);
// For each term bump up the frequency.
//
long ord;
while ((ord = set.nextOrd()) != SortedSetDocValues.NO_MORE_ORDS) {
ordCounts.adjustOrPutValue((int) ord, 1, 1);
System.out.println("term=" + set.lookupOrd(ord).utf8ToString());
}
}
}
TermsEnum te = set.termsEnum();
BytesRef term;
while ((term = te.next()) != null) {
int ord = (int) te.ord();
add(fld, valuesMap, filter, term, ordCounts.get(ord));
}
}
} else {
SortedDocValues set = lr.getSortedDocValues(fld.getName());
if (set != null) {
// For all documents that have the field "album_genres":
//
for (int docId = 0; docId != docs.length(); docId++) {
if (docs.get(docId)) {
// Get the term - Classical, Rock, etc.
//
BytesRef term = set.get(docId);
add(fld, valuesMap, filter, term, 1);
}
}
}
}
} else {
// Normal field, not a doc value.
//
Terms terms = lr.terms(fld.getName());
TermsEnum te = terms.iterator();
BytesRef term;
while ((term = te.next()) != null) {
add(fld, valuesMap, filter, term, te.docFreq());
}
}
/*
* SORTED doc[0] = "aardvark" doc[1] = "beaver" doc[2] = "aardvark"
*
* doc[0] = 0 doc[1] = 1 doc[2] = 0
*
* term[0] = "aardvark" term[1] = "beaver"
*/
// http://127.0.0.1:8080/api/facets?fields=track_title_a
// the above should return B:(4) because titles starting with B are
// 4!
}
// Get the array of term counters.
//
IndexedFieldTermCount[] list = valuesMap.values().toArray(new IndexedFieldTermCount[0]);
// Sort by term.
//
Arrays.sort(list);
// add to the map.
//
this.fieldCounts.put(fld.getName(), list);
return this;
}
void add(IndexedField fld, Map<String, IndexedFieldTermCount> valuesMap, String filter, BytesRef term,
int docFreq) {
String termVal = term.utf8ToString();
// Case insensitive comparison.
//
String termValLC = TagUtils.convertStringToId(termVal);
if (filter != null && !termValLC.startsWith(filter)) {
return;
}
IndexedFieldTermCount c = valuesMap.get(termValLC);
if (c == null) {
valuesMap.put(termValLC, c = new IndexedFieldTermCount(fld, termVal, termValLC));
}
c.docFreq += docFreq;
System.out.println("term=" + termVal + " " + docFreq);
}
public IndexedFieldCounts build() {
return new IndexedFieldCounts(this.fieldCounts);
}
}
| 36.803828 | 106 | 0.50754 |
8f6cd9cd525a5597b38f37e6ae0bd41b1d664998 | 629 | package quek.undergarden.world.gen.tree;
import net.minecraft.world.level.block.grower.AbstractTreeGrower;
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
import net.minecraft.world.level.levelgen.feature.configurations.TreeConfiguration;
import quek.undergarden.registry.UGConfiguredFeatures;
import javax.annotation.Nullable;
import java.util.Random;
public class SmogstemTree extends AbstractTreeGrower {
@Nullable
@Override
public ConfiguredFeature<TreeConfiguration, ?> getConfiguredFeature(Random randomIn, boolean largeHive) {
return UGConfiguredFeatures.SMOGSTEM_TREE;
}
} | 34.944444 | 109 | 0.82035 |
216bd864becc1070a949c3a3ce29dc4cb377113a | 4,776 | package org.esupportail.opi.batch;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.esupportail.commons.services.application.ApplicationService;
import org.esupportail.commons.services.application.ApplicationUtils;
import org.esupportail.commons.services.database.DatabaseUtils;
import org.esupportail.commons.services.exceptionHandling.ExceptionUtils;
import org.esupportail.commons.services.logging.Logger;
import org.esupportail.commons.services.logging.LoggerImpl;
import org.esupportail.commons.utils.BeanUtils;
import org.esupportail.opi.domain.ParameterService;
import org.esupportail.opi.domain.beans.parameters.Campagne;
import org.esupportail.opi.domain.beans.references.commission.Commission;
import org.esupportail.opi.domain.beans.references.commission.LinkTrtCmiCamp;
import org.esupportail.opi.domain.beans.references.commission.TraitementCmi;
import org.esupportail.opi.domain.beans.user.candidature.VersionEtpOpi;
/**
* @author ylecuyer
* TODO : IMPORTANT, batch à exécuter AVANT de supprimer les colonnes
* formant VersionEtpOpi
*
*/
public class CreateTrtCmiCamp {
/**
* A logger.
*/
private static final Logger LOG = new LoggerImpl(CreateTrtCmiCamp.class);
/**
* Bean constructor.
*/
private CreateTrtCmiCamp() {
throw new UnsupportedOperationException();
}
/**
* send the mail.
*/
private static void createTrtCmiCamp() {
//DomainService domainService = (DomainService) BeanUtils.getBean("domainService");
ParameterService parameterService = (ParameterService) BeanUtils.getBean("parameterService");
try {
DatabaseUtils.open();
DatabaseUtils.begin();
LOG.info("lancement de la procédure createTrtCmiCamp");
// récupération de la campagne en cours
Campagne camp = parameterService.getCampagneEnServ(1);
// on récupère toutes les commissions
Set<Commission> commissions = parameterService.getCommissions(null);
for (Commission cmi : commissions) {
// pour chaque commission, on traite chaque traitement cmi
// afin de créer le linkTrtCmiCamp correspondant
Set<TraitementCmi> traitements = cmi.getTraitementCmi();
// map utilisée pour faire le lien avec les vet des voeux
Map<VersionEtpOpi, LinkTrtCmiCamp> mapVetLinkTrtCmiCamp =
new HashMap<VersionEtpOpi, LinkTrtCmiCamp>();
for (TraitementCmi trt : traitements) {
if (parameterService.getLinkTrtCmiCamp(trt, camp) == null) {
// création du linkTrtCmiCamp
LinkTrtCmiCamp linkTrtCmiCamp = new LinkTrtCmiCamp();
linkTrtCmiCamp.setTraitementCmi(trt);
linkTrtCmiCamp.setCampagne(camp);
// sauvegarde en base
parameterService.addLinkTrtCmiCamp(linkTrtCmiCamp);
// on ajoute le linkTrtCmiCamp à la map
VersionEtpOpi vet = trt.getVersionEtpOpi();
if (!mapVetLinkTrtCmiCamp.containsKey(vet)) {
mapVetLinkTrtCmiCamp.put(vet, linkTrtCmiCamp);
}
if (vet.getCodEtp().equals("SL3051")) {
LOG.info("cas SL3051");
}
}
}
// List<Individu> individus = domainService.getIndividus(cmi, null);
// // pour chaque individu de la commission, on ajoute chaque linkTrtCmiCamp
// for (Individu ind : individus) {
// for (IndVoeu indVoeu : ind.getVoeux()) {
// VersionEtpOpi vet = indVoeu.getVersionEtpOpi();
// if (vet.getCodEtp().equals("SL3051")) {
// LOG.info("cas SL3051");
// }
// if (mapVetLinkTrtCmiCamp.containsKey(vet)) {
// // on ajoute le linkTrtCmiCamp puis on met à jour en base
// indVoeu.setLinkTrtCmiCamp(mapVetLinkTrtCmiCamp.get(vet));
// domainService.updateIndVoeu(indVoeu);
// }
// }
// }
}
DatabaseUtils.commit();
LOG.info("procédure createTrtCmiCamp terminée");
} catch (Exception e) {
DatabaseUtils.rollback();
} finally {
DatabaseUtils.close();
}
}
/**
* Print the syntax and exit.
*/
private static void syntax() {
throw new IllegalArgumentException(
"syntax: " + SetCampagneToInd.class.getSimpleName() + " <options>"
+ "\nwhere option can be:"
+ "\n- test-beans: test the required beans");
}
/**
* Dispatch dependaing on the arguments.
* @param args
*/
protected static void dispatch(final String[] args) {
switch (args.length) {
case 0:
createTrtCmiCamp();
break;
default:
syntax();
break;
}
}
/**
* The main method, called by ant.
* @param args
*/
public static void main(final String[] args) {
try {
ApplicationService applicationService = ApplicationUtils.createApplicationService();
LOG.info(applicationService.getName() + " v" + applicationService.getVersion());
dispatch(args);
} catch (Throwable t) {
ExceptionUtils.catchException(t);
}
}
}
| 29.121951 | 95 | 0.707286 |
40325ebc58dfb6f83c5a1c5833471e12cf36613b | 1,157 | package io.vertx.example.core.http.simpleform;
import io.vertx.core.AbstractVerticle;
import io.vertx.example.util.Runner;
/*
* NOTE! It's recommended to use Vert.x-Web for examples like this
*
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class SimpleFormServer extends AbstractVerticle {
// Convenience method so you can run it in your IDE
public static void main(String[] args) {
Runner.runExample(SimpleFormServer.class);
}
@Override
public void start() throws Exception {
vertx.createHttpServer().requestHandler(req -> {
if (req.uri().equals("/")) {
// Serve the index page
req.response().sendFile("index.html");
} else if (req.uri().startsWith("/form")) {
req.response().setChunked(true);
req.setExpectMultipart(true);
req.endHandler((v) -> {
for (String attr : req.formAttributes().names()) {
req.response().write("Got attr " + attr + " : " + req.formAttributes().get(attr) + "\n");
}
req.response().end();
});
} else {
req.response().setStatusCode(404).end();
}
}).listen(8080);
}
}
| 29.666667 | 101 | 0.611063 |
118aa5185eca245215fb439331d9cf2299d8b48f | 1,049 | // Template Source: Enum.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.models.generated;
/**
* The Enum Kerberos Sign On Mapping Attribute Type.
*/
public enum KerberosSignOnMappingAttributeType
{
/**
* user Principal Name
*/
USER_PRINCIPAL_NAME,
/**
* on Premises User Principal Name
*/
ON_PREMISES_USER_PRINCIPAL_NAME,
/**
* user Principal Username
*/
USER_PRINCIPAL_USERNAME,
/**
* on Premises User Principal Username
*/
ON_PREMISES_USER_PRINCIPAL_USERNAME,
/**
* on Premises SAMAccount Name
*/
ON_PREMISES_SAM_ACCOUNT_NAME,
/**
* For KerberosSignOnMappingAttributeType values that were not expected from the service
*/
UNEXPECTED_VALUE
}
| 26.897436 | 152 | 0.587226 |
2f95495162def0e70c0f7b93b7f7c312f57ab585 | 2,814 | package word_ladder;
import java.lang.reflect.Array;
import java.util.*;
public class Solution{
public static void main(String [] args){
String beginWord = "hit";
String endWord = "cog";
// String beginWord = "a";
// String endWord = "c";
// String beginWord = "red";
// String endWord = "tax";
String [] arr = {"hot","dot","dog","lot","log","cog"};
// String [] arr = {"a", "b", "c"};
// String [] arr = {"ted","tex","red","tax","tad","den","rex","pee"};
List<String> wordList = new ArrayList<String>(Arrays.asList(arr));
for(List<String> path : findLadders(beginWord, endWord, wordList)){
String way = Arrays.toString(path.toArray());
System.out.println(way);
}
}
public static class BFSNode{
public String word;
public List<String> path;
public BFSNode(String word, List<String> path){
this.word = word;
this.path = path;
}
}
public static List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
Set<String> dictionary = new HashSet<>(wordList);
List<List<String>> transformations = new ArrayList<>();
if(!dictionary.contains(endWord)){
return transformations;
}
Queue<BFSNode> queue = new LinkedList<>();
Set<String> visited = new HashSet<>();
BFSNode start = new BFSNode(beginWord, new ArrayList<>());
start.path.add(beginWord);
queue.offer(start);
int min_count = Integer.MAX_VALUE;
while (!queue.isEmpty()){
BFSNode node = queue.poll();
if(node.path.size()>min_count){
break;
}
if(node.word.equals(endWord)){
transformations.add(node.path);
min_count = Math.min(min_count,node.path.size());
continue;
}
visited.add(node.word);
for(int i=0;i<node.word.length();i++){
for(int j=0;j<26;j++){
char ch = (char) ('a' + j);
String newWord = new String(node.word.substring(0,i)+ ch + node.word.substring(i+1));
if(visited.contains(newWord) && !newWord.equals(endWord)){
continue;
}
if(dictionary.contains(newWord)){
List<String> path = new ArrayList<>();
path.addAll(node.path);
path.add(newWord);
BFSNode bfsNode = new BFSNode(newWord, path);
queue.offer(bfsNode);
}
}
}
}
return transformations;
}
}
| 38.027027 | 107 | 0.505686 |
4e6fafe73ad7d8db1c75653ae76c76b41d7f19de | 2,663 | package com.deepoove.cargo.web.controller;
import com.deepoove.cargo.application.command.CargoCmdService;
import com.deepoove.cargo.application.command.cmd.CargoBookCommand;
import com.deepoove.cargo.application.command.cmd.CargoDeleteCommand;
import com.deepoove.cargo.application.command.cmd.CargoDeliveryUpdateCommand;
import com.deepoove.cargo.application.command.cmd.CargoSenderUpdateCommand;
import com.deepoove.cargo.application.query.CargoQueryService;
import com.deepoove.cargo.application.query.dto.CargoDTO;
import com.deepoove.cargo.application.query.qry.CargoFindbyCustomerQry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/cargo")
public class CargoController {
@Autowired
CargoQueryService cargoQueryService;
@Autowired
CargoCmdService cargoCmdService;
@RequestMapping(method = RequestMethod.GET)
public List<CargoDTO> queryCargos(@RequestParam(value = "phone", required = false) String phone) {
if (!StringUtils.isEmpty(phone)) {
CargoFindbyCustomerQry qry = new CargoFindbyCustomerQry();
qry.setCustomerPhone(phone);
return cargoQueryService.queryCargos(qry);
}
return cargoQueryService.queryCargos();
}
@RequestMapping(value = "/{cargoId}", method = RequestMethod.GET)
public CargoDTO cargo(@PathVariable String cargoId) {
return cargoQueryService.getCargo(cargoId);
}
@RequestMapping(method = RequestMethod.POST)
public void book(@RequestBody CargoBookCommand cargoBookCommand) {
cargoCmdService.bookCargo(cargoBookCommand);
}
@RequestMapping(value = "/{cargoId}/delivery", method = RequestMethod.PUT)
public void modifyDestinationLocationCode(@PathVariable String cargoId,
@RequestBody CargoDeliveryUpdateCommand cmd) {
cmd.setCargoId(cargoId);
cargoCmdService.updateCargoDelivery(cmd);
}
@RequestMapping(value = "/{cargoId}/sender", method = RequestMethod.PUT)
public void modifySender(@PathVariable String cargoId,
@RequestBody CargoSenderUpdateCommand cmd) {
cmd.setCargoId(cargoId);
cargoCmdService.updateCargoSender(cmd);
}
@RequestMapping(value = "/{cargoId}", method = RequestMethod.DELETE)
public void removeCargo(@PathVariable String cargoId) {
CargoDeleteCommand cmd = new CargoDeleteCommand();
cmd.setCargoId(cargoId);
cargoCmdService.deleteCargo(cmd);
}
}
| 39.161765 | 102 | 0.733008 |
c24be14d9c366217a978d7e01ec6a1d346c76c8c | 145 | package rolectrl;
/**
* @author: xu.yefcion
* @description:
* @date: 2020/2/1 14:02
*/
public interface RoleOperation {
String op();
}
| 12.083333 | 32 | 0.627586 |
02d48b528fb3409a34c7e1b1f8cc62461bd0f14c | 17,142 | package com.project.convertedCode.globalNamespace.namespaces.Symfony.namespaces.Component.namespaces.Console.namespaces.Question.classes;
import com.runtimeconverter.runtime.references.ReferenceContainer;
import com.runtimeconverter.runtime.nativeFunctions.string.function_str_replace;
import com.runtimeconverter.runtime.passByReference.PassByReferenceArgs;
import com.runtimeconverter.runtime.nativeClasses.Closure;
import com.runtimeconverter.runtime.nativeFunctions.pcre.function_preg_match;
import com.runtimeconverter.runtime.nativeFunctions.string.function_explode;
import com.runtimeconverter.runtime.passByReference.RuntimeArgsWithReferences;
import com.runtimeconverter.runtime.ZVal;
import com.runtimeconverter.runtime.reflection.ReflectionClassData;
import com.runtimeconverter.runtime.annotations.ConvertedParameter;
import com.runtimeconverter.runtime.arrays.ZPair;
import java.lang.invoke.MethodHandles;
import com.runtimeconverter.runtime.nativeFunctions.array.function_array_search;
import com.runtimeconverter.runtime.interfaces.ContextConstants;
import com.project.convertedCode.globalNamespace.namespaces.Symfony.namespaces.Component.namespaces.Console.namespaces.Exception.classes.InvalidArgumentException;
import com.runtimeconverter.runtime.nativeFunctions.string.function_sprintf;
import com.runtimeconverter.runtime.nativeFunctions.array.function_count;
import com.project.convertedCode.globalNamespace.namespaces.Symfony.namespaces.Component.namespaces.Console.namespaces.Question.classes.Question;
import com.runtimeconverter.runtime.annotations.ConvertedMethod;
import com.runtimeconverter.runtime.references.BasicReferenceContainer;
import com.runtimeconverter.runtime.nativeClasses.spl.exceptions.LogicException;
import com.runtimeconverter.runtime.classes.RuntimeClassBase;
import com.runtimeconverter.runtime.RuntimeEnv;
import com.runtimeconverter.runtime.classes.NoConstructor;
import com.runtimeconverter.runtime.nativeFunctions.array.function_current;
import com.runtimeconverter.runtime.arrays.ArrayAction;
import com.project.convertedCode.globalNamespace.NamespaceGlobal;
import static com.runtimeconverter.runtime.ZVal.arrayActionR;
import static com.runtimeconverter.runtime.ZVal.toStringR;
import static com.runtimeconverter.runtime.ZVal.assignParameter;
/*
Converted with The Runtime Converter (runtimeconverter.com)
vendor/symfony/console/Question/ChoiceQuestion.php
*/
public class ChoiceQuestion extends Question {
public Object choices = null;
public Object multiselect = false;
public Object prompt = " > ";
public Object errorMessage = "Value \"%s\" is invalid";
public ChoiceQuestion(RuntimeEnv env, Object... args) {
super(env);
if (this.getClass() == ChoiceQuestion.class) {
this.__construct(env, args);
}
}
public ChoiceQuestion(NoConstructor n) {
super(n);
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "question", typeHint = "string")
@ConvertedParameter(index = 1, name = "choices", typeHint = "array")
@ConvertedParameter(
index = 2,
name = "default",
defaultValue = "NULL",
defaultValueType = "constant"
)
public Object __construct(RuntimeEnv env, Object... args) {
Object question = assignParameter(args, 0, false);
Object choices = assignParameter(args, 1, false);
Object _pDefault = assignParameter(args, 2, true);
if (null == _pDefault) {
_pDefault = ZVal.getNull();
}
if (!ZVal.isTrue(choices)) {
throw ZVal.getException(
env,
new LogicException(
env, "Choice question must have at least 1 choice available."));
}
super.__construct(env, question, _pDefault);
this.choices = choices;
env.callMethod(this, "setValidator", ChoiceQuestion.class, this.getDefaultValidator(env));
env.callMethod(this, "setAutocompleterValues", ChoiceQuestion.class, choices);
return null;
}
@ConvertedMethod
public Object getChoices(RuntimeEnv env, Object... args) {
return ZVal.assign(this.choices);
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "multiselect")
public Object setMultiselect(RuntimeEnv env, Object... args) {
Object multiselect = assignParameter(args, 0, false);
this.multiselect = multiselect;
env.callMethod(this, "setValidator", ChoiceQuestion.class, this.getDefaultValidator(env));
return ZVal.assign(this);
}
@ConvertedMethod
public Object isMultiselect(RuntimeEnv env, Object... args) {
return ZVal.assign(this.multiselect);
}
@ConvertedMethod
public Object getPrompt(RuntimeEnv env, Object... args) {
return ZVal.assign(this.prompt);
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "prompt")
public Object setPrompt(RuntimeEnv env, Object... args) {
Object prompt = assignParameter(args, 0, false);
this.prompt = prompt;
return ZVal.assign(this);
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "errorMessage")
public Object setErrorMessage(RuntimeEnv env, Object... args) {
Object errorMessage = assignParameter(args, 0, false);
this.errorMessage = errorMessage;
env.callMethod(this, "setValidator", ChoiceQuestion.class, this.getDefaultValidator(env));
return ZVal.assign(this);
}
@ConvertedMethod
private Object getDefaultValidator(RuntimeEnv env, Object... args) {
ContextConstants runtimeConverterFunctionClassConstants =
new ContextConstants()
.setDir("/vendor/symfony/console/Question")
.setFile("/vendor/symfony/console/Question/ChoiceQuestion.php");
Object multiselect = null;
Object errorMessage = null;
Object choices = null;
Object isAssoc = null;
choices = ZVal.assign(this.choices);
errorMessage = ZVal.assign(this.errorMessage);
multiselect = ZVal.assign(this.multiselect);
isAssoc = env.callMethod(this, "isAssoc", ChoiceQuestion.class, choices);
return ZVal.assign(
new Closure(
env,
runtimeConverterFunctionClassConstants,
"Symfony\\Component\\Console\\Question",
this) {
@Override
@ConvertedMethod
@ConvertedParameter(index = 0, name = "selected")
public Object run(
RuntimeEnv env,
Object thisvar,
PassByReferenceArgs runtimePassByReferenceArgs,
Object... args) {
Object selected = assignParameter(args, 0, false);
ReferenceContainer multiselectChoices = new BasicReferenceContainer(null);
Object errorMessage = null;
ReferenceContainer matches = new BasicReferenceContainer(null);
Object multiselect = null;
Object result = null;
Object selectedChoices = null;
Object choice = null;
ReferenceContainer choices = new BasicReferenceContainer(null);
ReferenceContainer results = new BasicReferenceContainer(null);
Object value = null;
Object key = null;
Object isAssoc = null;
multiselect = this.contextReferences.getCapturedValue("multiselect");
errorMessage = this.contextReferences.getCapturedValue("errorMessage");
choices = this.contextReferences.getReferenceContainer("choices");
isAssoc = this.contextReferences.getCapturedValue("isAssoc");
selectedChoices =
function_str_replace.f.env(env).call(" ", "", selected).value();
if (ZVal.isTrue(multiselect)) {
if (!function_preg_match
.f
.env(env)
.addReferenceArgs(
new RuntimeArgsWithReferences().add(2, matches))
.call(
"/^[^,]+(?:,[^,]+)*$/",
selectedChoices,
matches.getObject())
.getBool()) {
throw ZVal.getException(
env,
new InvalidArgumentException(
env,
function_sprintf
.f
.env(env)
.call(errorMessage, selected)
.value()));
}
selectedChoices =
function_explode.f.env(env).call(",", selectedChoices).value();
} else {
selectedChoices = ZVal.newArray(new ZPair(0, selected));
}
multiselectChoices.setObject(ZVal.newArray());
for (ZPair zpairResult1742 : ZVal.getIterable(selectedChoices, env, true)) {
value = ZVal.assign(zpairResult1742.getValue());
results.setObject(ZVal.newArray());
for (ZPair zpairResult1743 :
ZVal.getIterable(choices.getObject(), env, false)) {
key = ZVal.assign(zpairResult1743.getKey());
choice = ZVal.assign(zpairResult1743.getValue());
if (ZVal.strictEqualityCheck(choice, "===", value)) {
results.arrayAppend(env).set(key);
}
}
if (ZVal.isGreaterThan(
function_count.f.env(env).call(results.getObject()).value(),
'>',
1)) {
throw ZVal.getException(
env,
new InvalidArgumentException(
env,
function_sprintf
.f
.env(env)
.call(
"The provided answer is ambiguous. Value should be one of %s.",
NamespaceGlobal.implode
.env(env)
.call(
" or ",
results.getObject())
.value())
.value()));
}
result =
function_array_search
.f
.env(env)
.call(value, choices.getObject())
.value();
if (!ZVal.isTrue(isAssoc)) {
if (ZVal.strictNotEqualityCheck(false, "!==", result)) {
result = ZVal.assign(choices.arrayGet(env, result));
} else if (arrayActionR(ArrayAction.ISSET, choices, env, value)) {
result = ZVal.assign(choices.arrayGet(env, value));
}
} else if (ZVal.toBool(ZVal.strictEqualityCheck(false, "===", result))
&& ZVal.toBool(
arrayActionR(ArrayAction.ISSET, choices, env, value))) {
result = ZVal.assign(value);
}
if (ZVal.strictEqualityCheck(false, "===", result)) {
throw ZVal.getException(
env,
new InvalidArgumentException(
env,
function_sprintf
.f
.env(env)
.call(errorMessage, value)
.value()));
}
multiselectChoices.arrayAppend(env).set(toStringR(result, env));
}
if (ZVal.isTrue(multiselect)) {
return ZVal.assign(multiselectChoices.getObject());
}
return ZVal.assign(
function_current
.f
.env(env)
.call(multiselectChoices.getObject())
.value());
}
}.use("multiselect", multiselect)
.use("errorMessage", errorMessage)
.use("choices", choices)
.use("isAssoc", isAssoc));
}
public static final Object CONST_class =
"Symfony\\Component\\Console\\Question\\ChoiceQuestion";
// Runtime Converter Internals
// RuntimeStaticCompanion contains static methods
// RequestStaticProperties contains static (per-request) properties
// ReflectionClassData contains php reflection data used by the runtime library
public static class RuntimeStaticCompanion extends Question.RuntimeStaticCompanion {
private static final MethodHandles.Lookup staticCompanionLookup = MethodHandles.lookup();
}
public static final RuntimeStaticCompanion runtimeStaticObject = new RuntimeStaticCompanion();
private static final ReflectionClassData runtimeConverterReflectionData =
ReflectionClassData.builder()
.setName("Symfony\\Component\\Console\\Question\\ChoiceQuestion")
.setLookup(
ChoiceQuestion.class,
MethodHandles.lookup(),
RuntimeStaticCompanion.staticCompanionLookup)
.setLocalProperties(
"attempts",
"autocompleterValues",
"choices",
"default",
"errorMessage",
"hidden",
"hiddenFallback",
"multiselect",
"normalizer",
"prompt",
"question",
"validator")
.setFilename("vendor/symfony/console/Question/ChoiceQuestion.php")
.addExtendsClass("Symfony\\Component\\Console\\Question\\Question")
.get();
@Override
public ReflectionClassData getRuntimeConverterReflectionData() {
return runtimeConverterReflectionData;
}
@Override
public Object converterRuntimeCallExtended(
RuntimeEnv env,
String method,
Class<?> caller,
PassByReferenceArgs passByReferenceArgs,
Object... args) {
return RuntimeClassBase.converterRuntimeCallExtendedWithDataStatic(
this,
runtimeConverterReflectionData,
env,
method,
caller,
passByReferenceArgs,
args);
}
}
| 47.882682 | 162 | 0.504842 |
57d284d6f2767b4d683adb6e61b312724a496579 | 3,081 | package pl.consdata.ico.sqcompanion.sync;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import pl.consdata.ico.sqcompanion.cache.Caches;
import pl.consdata.ico.sqcompanion.members.MemberService;
import pl.consdata.ico.sqcompanion.project.ProjectService;
import pl.consdata.ico.sqcompanion.repository.RepositoryService;
import pl.consdata.ico.sqcompanion.users.UsersService;
import pl.consdata.ico.sqcompanion.violation.project.ProjectViolationsHistoryService;
import pl.consdata.ico.sqcompanion.violation.user.diff.UserViolationDiffSyncService;
import pl.consdata.ico.sqcompanion.violation.user.summary.UserViolationSummaryHistorySyncService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* @author gregorry
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class SynchronizationService {
private final ProjectService projectService;
private final ProjectViolationsHistoryService projectViolationsHistoryService;
private final UserViolationDiffSyncService userViolationDiffSyncService;
private final UsersService usersService;
private final RepositoryService repositoryService;
private final UserViolationSummaryHistorySyncService userViolationSummaryHistorySyncService;
private final SynchronizationStateService synchronizationStateService;
private final CacheManager cacheManager;
private final MemberService memberService;
private final Semaphore semaphore = new Semaphore(1);
public void acquireAndStartSynchronization() throws SynchronizationException {
boolean permit;
try {
permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new CannotStartSynchronizationException();
}
if (permit) {
try {
synchronize();
} finally {
semaphore.release();
}
} else {
throw new SynchronizationInProgressException();
}
}
/**
* Always run within semaphore loc via {@link SynchronizationService#acquireAndStartSynchronization()}!
*/
private void synchronize() {
log.info("Starting synchronization... This may take a while.");
long startTime = System.currentTimeMillis();
synchronizationStateService.initSynchronization();
memberService.syncMembers();
projectService.syncProjects();
repositoryService.syncGroups();
usersService.sync();
projectViolationsHistoryService.syncProjectsHistory();
userViolationDiffSyncService.sync();
userViolationSummaryHistorySyncService.sync();
synchronizationStateService.finishSynchronization();
Caches.LIST
.stream()
.map(cacheManager::getCache)
.forEach(cache -> cache.clear());
log.info("Synchronization finished in {}ms", (System.currentTimeMillis() - startTime));
}
}
| 38.037037 | 107 | 0.734826 |
c93bebac068aaad7c1ce224f94059e8b9d8c5a01 | 13,605 | /*
* Copyright 2019 is-land
*
* 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 oharastream.ohara.metrics;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import oharastream.ohara.common.annotations.VisibleForTesting;
import oharastream.ohara.common.util.CommonUtils;
import oharastream.ohara.metrics.basic.CounterMBean;
import oharastream.ohara.metrics.kafka.TopicMeter;
/**
* This channel is a SNAPSHOT of all bean objects from local/remote bean server. Since Java APIs
* don't allow us to get all objects in single connection, the implementation has to send multi
* requests to fetch all bean objects. If you really case the performance, you should set both
* {@link BeanChannel.Builder#domainName} and {@link BeanChannel.Builder#properties(Map)} to filter
* unwanted objects. If you don't set both arguments, the filter will happen after the connection to
* local/remote bean server. It won't save your life.
*/
@FunctionalInterface
public interface BeanChannel extends Iterable<BeanObject> {
/**
* remove unused beans from local jvm. This is not a public method since it should be called by
* ohara's beans only.
*
* @param domain domain
* @param properties properties
*/
static void unregister(String domain, Map<String, String> properties) {
try {
ManagementFactory.getPlatformMBeanServer()
.unregisterMBean(ObjectName.getInstance(domain, new Hashtable<>(properties)));
} catch (InstanceNotFoundException
| MBeanRegistrationException
| MalformedObjectNameException e) {
throw new IllegalArgumentException(e);
}
}
/**
* a helper method creating a channel to access local mbean server
*
* @return a bean channel connecting to local bean server
*/
static BeanChannel local() {
return builder().local().build();
}
/** @return a immutable list of bean objects */
List<BeanObject> beanObjects();
/** @return get only counter type from bean objects */
default List<CounterMBean> counterMBeans() {
return stream().filter(CounterMBean::is).map(CounterMBean::of).collect(Collectors.toList());
}
/** @return get only TopicMeter type from bean objects */
default List<TopicMeter> topicMeters() {
return stream().filter(TopicMeter::is).map(TopicMeter::of).collect(Collectors.toList());
}
default Stream<BeanObject> stream() {
return beanObjects().stream();
}
/** @return the number of beans in this channel */
default int size() {
return beanObjects().size();
}
/** @return true if there is no beans in this channel. */
default boolean empty() {
return beanObjects().isEmpty();
}
/** @return false if there is no beans in this channel. */
default boolean nonEmpty() {
return !empty();
}
@Override
default Iterator<BeanObject> iterator() {
return beanObjects().iterator();
}
static Builder builder() {
return new Builder();
}
static <T> Register<T> register() {
return new Register<T>();
}
class Builder implements oharastream.ohara.common.pattern.Builder<BeanChannel> {
private String domainName;
private Map<String, String> properties = Collections.emptyMap();
private String hostname = null;
private int port = -1;
@VisibleForTesting boolean local = true;
private Builder() {}
public Builder hostname(String hostname) {
this.hostname = CommonUtils.requireNonEmpty(hostname);
this.local = false;
return this;
}
public Builder port(int port) {
this.port = CommonUtils.requireConnectionPort(port);
this.local = false;
return this;
}
@oharastream.ohara.common.annotations.Optional("default value is true")
public Builder local() {
this.local = true;
return this;
}
/**
* list the bean objects having the same domain. Setting a specific domain can reduce the
* communication to jmx server
*
* @param domainName domain
* @return this builder
*/
public Builder domainName(String domainName) {
this.domainName = CommonUtils.requireNonEmpty(domainName);
return this;
}
/**
* list the bean objects having the same property. Setting a specific property can reduce the
* communication to jmx server
*
* @param key property key
* @param value property value
* @return this builder
*/
public Builder property(String key, String value) {
return properties(Collections.singletonMap(key, value));
}
/**
* list the bean objects having the same properties. Setting a specific properties can reduce
* the communication to jmx server
*
* @param properties properties
* @return this builder
*/
public Builder properties(Map<String, String> properties) {
CommonUtils.requireNonEmpty(properties)
.forEach(
(k, v) -> {
CommonUtils.requireNonEmpty(k);
CommonUtils.requireNonEmpty(v);
});
this.properties = CommonUtils.requireNonEmpty(properties);
return this;
}
private BeanObject to(
ObjectName objectName,
MBeanInfo beanInfo,
Function<String, Object> valueGetter,
long queryTime) {
// used to filter the "illegal" attribute
Object unknown = new Object();
Map<String, Object> attributes =
Stream.of(beanInfo.getAttributes())
.collect(
Collectors.toMap(
MBeanAttributeInfo::getName,
attribute -> {
try {
return valueGetter.apply(attribute.getName());
} catch (Throwable e) {
// It is not allow to access the value.
return unknown;
}
}))
.entrySet().stream()
.filter(e -> e.getValue() != unknown)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return BeanObject.builder()
.domainName(objectName.getDomain())
.properties(objectName.getKeyPropertyList())
.attributes(attributes)
// For all metrics, we will have a time of querying object
.queryTime(queryTime)
.build();
}
private ObjectName objectName() {
if (domainName == null || properties.isEmpty()) return null;
else {
try {
return ObjectName.getInstance(domainName, new Hashtable<>(properties));
} catch (MalformedObjectNameException e) {
throw new IllegalArgumentException(e);
}
}
}
private List<BeanObject> doBuild() {
if (local) {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
// for each query, we should have same "queryTime" for each metric
final long queryTime = CommonUtils.current();
return server.queryMBeans(objectName(), null).stream()
.map(
objectInstance -> {
try {
return Optional.of(
to(
objectInstance.getObjectName(),
server.getMBeanInfo(objectInstance.getObjectName()),
(attribute) -> {
try {
return server.getAttribute(
objectInstance.getObjectName(), attribute);
} catch (MBeanException
| AttributeNotFoundException
| InstanceNotFoundException
| ReflectionException e) {
throw new IllegalArgumentException(e);
}
},
queryTime));
} catch (Throwable e) {
return Optional.empty();
}
})
.filter(Optional::isPresent)
.map(o -> (BeanObject) o.get())
.collect(Collectors.toList());
} else {
try (JMXConnector connector =
JMXConnectorFactory.connect(
new JMXServiceURL(
"service:jmx:rmi:///jndi/rmi://"
+ CommonUtils.requireNonEmpty(hostname)
+ ":"
+ CommonUtils.requireConnectionPort(port)
+ "/jmxrmi"),
null)) {
MBeanServerConnection connection = connector.getMBeanServerConnection();
// for each query, we should have same "queryTime" for each metric
final long queryTime = CommonUtils.current();
return connection.queryMBeans(objectName(), null).stream()
.map(
objectInstance -> {
try {
return Optional.of(
to(
objectInstance.getObjectName(),
connection.getMBeanInfo(objectInstance.getObjectName()),
(attribute) -> {
try {
return connection.getAttribute(
objectInstance.getObjectName(), attribute);
} catch (MBeanException
| AttributeNotFoundException
| InstanceNotFoundException
| ReflectionException
| IOException e) {
throw new IllegalArgumentException(e);
}
},
queryTime));
} catch (Throwable e) {
return Optional.empty();
}
})
.filter(Optional::isPresent)
.map(o -> (BeanObject) o.get())
.collect(Collectors.toList());
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
}
@Override
public BeanChannel build() {
List<BeanObject> objs =
doBuild().stream()
.filter(o -> CommonUtils.isEmpty(domainName) || o.domainName().equals(domainName))
.filter(
o ->
CommonUtils.isEmpty(properties)
|| new HashMap<>(o.properties()).equals(new HashMap<>(properties)))
.collect(Collectors.toList());
return () -> objs;
}
}
class Register<T> {
private String domain = null;
private Map<String, String> properties = Collections.emptyMap();
private T beanObject = null;
private Register() {}
public Register<T> domain(String domain) {
this.domain = CommonUtils.requireNonEmpty(domain);
return this;
}
public Register<T> properties(Map<String, String> properties) {
this.properties = CommonUtils.requireNonEmpty(properties);
return this;
}
public Register<T> beanObject(T beanObject) {
this.beanObject = Objects.requireNonNull(beanObject);
return this;
}
private void check() {
CommonUtils.requireNonEmpty(domain);
CommonUtils.requireNonEmpty(properties);
Objects.requireNonNull(beanObject);
}
public T run() {
check();
try {
ObjectName name = ObjectName.getInstance(domain, new Hashtable<>(properties));
ManagementFactory.getPlatformMBeanServer().registerMBean(beanObject, name);
return beanObject;
} catch (MalformedObjectNameException
| InstanceAlreadyExistsException
| MBeanRegistrationException
| NotCompliantMBeanException e) {
throw new IllegalArgumentException(e);
}
}
}
}
| 35.522193 | 100 | 0.601985 |
16e5a4fa8357eb3331c435e3d7cdd9643095b41e | 13,331 | /*
* Copyright (c) 2015 EMC Corporation
* All Rights Reserved
*/
package com.emc.vipr.client.core.util;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.emc.storageos.model.DataObjectRestRep;
import com.emc.storageos.model.NamedRelatedResourceRep;
import com.emc.storageos.model.RelatedResourceRep;
import com.emc.vipr.client.core.filters.ResourceFilter;
public class ResourceUtils {
/** Null URI to use to unassign certain values. */
public static final URI NULL_URI = uri("null");
/**
* Gets the ID of a data object, null safe.
*
* @param value
* the data object.
* @return the ID.
*/
public static URI id(DataObjectRestRep value) {
return value != null ? value.getId() : null;
}
/**
* Gets the ID of a reference, null safe.
*
* @param ref
* the resource reference.
* @return the ID.
*/
public static URI id(RelatedResourceRep ref) {
return ref != null ? ref.getId() : null;
}
/**
* Gets a list of IDs of data objects, null safe.
*
* @param values
* list of data objects.
* @return List of IDs.
*/
public static List<URI> ids(Collection<? extends DataObjectRestRep> values) {
List<URI> ids = new ArrayList<URI>();
if (values != null) {
for (DataObjectRestRep value : values) {
ids.add(value.getId());
}
}
return ids;
}
/**
* Gets a list of IDs of data objects, null safe.
*
* @param refs
* list of resource references.
* @return List of IDs.
*/
public static List<URI> refIds(Collection<? extends RelatedResourceRep> refs) {
List<URI> ids = new ArrayList<URI>();
if (refs != null) {
for (RelatedResourceRep ref : refs) {
ids.add(ref.getId());
}
}
return ids;
}
/**
* Gets the ID of the resource, as a string.
*
* @param value
* the resource.
* @return the string ID.
*/
public static String stringId(DataObjectRestRep value) {
return asString(id(value));
}
/**
* Gets the ID of the reference, as a string.
*
* @param ref
* the resource reference.
* @return the string ID.
*/
public static String stringId(RelatedResourceRep ref) {
return asString(id(ref));
}
/**
* Gets the IDs of the resources, as a list of strings.
*
* @param values
* the resources.
* @return the string ID.
*/
public static List<String> stringIds(Collection<? extends DataObjectRestRep> values) {
List<String> ids = new ArrayList<String>();
if (values != null) {
for (DataObjectRestRep value : values) {
ids.add(stringId(value));
}
}
return ids;
}
/**
* Gets the IDs of the references, as a list of strings.
*
* @param refs
* the resource references.
* @return the list of string IDs.
*/
public static List<String> stringRefIds(Collection<? extends RelatedResourceRep> refs) {
List<String> ids = new ArrayList<String>();
if (refs != null) {
for (RelatedResourceRep ref : refs) {
ids.add(stringId(ref));
}
}
return ids;
}
/**
* Gets the name of a data object, null safe
*
* @param value
* the data object.
* @return the name of the data object.
*/
public static String name(DataObjectRestRep value) {
return value != null ? value.getName() : null;
}
/**
* Gets the name of a named reference, null safe
*
* @param ref
* the named reference.
* @return the name of the reference.
*/
public static String name(NamedRelatedResourceRep ref) {
return ref != null ? ref.getName() : null;
}
/**
* Gets the names of the data objects, null safe
*
* @param values
* the data objects.
* @return the names of the data objects.
*/
public static List<String> names(Collection<? extends DataObjectRestRep> values) {
List<String> names = new ArrayList<String>();
if (values != null) {
for (DataObjectRestRep value : values) {
names.add(value.getName());
}
}
return names;
}
/**
* Gets the name of the references, null safe
*
* @param refs
* the named references.
* @return the names of the references.
*/
public static List<String> refNames(Collection<? extends NamedRelatedResourceRep> refs) {
List<String> names = new ArrayList<String>();
if (refs != null) {
for (NamedRelatedResourceRep ref : refs) {
names.add(ref.getName());
}
}
return names;
}
/**
* Finds a data object within a collection by ID.
*
* @param values
* the data objects.
* @param id
* the ID of the value to find.
* @return the value, or null if not found.
*/
public static <T extends DataObjectRestRep> T find(Collection<T> values, URI id) {
if ((values != null) && (id != null)) {
for (T value : values) {
if (id.equals(id(value))) {
return value;
}
}
}
return null;
}
/**
* Finds a resource reference within a collection by ID.
*
* @param resources
* the resource references.
* @param id
* the ID of the reference to find.
* @return the resource reference, or null if not found.
*/
public static <T extends RelatedResourceRep> T findRef(Collection<T> resources, URI id) {
if ((resources != null) && (id != null)) {
for (T resource : resources) {
if (id.equals(id(resource))) {
return resource;
}
}
}
return null;
}
/**
* Defaults the list to an empty list if null.
*
* @param value
* the list value.
* @return the original list if non-null, otherwise it creates a new list.
*/
public static <T> List<T> defaultList(List<T> value) {
if (value == null) {
return new ArrayList<T>();
}
else {
return value;
}
}
/**
* Determines if the item is active.
*
* @param value
* the item.
* @return true if the item is active (inactive is not set, or is set to FALSE)
*/
public static boolean isActive(DataObjectRestRep value) {
return (value != null) && !Boolean.TRUE.equals(value.getInactive());
}
/**
* Determines if the item is not internal.
*
* @param value
* the item.
* @return true if the item is active (inactive is not set, or is set to FALSE)
*/
public static boolean isNotInternal(DataObjectRestRep value) {
return (value != null) && !Boolean.TRUE.equals(value.getInternal());
}
/**
* Maps a collection of resources by their IDs.
*
* @param resources
* the resources to map.
* @return the map of ID resource.
*/
public static <T extends DataObjectRestRep> Map<URI, T> mapById(Collection<T> resources) {
Map<URI, T> map = new LinkedHashMap<URI, T>();
for (T resource : resources) {
map.put(resource.getId(), resource);
}
return map;
}
/**
* Maps a collection of references by their ID to their name.
*
* @param references
* the references to map.
* @return the map of ID name.
*/
public static Map<URI, String> mapNames(Collection<? extends NamedRelatedResourceRep> references) {
Map<URI, String> map = new LinkedHashMap<URI, String>();
for (NamedRelatedResourceRep ref : references) {
map.put(ref.getId(), ref.getName());
}
return map;
}
/**
* Gets the value of the URI as a string, returns null if the URI is null.
*
* @param value
* the URI.
* @return the string value of the URI.
*/
public static String asString(URI value) {
return value != null ? value.toString() : null;
}
/**
* Converts a string to a URI, null safe.
*
* @param value
* the string value.
* @return the URI or null if the value does not represent a valid URI.
*/
public static URI uri(String value) {
try {
return (value != null && value.length() > 0) ? URI.create(value) : null;
} catch (IllegalArgumentException invalid) {
return null;
}
}
/**
* Converts a collection of strings to a list of URIs, null safe.
*
* @param values
* the string values.
* @return the URIs.
*/
public static List<URI> uris(Collection<String> values) {
List<URI> results = new ArrayList<URI>();
if (values != null) {
for (String value : values) {
URI uri = uri(value);
if (uri != null) {
results.add(uri);
}
}
}
return results;
}
/**
* Converts an array of strings to a list of URIs, null safe.
*
* @param values
* the string values.
* @return the URIs.
*/
public static List<URI> uris(String... values) {
if (values != null) {
return uris(Arrays.asList(values));
}
else {
return new ArrayList<URI>();
}
}
/**
* Determines if the IDs of the given values match.
*
* @param first
* the first reference.
* @param second
* the second reference.
* @return true if the values point to the same ID.
*/
public static boolean idEquals(RelatedResourceRep first, RelatedResourceRep second) {
return equals(id(first), id(second));
}
/**
* Determines if the IDs of the given values match.
*
* @param first
* the resource reference.
* @param second
* the resource object.
* @return true if the values point to the same ID.
*/
public static boolean idEquals(RelatedResourceRep first, DataObjectRestRep second) {
return equals(id(first), id(second));
}
/**
* Determines if the IDs of the given values match.
*
* @param first
* the resource object.
* @param second
* the resource reference.
* @return true if the values point to the same ID.
*/
public static boolean idEquals(DataObjectRestRep first, RelatedResourceRep second) {
return equals(id(first), id(second));
}
/**
* Determines if the IDs are equal (and non-null).
*
* @param first
* the first ID.
* @param second
* the second ID.
* @return true if and only if the IDs are non-null and equal.
*/
@SuppressWarnings("squid:S1201")
// Suppressing Sonar violation for method naming convention. We cannot use @override to this method as signature is different from
// Object.equal() method.
public static
boolean equals(URI first, URI second) {
if ((first != null) && (second != null)) {
return first.equals(second);
}
return false;
}
/**
* Checks if the ID is null (or matches the NULL_URI).
*
* @param id
* the ID.
* @return true if the ID is null.
*/
public static boolean isNull(URI id) {
return (id == null) || NULL_URI.equals(id);
}
/**
* Creates a named reference to the resource. The reference will have no selfLink set.
*
* @param resource
* the resource.
* @return the named reference to the resource.
*/
public static NamedRelatedResourceRep createNamedRef(DataObjectRestRep resource) {
return (resource != null) ? new NamedRelatedResourceRep(id(resource), null, name(resource)) : null;
}
/**
* Applies a resource filter to the collection of resources.
*
* @param resources
* the resources to filter.
* @param filter
* the filter to apply.
*/
public static <T extends DataObjectRestRep> void applyFilter(Collection<T> resources, ResourceFilter<T> filter) {
if (filter != null) {
Iterator<T> iter = resources.iterator();
while (iter.hasNext()) {
T resource = iter.next();
if (!filter.accept(resource)) {
iter.remove();
}
}
}
}
}
| 28.730603 | 134 | 0.54152 |
612236de177da648b5edda35e9c9790ade435192 | 241 | package com.example.injector.includes.provider.naming.flat_enclosing;
public interface Outer
{
class Middle
{
public static class Leaf
{
@MyFrameworkComponent
public static class MyModel2
{
}
}
}
}
| 15.0625 | 69 | 0.655602 |
7c2b715a61ca53f72e453a3da18e93c5f56852b8 | 2,328 | package chronosacaria.mcdw.bases;
import chronosacaria.mcdw.Mcdw;
import chronosacaria.mcdw.api.util.RarityHelper;
import chronosacaria.mcdw.enums.DoubleAxesID;
import chronosacaria.mcdw.items.ItemsInit;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.item.AxeItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ToolMaterial;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.Formatting;
import net.minecraft.world.World;
import java.util.List;
public class McdwDoubleAxe extends AxeItem {
public McdwDoubleAxe(ToolMaterial material, float attackDamage, float attackSpeed){
super(material, attackDamage, attackSpeed,
new Item.Settings().group(Mcdw.WEAPONS).rarity(RarityHelper.fromToolMaterial(material)));
}
@Override
public void appendTooltip(ItemStack stack, World world, List<Text> tooltip, TooltipContext tooltipContext){
if (stack.getItem() == ItemsInit.doubleAxeItems.get(DoubleAxesID.AXE_DOUBLE)){
tooltip.add(new TranslatableText("tooltip_info_item.mcdw.double_axe_1").formatted(Formatting.ITALIC));
tooltip.add(new TranslatableText("tooltip_info_item.mcdw.double_axe_2").formatted(Formatting.ITALIC));
}
if (stack.getItem() == ItemsInit.doubleAxeItems.get(DoubleAxesID.AXE_CURSED)){
tooltip.add(new TranslatableText("tooltip_info_item.mcdw.cursed_axe_1").formatted(Formatting.ITALIC));
tooltip.add(new TranslatableText("tooltip_info_item.mcdw.cursed_axe_2").formatted(Formatting.ITALIC));
tooltip.add(new TranslatableText("tooltip_info_item.mcdw.cursed_axe_3").formatted(Formatting.ITALIC));
tooltip.add(new TranslatableText("tooltip_info_item.mcdw.cursed_axe_4").formatted(Formatting.ITALIC));
}
if (stack.getItem() == ItemsInit.doubleAxeItems.get(DoubleAxesID.AXE_WHIRLWIND)){
tooltip.add(new TranslatableText("tooltip_info_item.mcdw.whirlwind_1").formatted(Formatting.ITALIC));
tooltip.add(new TranslatableText("tooltip_info_item.mcdw.whirlwind_2").formatted(Formatting.ITALIC));
tooltip.add(new TranslatableText("tooltip_info_item.mcdw.whirlwind_3").formatted(Formatting.ITALIC));
}
}
} | 52.909091 | 114 | 0.758162 |
661439a2de41d1b6ccb2851249594106f1ccf20f | 176 | package fly;
/**
* @className: FlyBehavior
* @description: TODO 类描述
* @author: WU Yuejiang
* @date: 2021/1/11
**/
public interface FlyBehavior {
public void fly();
}
| 14.666667 | 30 | 0.647727 |
e676c6a8a6908ea4e740239cb4e542c35dc35442 | 853 | package no.uio.cesar.ViewModel;
import android.app.Application;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import no.uio.cesar.Model.Interface.Repository;
import no.uio.cesar.Model.Sample;
public class SampleViewModel extends AndroidViewModel {
private Repository repository;
public SampleViewModel(@NonNull Application application) {
super(application);
this.repository = new Repository(application);
}
public void insert(Sample sample) {
repository.insert(sample);
}
public void insert(Sample sample, String data) {
repository.insertFlowSample(sample, data);
}
public LiveData<List<Sample>> getSamplesForRecord(long id) {
return repository.getSamplesForRecord(id);
}
}
| 24.371429 | 64 | 0.737397 |
cb8e3be87a29fc8f6df7670bc71cd0c7372dce99 | 1,375 | package database;
import java.time.Instant;
import javax.persistence.EntityManager;
import org.junit.Assert;
import org.junit.Test;
import dto.Channel;
import dto.Comment;
import dto.User;
public class EntityManagerTest {
@Test
public void entityManagerTest1() {
EntityManager em = HibernateUtil.getEntityManager();
em.getTransaction().begin();
User user = new User();
user.setName("name 2");
em.persist(user);
Channel channel = new Channel();
channel.setName("channel 2");
em.persist(channel);
Comment comment = new Comment();
comment.setContent("contents");
comment.setTimestamp(Instant.now());
comment.setUser(user);
comment.setChannel(channel);
em.persist(comment);
Assert.assertNotNull(user.getId());
em.getTransaction().commit();
em.close();
}
@Test
public void entityManagerTest2() {
EntityManager em = HibernateUtil.getEntityManager();
em.getTransaction().begin();
User user = new User();
user.setName("name 1");
em.persist(user);
Channel channel = new Channel();
channel.setName("channel 1");
em.persist(channel);
Comment comment = new Comment();
comment.setContent("hello to you");
comment.setTimestamp(Instant.now());
comment.setUser(user);
comment.setChannel(channel);
em.persist(comment);
Assert.assertNotNull(user.getId());
em.getTransaction().commit();
em.close();
}
}
| 20.220588 | 54 | 0.709818 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.