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
6d285d7b7bdde8450fdc9a2ea44a119c33680091
4,822
/* * Copyright (c) 2021 Daimler TSS GmbH * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0 * * SPDX-License-Identifier: Apache-2.0 * * Contributors: * Daimler TSS GmbH - Initial Implementation * */ package org.eclipse.dataspaceconnector.ids.transform; import org.eclipse.dataspaceconnector.ids.spi.IdsId; import org.eclipse.dataspaceconnector.policy.model.Action; import org.eclipse.dataspaceconnector.policy.model.Constraint; import org.eclipse.dataspaceconnector.policy.model.Duty; import org.eclipse.dataspaceconnector.policy.model.Permission; import org.eclipse.dataspaceconnector.spi.transformer.TransformerContext; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.net.URI; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class PermissionToIdsPermissionTransformerTest { private static final URI PERMISSION_ID = URI.create("urn:permission:456uz984390236s"); private static final String TARGET = "https://target.com"; private static final URI TARGET_URI = URI.create(TARGET); private static final String ASSIGNER = "https://assigner.com"; private static final URI ASSIGNER_URI = URI.create(ASSIGNER); private static final String ASSIGNEE = "https://assignee.com"; private static final URI ASSIGNEE_URI = URI.create(ASSIGNEE); private PermissionToIdsPermissionTransformer transformer; private TransformerContext context; @BeforeEach void setUp() { transformer = new PermissionToIdsPermissionTransformer(); context = mock(TransformerContext.class); } @Test void testThrowsNullPointerExceptionForAll() { Assertions.assertThrows(NullPointerException.class, () -> { transformer.transform(null, null); }); } @Test void testThrowsNullPointerExceptionForContext() { Assertions.assertThrows(NullPointerException.class, () -> { transformer.transform(Permission.Builder.newInstance().build(), null); }); } @Test void testReturnsNull() { var result = transformer.transform(null, context); Assertions.assertNull(result); } @Test void testSuccessfulSimple() { Action edcAction = mock(Action.class); de.fraunhofer.iais.eis.Action idsAction = de.fraunhofer.iais.eis.Action.READ; Constraint edcConstraint = mock(Constraint.class); de.fraunhofer.iais.eis.Constraint idsConstraint = mock(de.fraunhofer.iais.eis.Constraint.class); Duty edcDuty = mock(Duty.class); de.fraunhofer.iais.eis.Duty idsDuty = mock(de.fraunhofer.iais.eis.Duty.class); var permission = Permission.Builder.newInstance() .target(TARGET).assigner(ASSIGNER).assignee(ASSIGNEE) .constraint(edcConstraint) .duty(edcDuty) .action(edcAction) .build(); when(context.transform(eq(edcAction), eq(de.fraunhofer.iais.eis.Action.class))).thenReturn(idsAction); when(context.transform(eq(edcConstraint), eq(de.fraunhofer.iais.eis.Constraint.class))).thenReturn(idsConstraint); when(context.transform(eq(edcDuty), eq(de.fraunhofer.iais.eis.Duty.class))).thenReturn(idsDuty); when(context.transform(any(IdsId.class), eq(URI.class))).thenReturn(PERMISSION_ID); var result = transformer.transform(permission, context); Assertions.assertNotNull(result); Assertions.assertEquals(PERMISSION_ID, result.getId()); Assertions.assertEquals(1, result.getAssigner().size()); Assertions.assertEquals(ASSIGNER_URI, result.getAssigner().get(0)); Assertions.assertEquals(1, result.getAssignee().size()); Assertions.assertEquals(ASSIGNEE_URI, result.getAssignee().get(0)); Assertions.assertEquals(1, result.getAction().size()); Assertions.assertEquals(idsAction, result.getAction().get(0)); Assertions.assertEquals(1, result.getConstraint().size()); Assertions.assertEquals(idsConstraint, result.getConstraint().get(0)); verify(context).transform(eq(edcAction), eq(de.fraunhofer.iais.eis.Action.class)); verify(context).transform(eq(edcConstraint), eq(de.fraunhofer.iais.eis.Constraint.class)); verify(context).transform(eq(edcDuty), eq(de.fraunhofer.iais.eis.Duty.class)); verify(context, times(2)).transform(any(IdsId.class), eq(URI.class)); } }
41.568966
122
0.7163
4cd9aaa6c4755f4fc148bd211307e37292e43651
1,657
/* * $Id: JMadModelDescription.java,v 1.1 2008-12-19 13:55:27 kfuchsbe Exp $ * * $Date: 2008-12-19 13:55:27 $ * $Revision: 1.1 $ * $Author: kfuchsbe $ * * Copyright CERN, All Rights Reserved. */ package cern.accsoft.steering.aloha.proj.data.jmad; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import cern.accsoft.steering.aloha.proj.data.ModelDescription; import cern.accsoft.steering.jmad.model.ModelCategory; /** * the description of an madx-model * * @author kfuchsbe * */ @Root(name = "jmad-model") public class JMadModelDescription implements ModelDescription { /** the id of the jmad-model */ @Element(name = "model-id") private ModelCategory modelId; /** the name of the model-sequence */ @Element(name = "sequence-name") private String sequenceName; /** the name of the range to use */ @Element(name = "range-name") private String rangeName; /** * @param modelId * the modelId to set */ public void setModelId(ModelCategory modelId) { this.modelId = modelId; } /** * @return the modelId */ public ModelCategory getModelId() { return modelId; } /** * @param sequenceName * the sequenceName to set */ public void setSequenceName(String sequenceName) { this.sequenceName = sequenceName; } /** * @return the sequenceName */ public String getSequenceName() { return sequenceName; } /** * @param rangeName * the rangeName to set */ public void setRangeName(String rangeName) { this.rangeName = rangeName; } /** * @return the rangeName */ public String getRangeName() { return rangeName; } }
19.72619
74
0.672903
fc01394ce68053ac90d66bbb421fb8f633301ba8
1,414
package de.kid2407.bannermod.gui; import de.kid2407.bannermod.BannerMod; import mcp.MethodsReturnNonnullByDefault; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; import javax.annotation.ParametersAreNonnullByDefault; /** * User: Tobias Franz * Date: 28.04.2020 * Time: 17:49 */ @MethodsReturnNonnullByDefault public class GuiCommand extends CommandBase { @Override public String getName() { return "gui"; } @Override @ParametersAreNonnullByDefault public String getUsage(ICommandSender sender) { return "/gui"; } @Override @ParametersAreNonnullByDefault public void execute(MinecraftServer server, ICommandSender sender, String[] args) { if (sender instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) sender; BlockPos position = player.getPosition(); BannerMod.logger.info("Kommando ausgeführt!"); player.openGui(BannerMod.MOD_ID, GuiHandler.GUIID, player.getEntityWorld(), position.getX(), position.getY(), position.getZ()); } } @Override @ParametersAreNonnullByDefault public boolean checkPermission(MinecraftServer server, ICommandSender sender) { return true; } }
28.857143
139
0.721358
ce215ca669f24d74280c151d0b7e7addc76f54d1
12,748
/* * Copyright (C) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.copybara.buildozer; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.copybara.WorkflowOptions; import com.google.copybara.config.SkylarkUtil; import com.google.copybara.doc.annotations.Example; import com.google.devtools.build.lib.syntax.EvalException; import com.google.devtools.build.lib.syntax.Location; import com.google.devtools.build.lib.syntax.Sequence; import com.google.devtools.build.lib.syntax.Starlark; import com.google.devtools.build.lib.syntax.StarlarkThread; import com.google.devtools.build.lib.syntax.StarlarkValue; import java.util.ArrayList; import java.util.List; import net.starlark.java.annot.Param; import net.starlark.java.annot.ParamType; import net.starlark.java.annot.StarlarkBuiltin; import net.starlark.java.annot.StarlarkDocumentationCategory; import net.starlark.java.annot.StarlarkMethod; /** Skylark module for Buildozer-related functionality. */ @StarlarkBuiltin( name = "buildozer", doc = "Module for Buildozer-related functionality such as creating and modifying BUILD targets.", category = StarlarkDocumentationCategory.BUILTIN) public final class BuildozerModule implements StarlarkValue { private final BuildozerOptions buildozerOptions; private final WorkflowOptions workflowOptions; public BuildozerModule(WorkflowOptions workflowOptions, BuildozerOptions buildozerOptions) { this.workflowOptions = Preconditions.checkNotNull(workflowOptions); this.buildozerOptions = Preconditions.checkNotNull(buildozerOptions); } private static ImmutableList<Target> getTargetList(Location location, Object arg) throws EvalException { if (arg instanceof String) { return ImmutableList.of(Target.fromConfig(location, (String) arg)); } else { ImmutableList.Builder<Target> builder = ImmutableList.builder(); for (String target : SkylarkUtil.convertStringList(arg, "target")) { builder.add(Target.fromConfig(location, target)); } return builder.build(); } } private static ImmutableList<Command> coerceCommandList(Location location, Iterable<?> commands) throws EvalException { ImmutableList.Builder<Command> wrappedCommands = new ImmutableList.Builder<>(); for (Object command : commands) { if (command instanceof String) { wrappedCommands.add(Command.fromConfig(location, (String) command, /*reverse*/ null)); } else if (command instanceof Command) { wrappedCommands.add((Command) command); } else { throw Starlark.errorf("Expected a string or buildozer.cmd, but got: %s", command); } } return wrappedCommands.build(); } @StarlarkMethod( name = "create", doc = "A transformation which creates a new build target and populates its " + "attributes. This transform can reverse automatically to delete the target.", parameters = { @Param( name = "target", type = String.class, doc = "Target to create, including the package, e.g. 'foo:bar'. The package can be " + "'.' for the root BUILD file.", named = true), @Param( name = "rule_type", type = String.class, doc = "Type of this rule, for instance, java_library.", named = true), @Param( name = "commands", type = Sequence.class, doc = "Commands to populate attributes of the target after creating it. Elements can" + " be strings such as 'add deps :foo' or objects returned by buildozer.cmd.", defaultValue = "[]", named = true), @Param( name = "before", type = String.class, doc = "When supplied, causes this target to be created *before* the target named by" + " 'before'", positional = false, defaultValue = "''", named = true), @Param( name = "after", type = String.class, doc = "When supplied, causes this target to be created *after* the target named by" + " 'after'", positional = false, defaultValue = "''", named = true), }, useStarlarkThread = true) public BuildozerCreate create( String target, String ruleType, Sequence<?> commands, String before, String after, StarlarkThread thread) throws EvalException { Location location = thread.getCallerLocation(); List<String> commandStrings = new ArrayList<>(); for (Object command : coerceCommandList(location, commands)) { commandStrings.add(command.toString()); } return new BuildozerCreate( location, buildozerOptions, workflowOptions, Target.fromConfig(location, target), ruleType, new BuildozerCreate.RelativeTo(location, before, after), commandStrings); } private void mustOmitRecreateParam(Object expected, Object actual, String paramName) throws EvalException { if (!expected.equals(actual)) { throw Starlark.errorf( "Parameter '%s' is only used for reversible buildozer.delete transforms, but this" + " buildozer.delete is not reversible. Specify 'rule_type' argument to make it" + " reversible.", paramName); } } @StarlarkMethod( name = "delete", doc = "A transformation which is the opposite of creating a build target. When run normally," + " it deletes a build target. When reversed, it creates and prepares one.", parameters = { @Param( name = "target", type = String.class, doc = "Target to create, including the package, e.g. 'foo:bar'", named = true), @Param( name = "rule_type", type = String.class, doc = "Type of this rule, for instance, java_library. Supplying this will cause this" + " transformation to be reversible.", defaultValue = "''", named = true), @Param( name = "recreate_commands", type = Sequence.class, doc = "Commands to populate attributes of the target after creating it. Elements can" + " be strings such as 'add deps :foo' or objects returned by buildozer.cmd.", positional = false, defaultValue = "[]", named = true), @Param( name = "before", type = String.class, doc = "When supplied with rule_type and the transformation is reversed, causes this" + " target to be created *before* the target named by 'before'", positional = false, defaultValue = "''", named = true), @Param( name = "after", type = String.class, doc = "When supplied with rule_type and the transformation is reversed, causes this" + " target to be created *after* the target named by 'after'", positional = false, defaultValue = "''", named = true), }, useStarlarkThread = true) public BuildozerDelete delete( String targetString, String ruleType, Sequence<?> recreateCommands, String before, String after, StarlarkThread thread) throws EvalException { Location location = thread.getCallerLocation(); List<String> commandStrings = new ArrayList<>(); for (Object command : coerceCommandList(location, recreateCommands)) { commandStrings.add(command.toString()); } BuildozerCreate recreateAs; Target target = Target.fromConfig(location, targetString); if (ruleType.isEmpty()) { recreateAs = null; mustOmitRecreateParam(ImmutableList.of(), recreateCommands, "recreate_commands"); mustOmitRecreateParam("", before, "before"); mustOmitRecreateParam("", after, "after"); } else { recreateAs = new BuildozerCreate( location, buildozerOptions, workflowOptions, target, ruleType, new BuildozerCreate.RelativeTo(location, before, after), commandStrings); } return new BuildozerDelete(location, buildozerOptions, workflowOptions, target, recreateAs); } @StarlarkMethod( name = "modify", doc = "A transformation which runs one or more Buildozer commands against a single" + " target expression. See http://go/buildozer for details on supported commands and" + " target expression formats.", parameters = { @Param( name = "target", allowedTypes = { @ParamType(type = String.class), @ParamType(type = Sequence.class, generic1 = String.class) }, doc = "Specifies the target(s) against which to apply the commands. Can be a list.", named = true), @Param( name = "commands", type = Sequence.class, doc = "Commands to apply to the target(s) specified. Elements can" + " be strings such as 'add deps :foo' or objects returned by buildozer.cmd.", named = true), }, useStarlarkThread = true) @Example( title = "Add a setting to one target", before = "Add \"config = ':foo'\" to foo/bar:baz:", code = "buildozer.modify(\n" + " target = 'foo/bar:baz',\n" + " commands = [\n" + " buildozer.cmd('set config \":foo\"'),\n" + " ],\n" + ")") @Example( title = "Add a setting to several targets", before = "Add \"config = ':foo'\" to foo/bar:baz and foo/bar:fooz:", code = "buildozer.modify(\n" + " target = ['foo/bar:baz', 'foo/bar:fooz'],\n" + " commands = [\n" + " buildozer.cmd('set config \":foo\"'),\n" + " ],\n" + ")") public BuildozerModify modify(Object target, Sequence<?> commands, StarlarkThread thread) throws EvalException { if (commands.isEmpty()) { throw Starlark.errorf("at least one element required in 'commands' argument"); } Location location = thread.getCallerLocation(); return new BuildozerModify( buildozerOptions, workflowOptions, getTargetList(location, target), coerceCommandList(location, commands)); } @StarlarkMethod( name = "cmd", doc = "Creates a Buildozer command. You can specify the reversal with the 'reverse' " + "argument.", parameters = { @Param( name = "forward", type = String.class, doc = "Specifies the Buildozer command, e.g. 'replace deps :foo :bar'", named = true), @Param( name = "reverse", type = String.class, doc = "The reverse of the command. This is only required if the given command cannot be" + " reversed automatically and the reversal of this command is required by" + " some workflow or Copybara check. The following commands are automatically" + " reversible:<br><ul><li>add</li><li>remove (when used to remove element" + " from list i.e. 'remove srcs foo.cc'</li><li>replace</li></ul>", noneable = true, defaultValue = "None", named = true), }, useStarlarkThread = true) public Command cmd(String forward, Object reverse, StarlarkThread thread) throws EvalException { return Command.fromConfig( thread.getCallerLocation(), forward, SkylarkUtil.convertOptionalString(reverse)); } }
38.865854
99
0.603546
84e93d5de8fc7cef98fda5a776d7e015743d0c15
861
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.prelude.query; /** * Ordered NearItem. * <p> * Matches as a near operator, but also demands that the operands have the * same order in the document as in the query. * * @author bratseth */ public class ONearItem extends NearItem { /** Creates a ordered NEAR item with limit 2 */ public ONearItem() { setDistance(2); } /** * Creates a ordered near item which matches if there are at most <code>distance</code> * separation between the words, in the right direction. */ public ONearItem(int distance) { super(distance); } public ItemType getItemType() { return ItemType.ONEAR; } public String getName() { return "ONEAR"; } }
23.27027
118
0.651568
7f200c21568dda7cf0e4c288c24200ea8702c16f
1,408
package com.example.ooprojectblocks; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; import java.util.Map; public class BillboardAdapter extends BaseAdapter { private LayoutInflater inflater; private List<Map<String, Object>> data; public BillboardAdapter(Context context, List<Map<String, Object>> data) { this.inflater = LayoutInflater.from(context); this.data = data; } @Override public int getCount() { return 11; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = inflater.inflate(R.layout.billboard_list, null); TextView rank = (TextView) view.findViewById(R.id.rank); TextView id = (TextView) view.findViewById(R.id.id); TextView score = (TextView) view.findViewById(R.id.score); rank.setText((String) data.get(position).get("rank")); id.setText((String) data.get(position).get("id")); score.setText((String) data.get(position).get("score")); return view; } }
27.607843
78
0.679688
0849f0201bb9b6a9a6ff781f30ed95f2a8be116a
1,591
/** * Copyright (C) 2016 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.jboss.errai.common.client.api.annotations; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Marks a native {@link JsType} as a wrapper for a DOM event. {@link BrowserEvent#value()} are the event type names * that the annotated type can be used with (i.e. click, dblclick, change, etc.). A type annotated with * {@code BrowserEvent} can be used with the {@code @EventHandler} annotation in Errai UI templates. * * @author Max Barkley <[email protected]> */ @Retention(RUNTIME) @Documented @Target(TYPE) public @interface BrowserEvent { /** * A list of event types supported by this event (i.e. click, dblclick, change). If this value has length 0 then the * annotated type supports all browser event types. */ String[] value() default {}; }
35.355556
118
0.737901
4337799ad5260cf99512a32eab7d41a850593321
1,609
package com.qjuzi.tools.net.status; import android.content.Context; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkCapabilities; import android.net.NetworkRequest; import android.util.Log; public class NetworkInfoManager { public static class Holder { public static NetworkInfoManager Instance = new NetworkInfoManager(); } public static NetworkInfoManager getInstance() { return Holder.Instance; } public void init(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) { return; } NetworkRequest.Builder builder = new NetworkRequest.Builder(); NetworkRequest request = builder .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) .build(); cm.registerNetworkCallback(request, new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { NetworkCapabilities networkCapabilities = cm.getNetworkCapabilities(network); Log.e("NetworkInfoManager", networkCapabilities.toString()); } @Override public void onLost(Network network) { Log.e("NetworkInfoManager", "onLost"); } }); } public void isConnected() { } }
28.732143
110
0.660037
609f3e0afbcaa64a3f5a0e918215ef5b4bf677ae
1,898
package com.appnext.ads.fullscreen; import java.io.Serializable; import java.util.HashMap; public class RewardedServerSidePostback implements Serializable { private static final long serialVersionUID = 1; private String bo = ""; private String bp = ""; private String bq = ""; private String br = ""; private String bs = ""; public RewardedServerSidePostback() { } public RewardedServerSidePostback(String str, String str2, String str3, String str4, String str5) { this.bo = str; this.bp = str2; this.bq = str3; this.br = str4; this.bs = str5; } public String getRewardsTransactionId() { return this.bo; } public void setRewardsTransactionId(String str) { this.bo = str; } public String getRewardsUserId() { return this.bp; } public void setRewardsUserId(String str) { this.bp = str; } public String getRewardsRewardTypeCurrency() { return this.bq; } public void setRewardsRewardTypeCurrency(String str) { this.bq = str; } public String getRewardsAmountRewarded() { return this.br; } public void setRewardsAmountRewarded(String str) { this.br = str; } public String getRewardsCustomParameter() { return this.bs; } public void setRewardsCustomParameter(String str) { this.bs = str; } /* access modifiers changed from: protected */ public final HashMap<String, String> p() { HashMap<String, String> hashMap = new HashMap<>(); hashMap.put("rewardsTransactionId", this.bo); hashMap.put("rewardsUserId", this.bp); hashMap.put("rewardsRewardTypeCurrency", this.bq); hashMap.put("rewardsAmountRewarded", this.br); hashMap.put("rewardsCustomParameter", this.bs); return hashMap; } }
24.973684
103
0.631191
5fa3eee5ddd5a3ef1a956b1a2547a690c5629cac
4,516
package com.github.chen0040.spark.sga.services; import com.github.chen0040.data.commons.consts.SparkGraphMinerCommand; import com.github.chen0040.data.commons.models.MyWorkerCompleted; import com.github.chen0040.data.commons.models.MyWorkerProgress; import com.github.chen0040.data.sga.models.JobInsight; import com.github.chen0040.data.sga.services.JobInsightService; import com.github.chen0040.lang.commons.utils.CollectionUtil; import com.github.chen0040.lang.commons.utils.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Date; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; /** * Created by xschen on 9/2/2017. */ @Service public class JobInsightFileServiceImpl implements JobInsightFileService { @Autowired private JobInsightService jobInsightService; @Override public MyWorkerCompleted writeLargeFile(String filename, Consumer<MyWorkerProgress> progressHandler) throws IOException { int totalPages = 20; int pageIndex = 0; int pageSize = 20; long totalElements = 0L; BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename))); int prevPercentage = -1; int remainingTime = 0; long startTime = new Date().getTime(); while(pageIndex < totalPages) { Page<JobInsight> page = jobInsightService.findPagedJobInsights(pageIndex, pageSize); totalElements = page.getTotalElements(); totalPages = page.getTotalPages(); List<JobInsight> data = page.getContent(); if(data.isEmpty()){ break; } pageSize = Math.min(1000, (int)(totalElements / 100)); pageSize = Math.max(20, pageSize); if(totalPages > 0){ int percentage = (pageIndex+1) * 100 / totalPages; if(prevPercentage != percentage) { MyWorkerProgress progress = new MyWorkerProgress(); progress.setPercentage(percentage); long duration = new Date().getTime() - startTime; int durationInSeconds = (int)(duration / 1000); if(percentage > 0){ int totalDurationInSeconds = durationInSeconds * 100 / percentage; remainingTime = Math.max(0, totalDurationInSeconds - durationInSeconds); } progress.setRemainingTime(remainingTime); progress.setMessage("Scanning job insights at " + percentage + "%"); progress.setError(""); prevPercentage = percentage; if(progressHandler != null){ progressHandler.accept(progress); } } } for(int i=0; i < data.size(); ++i){ JobInsight jobInsight = data.get(i); String skills = jobInsight.getSkills(); List<String> skillList = CollectionUtil.toList(skills.split(",")).stream() .map(String::trim) .filter(entry -> !StringUtils.isEmpty(entry)) .collect(Collectors.toList()); String companyName = StringUtils.replace(jobInsight.getCompanyName(), "\t", " "); String jobTitle = StringUtils.replace(jobInsight.getJobTitle(), "\t", " "); if(StringUtils.isEmpty(companyName) || StringUtils.isEmpty(jobTitle)){ continue; } for(int j=0; j < skillList.size(); ++j){ String skill = skillList.get(j).replace("\t", " "); writer.write(skill+"\t"+companyName+"\t"+jobTitle+"\r\n"); } } pageIndex++; } writer.close(); MyWorkerProgress progress = new MyWorkerProgress(); progress.setPercentage(100); progress.setRemainingTime(0); progress.setMessage("Scanning job insights at 100%"); progress.setError(""); if(progressHandler != null){ progressHandler.accept(progress); } MyWorkerCompleted completed = new MyWorkerCompleted(); completed.setChangedRows(totalPages); completed.setMessage(SparkGraphMinerCommand.COMMAND_GRAPH_MINING + ": Successfully extracted job insights from database"); return completed; } }
34.473282
128
0.644818
b60c8e5d40080acaa193a06419b5a10afe11e520
4,337
/* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.*/ /* DESCRIPTION The code sample shows how to use the DataSource API to establish a SSL connection to the Database using Java Key Store (JKS) files. You can specify JKS related properties as connection properties. Fully managed Oracle database services mandates SSL connection using JKS. Note that an instance of oracle.jdbc.pool.OracleDataSource doesn't provide any connection pooling. It's just a connection factory. A connection pool, such as Universal Connection Pool (UCP), can be configured to use an instance of oracle.jdbc.pool.OracleDataSource to create connections and then cache them. Step 1: Enter the Database details in this file. DB_USER, DB_PASSWORD and DB_URL are required Step 2: Run the sample with "ant DataSourceForJKS" NOTES Use JDK 1.7 and above MODIFIED (MM/DD/YY) nbsundar 02/17/15 - Creation */ import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import oracle.jdbc.pool.OracleDataSource; import oracle.jdbc.OracleConnection; import java.sql.DatabaseMetaData; public class DataSourceForJKS { // Connection string has a "dbaccess" as TNS alias for the connection // present in tnsnames.ora. Set the TNS_ADMIN property // to point to the location of tnsnames.ora final static String DB_URL= "jdbc:oracle:thin:@dbaccess"; final static String DB_USER = "myuser"; final static String DB_PASSWORD = "mypassword"; /* * The method gets a database connection using * oracle.jdbc.pool.OracleDataSource. It sets JKS related connection * level properties as shown here. Refer to * the OracleConnection interface to find more. */ public static void main(String args[]) throws SQLException { Properties info = new Properties(); info.put(OracleConnection.CONNECTION_PROPERTY_USER_NAME, DB_USER); info.put(OracleConnection.CONNECTION_PROPERTY_PASSWORD, DB_PASSWORD); // Set the SSL related connection properties info.put(OracleConnection.CONNECTION_PROPERTY_THIN_SSL_SERVER_DN_MATCH,"true"); info.put(OracleConnection.CONNECTION_PROPERTY_TNS_ADMIN,"/home/user/cloud"); info.put(OracleConnection.CONNECTION_PROPERTY_THIN_SSL_VERSION,"1.2"); // Set the JKS related connection properties info.put(OracleConnection.CONNECTION_PROPERTY_THIN_JAVAX_NET_SSL_KEYSTORE, "/home/user/cloud/keystore.jks"); info.put(OracleConnection.CONNECTION_PROPERTY_THIN_JAVAX_NET_SSL_KEYSTOREPASSWORD,"Welcome1"); info.put(OracleConnection.CONNECTION_PROPERTY_THIN_JAVAX_NET_SSL_TRUSTSTORE, "/home/user/cloud/truststore.jks"); info.put(OracleConnection.CONNECTION_PROPERTY_THIN_JAVAX_NET_SSL_TRUSTSTOREPASSWORD,"Welcome1"); OracleDataSource ods = new OracleDataSource(); ods.setURL(DB_URL); ods.setConnectionProperties(info); // With AutoCloseable, the connection is closed automatically. try (OracleConnection connection = (OracleConnection) ods.getConnection()) { // Get the JDBC driver name and version DatabaseMetaData dbmd = connection.getMetaData(); System.out.println("Driver Name: " + dbmd.getDriverName()); System.out.println("Driver Version: " + dbmd.getDriverVersion()); // Print some connection properties System.out.println("Default Row Prefetch Value is: " + connection.getDefaultRowPrefetch()); System.out.println("Database Username is: " + connection.getUserName()); System.out.println(); // Perform a database operation printEmployees(connection); } } /* * Displays first_name and last_name from the employees table. */ public static void printEmployees(Connection connection) throws SQLException { // Statement and ResultSet are AutoCloseable and closed automatically. try (Statement statement = connection.createStatement()) { try (ResultSet resultSet = statement .executeQuery("select sysdate from dual")) { while (resultSet.next()) System.out.println("Today's date is " + resultSet.getString(1)); } } } }
43.808081
106
0.730689
d2a0e3c1c95add6b441a41207ba6c39646fd3c25
3,661
// Chapter 16 Example 1 - FindCustomer GUI // Modified from Chapter 11 Example import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.Vector; public class FindCustomer extends JFrame implements ActionListener { // variables needing class scope Vector customers, customerNames; JList customerList; JLabel customerAddressText, customerPhoneText; JButton findButton, closeButton; Customer aCustomer; public static void main(String args[]) { Customer.initialize(); // create database connection FindCustomer frame = new FindCustomer(); } // constructor public FindCustomer() { // Use GridLayout and 3 panels for the Frame instance Container c = this.getContentPane(); c.setLayout(new GridLayout(3,1)); JPanel centerPanel = new JPanel(new GridLayout(1,2)); JPanel centerRightPanel = new JPanel(new GridLayout(2,1)); JPanel lowerPanel = new JPanel(new FlowLayout()); // create logo JLabel logoLabel = new JLabel(" ",SwingConstants.CENTER); logoLabel.setForeground(Color.red); logoLabel.setFont(new Font("TimesRoman", Font.ITALIC,36)); logoLabel.setText("Bradshaw Marina"); c.add(logoLabel); // add logo to the Frame // build JList customers = Customer.getAll();// get vector of all customers customerNames = new Vector(); // names used for JList for(int i = 0; i < customers.size(); i++) { //get customer reference, its name, and add to Vector aCustomer = (Customer) customers.get(i); String customerName = aCustomer.getName(); customerNames.add(customerName); } // create the list customerList = new JList(customerNames); // add scroll bars to the list JScrollPane scrollPaneCustomerList = new JScrollPane(customerList); // create labels for address & phone customerAddressText = new JLabel(" "); customerPhoneText = new JLabel(" "); // add list and labels to the panels centerPanel.add(scrollPaneCustomerList); centerRightPanel.add(customerAddressText); centerRightPanel.add(customerPhoneText); centerPanel.add(centerRightPanel); c.add(centerPanel); // add center panel to the Frame // create & add Buttons for bottom panel findButton = new JButton("Find"); closeButton = new JButton("Close"); lowerPanel.add(findButton); lowerPanel.add(closeButton); c.add(lowerPanel); this.setSize(300,200); this.setTitle("Find A Customer"); this.setVisible(true); // register frame as listener for button events findButton.addActionListener(this); closeButton.addActionListener(this); // create anonymous inner class to for window closing event this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent event) {shutDown();} } ); } // actionPerformed is invoked when a Button is clicked public void actionPerformed(ActionEvent e) { // see which button was clicked and findCustomer or shutDown if(e.getSource() == findButton) {findCustomer();} if(e.getSource() == closeButton) {shutDown();} } private void findCustomer() { // get index of list item selected int i = customerList.getSelectedIndex(); // get corresponding customer reference aCustomer = (Customer) customers.get(i); // put customer info in labels customerAddressText.setText(aCustomer.getAddress()); customerPhoneText.setText(aCustomer.getPhoneNo()); } private void shutDown() { Customer.terminate(); // release database resource System.exit(0); } }
32.39823
67
0.684512
bf5bb9a3ebf7d7eda9e613f88f05dbff391c5e7d
1,072
import java.util.*; // util 패키지 임포트 //public class exam011 { // public static void main(String[] args){ // System.out.println("Hello World!"); // // } //} class FormatSample{ public static void main(String[] args){ int a =10; double b =3.4; System.out.printf("%10d\n",a); System.out.printf("X %8.5f\n", b); System.out.printf("-----------\n"); System.out.printf("%10f\n\n", a * b); } } class Number{ public static void main(String[] args){ int[] a = {1, 2, 3, 4}; System.out.println((a[0])); System.out.println(a[3]); } } public class exam01{ public static void main(String[] args){ int num = 0; System.out.print("*을 출력할 라인의 수를 입력하세요.>"); Scanner scanner = new Scanner(System.in); String tmp = scanner.nextLine(); num = Integer.parseInt(tmp); for(int i=0; i<num; i++){ for(int j=0; j<=i; j++){ System.out.print("*"); } System.out.println(); } } }
22.808511
50
0.500933
1e77da5d4f9b05062abc6f23c35710dadfa60512
17,593
import org.junit.Test; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** PLEASE NOTE: THESE TESTS GUARANTEE NO MARKS. THESE TESTS ARE NOT GUARANTEED TO BE CORRECT. THESE TESTS DO NOT FOLLOW STYLE GUIDE. USE AT YOUR OWN RISK. NO STAFF MEMBER WILL BE RESPONSIBLE FOR ANYTHING RELATED TO THIS FILE. NO CLARIFICATIONS WILL BE POSTED ABOUT THIS FILE. NO UPDATES WILL BE MADE. USAGE: Place this in your test folder and run this test. You will need to have made every file for each test to run. Good luck. */ public class SpecTest { @Test public void testBoundsMapper() throws NoSuchMethodException, NoSuchFieldException { Class<BoundsMapper> c = BoundsMapper.class; // Constructors Constructor<BoundsMapper> con = c.getDeclaredConstructor(Room.class); assertEquals("public BoundsMapper(Room)", con.toString() ); // Extends assertEquals(c.getSuperclass(), MapWalker.class); // methods Method m = c.getDeclaredMethod("reset"); assertEquals("public void BoundsMapper.reset()", m.toString()); m = c.getDeclaredMethod("visit", Room.class); assertEquals("protected void BoundsMapper.visit(Room)", m.toString()); // Fields Field f = c.getField("coords"); assertEquals("public java.util.Map BoundsMapper.coords", f.toString()); f = c.getField("xMax"); assertEquals("public int BoundsMapper.xMax", f.toString()); f = c.getField("xMin"); assertEquals("public int BoundsMapper.xMin", f.toString()); f = c.getField("yMax"); assertEquals("public int BoundsMapper.yMax", f.toString()); f = c.getField("yMin"); assertEquals("public int BoundsMapper.yMin", f.toString()); } @Test public void testBuilder() throws NoSuchMethodException { Class<Builder> c = Builder.class; // Constructors Constructor con = c.getDeclaredConstructor(String.class, String.class, Room.class); assertEquals("public Builder(java.lang.String,java.lang.String,Room)", con.toString()); // Extends assertEquals(c.getSuperclass(), Player.class); // methods Method m = c.getDeclaredMethod("getDamage"); assertEquals("public int Builder.getDamage()", m.toString()); m = c.getDeclaredMethod("takeDamage", int.class); assertEquals("public void Builder.takeDamage(int)", m.toString()); m = c.getDeclaredMethod("repr"); assertEquals("public java.lang.String Builder.repr()", m.toString()); m = c.getDeclaredMethod("decode", String.class, Room.class); assertEquals("public static Builder Builder.decode(java.lang.String,Room)", m.toString()); } @Test public void testCrawlException() { Class c = CrawlException.class; assertEquals(Exception.class, c.getSuperclass()); } @Test public void testCritter() throws NoSuchMethodException { Class<Critter> c = Critter.class; // Constructors Constructor<Critter> con = c.getDeclaredConstructor(String.class, String.class, double.class, int.class); assertEquals("public Critter(java.lang.String,java.lang.String,double,int)", con.toString()); // Extends assertEquals(Thing.class, c.getSuperclass()); // Implements assertTrue(Arrays.asList(c.getInterfaces()).contains(Mob.class)); assertTrue(Arrays.asList(c.getInterfaces()).contains(Lootable.class)); // methods Method m = c.getDeclaredMethod("getDescription"); assertEquals("public java.lang.String Critter.getDescription()", m.toString()); m = c.getDeclaredMethod("takeDamage", int.class); assertEquals("public void Critter.takeDamage(int)", m.toString()); m = c.getDeclaredMethod("getDamage"); assertEquals("public int Critter.getDamage()", m.toString()); m = c.getDeclaredMethod("getValue"); assertEquals("public double Critter.getValue()", m.toString()); m = c.getDeclaredMethod("canLoot", Thing.class); assertEquals("public boolean Critter.canLoot(Thing)", m.toString()); m = c.getDeclaredMethod("fight", Mob.class); assertEquals("public void Critter.fight(Mob)", m.toString()); m = c.getDeclaredMethod("wantsToFight", Mob.class); assertEquals("public boolean Critter.wantsToFight(Mob)", m.toString()); m = c.getDeclaredMethod("isAlive"); assertEquals("public boolean Critter.isAlive()", m.toString()); m = c.getDeclaredMethod("setAlive", boolean.class); assertEquals("public void Critter.setAlive(boolean)", m.toString()); m = c.getDeclaredMethod("getHealth"); assertEquals("public int Critter.getHealth()", m.toString()); m = c.getDeclaredMethod("repr"); assertEquals("public java.lang.String Critter.repr()", m.toString()); m = c.getDeclaredMethod("decode", String.class); assertEquals("public static Critter Critter.decode(java.lang.String)", m.toString()); } @Test public void testExitExistsException() { Class c = ExitExistsException.class; assertEquals(CrawlException.class, c.getSuperclass()); } @Test public void testExplorer() throws NoSuchMethodException { Class<Explorer> c = Explorer.class; // Constructors Constructor<Explorer> con = c.getDeclaredConstructor(Player.class); assertEquals("public Explorer(Player)", con.toString()); con = c.getDeclaredConstructor(String.class, String.class); assertEquals("public Explorer(java.lang.String,java.lang.String)", con.toString()); con = c.getDeclaredConstructor(String.class, String.class, int.class); assertEquals("public Explorer(java.lang.String,java.lang.String,int)", con.toString()); // Extends assertEquals(c.getSuperclass(), Player.class); // methods Method m = c.getDeclaredMethod("getDescription"); assertEquals("public java.lang.String Explorer.getDescription()", m.toString()); m = c.getDeclaredMethod("getDamage"); assertEquals("public int Explorer.getDamage()", m.toString()); m = c.getDeclaredMethod("repr"); assertEquals("public java.lang.String Explorer.repr()", m.toString()); m = c.getDeclaredMethod("decode", String.class); assertEquals("public static Explorer Explorer.decode(java.lang.String)", m.toString()); } @Test public void testLootable() throws NoSuchMethodException { Class<Lootable> c = Lootable.class; // methods Method m = c.getDeclaredMethod("getValue"); assertEquals("public abstract double Lootable.getValue()", m.toString()); m = c.getDeclaredMethod("canLoot", Thing.class); assertEquals("public abstract boolean Lootable.canLoot(Thing)", m.toString()); } @Test public void testMapIO() throws NoSuchMethodException { Class<MapIO> c = MapIO.class; // Constructors Constructor<MapIO> con = c.getDeclaredConstructor(); assertEquals(con.toString(), "public MapIO()" ); // methods Method m = c.getDeclaredMethod("serializeMap", Room.class, String.class); assertEquals("public static boolean MapIO.serializeMap(Room,java.lang.String)", m.toString()); m = c.getDeclaredMethod("deserializeMap", String.class); assertEquals("public static Room MapIO.deserializeMap(java.lang.String)", m.toString()); m = c.getDeclaredMethod("saveMap", Room.class, String.class); assertEquals("public static boolean MapIO.saveMap(Room,java.lang.String)", m.toString()); m = c.getDeclaredMethod("decodeThing", String.class, Room.class); assertEquals("public static Thing MapIO.decodeThing(java.lang.String,Room)", m.toString()); m = c.getDeclaredMethod("loadMap", String.class); assertEquals("public static java.lang.Object[] MapIO.loadMap(java.lang.String)", m.toString()); } @Test public void testMapWalker() throws NoSuchMethodException { Class<MapWalker> c = MapWalker.class; // Constructors Constructor<MapWalker> con = c.getDeclaredConstructor(Room.class); assertEquals("public MapWalker(Room)", con.toString()); // methods Method m = c.getDeclaredMethod("reset"); assertEquals("protected void MapWalker.reset()", m.toString()); m = c.getDeclaredMethod("walk"); assertEquals("public void MapWalker.walk()", m.toString()); m = c.getDeclaredMethod("hasVisited", Room.class); assertEquals("public boolean MapWalker.hasVisited(Room)", m.toString()); m = c.getDeclaredMethod("visit", Room.class); assertEquals("protected void MapWalker.visit(Room)", m.toString()); } @Test public void testMob() throws NoSuchMethodException { Class<Mob> c = Mob.class; // Methods Method m = c.getMethod("fight", Mob.class); assertEquals("public abstract void Mob.fight(Mob)", m.toString()); m = c.getMethod("getDamage"); assertEquals("public abstract int Mob.getDamage()", m.toString()); m = c.getMethod("isAlive"); assertEquals("public abstract boolean Mob.isAlive()", m.toString()); m = c.getMethod("setAlive", boolean.class); assertEquals("public abstract void Mob.setAlive(boolean)", m.toString()); m = c.getMethod("takeDamage", int.class); assertEquals("public abstract void Mob.takeDamage(int)", m.toString()); m = c.getMethod("wantsToFight", Mob.class); assertEquals("public abstract boolean Mob.wantsToFight(Mob)", m.toString()); } @Test public void testNullRoomException() { Class<NullRoomException> c = NullRoomException.class; assertEquals(c.getSuperclass(), CrawlException.class); } @Test public void testPair() throws Exception { Class<Pair> p = Pair.class; //constructor Constructor<Pair> con = p.getConstructor(int.class, int.class); assertEquals("public Pair(int,int)", con.toString()); // fields Field f = p.getField("x"); assertEquals("public int Pair.x", f.toString()); f = p.getField("y"); assertEquals("public int Pair.y", f.toString()); // methods Method m = p.getDeclaredMethod("equals", Object.class); assertEquals("public boolean Pair.equals(java.lang.Object)", m.toString()); m = p.getDeclaredMethod("hashCode"); assertEquals("public int Pair.hashCode()", m.toString()); } @Test public void testPlayer() throws Exception { Class<Player> p = Player.class; // Extends assertEquals(p.getSuperclass(), Thing.class); // interfaces assertTrue(Arrays.asList(p.getInterfaces()).contains(Mob.class)); // constructor Constructor<Player> con = p.getConstructor(String.class, String.class); assertEquals("public Player(java.lang.String,java.lang.String)", con.toString()); con = p.getConstructor(String.class, String.class, int.class); assertEquals("public Player(java.lang.String,java.lang.String,int)", con.toString()); // methods Method m = p.getDeclaredMethod("add", Thing.class); assertEquals("public void Player.add(Thing)", m.toString()); m = p.getDeclaredMethod("drop", Thing.class); assertEquals("public void Player.drop(Thing)", m.toString()); m = p.getDeclaredMethod("drop", String.class); assertEquals("public Thing Player.drop(java.lang.String)", m.toString()); m = p.getDeclaredMethod("fight", Mob.class); assertEquals("public void Player.fight(Mob)", m.toString()); m = p.getDeclaredMethod("getContents"); assertEquals("public java.util.List Player.getContents()", m.toString()); m = p.getDeclaredMethod("getHealth"); assertEquals("public int Player.getHealth()", m.toString()); m = p.getDeclaredMethod("isAlive"); assertEquals("public boolean Player.isAlive()", m.toString()); m = p.getDeclaredMethod("setAlive", boolean.class); assertEquals("public void Player.setAlive(boolean)", m.toString()); m = p.getDeclaredMethod("takeDamage", int.class); assertEquals("public void Player.takeDamage(int)", m.toString()); m = p.getDeclaredMethod("wantsToFight", Mob.class); assertEquals("public boolean Player.wantsToFight(Mob)", m.toString()); } @Test public void testRoom() throws Exception { Class<Room> r = Room.class; // constructor Constructor<Room> c = r.getConstructor(String.class); assertEquals("public Room(java.lang.String)", c.toString()); // methods Method m = r.getDeclaredMethod("addExit", String.class, Room.class); //exception assertTrue(Arrays.asList(m.getExceptionTypes()).contains(ExitExistsException.class)); assertTrue(Arrays.asList(m.getExceptionTypes()).contains(NullRoomException.class)); // modifier and return type assertTrue(Modifier.isPublic(m.getModifiers())); assertTrue(Arrays.asList(m.getReturnType(), new Class[]{}).contains(void.class)); m = r.getDeclaredMethod("enter", Thing.class); assertEquals("public void Room.enter(Thing)", m.toString()); m = r.getDeclaredMethod("getContents"); assertEquals("public java.util.List Room.getContents()", m.toString()); m = r.getDeclaredMethod("getDescription"); assertEquals("public java.lang.String Room.getDescription()", m.toString()); m = r.getDeclaredMethod("getExits"); assertEquals("public java.util.Map Room.getExits()", m.toString()); m = r.getDeclaredMethod("leave", Thing.class); assertEquals("public boolean Room.leave(Thing)", m.toString()); m = r.getDeclaredMethod("makeExitPair", Room.class, Room.class, String.class, String.class); assertTrue(Arrays.asList(m.getExceptionTypes()).contains(ExitExistsException.class)); assertTrue(Arrays.asList(m.getExceptionTypes()).contains(NullRoomException.class)); assertTrue(Modifier.isStatic(m.getModifiers())); // this is probably unnecessary :P assertTrue(Arrays.asList(m.getReturnType(), new Class[]{}).contains(void.class)); assertTrue(Arrays.asList(m.getParameterTypes()).contains(Room.class)); assertTrue(Arrays.asList(m.getParameterTypes()).contains(String.class)); assertEquals(4, m.getParameterCount()); m = r.getDeclaredMethod("removeExit", String.class); assertEquals("public void Room.removeExit(java.lang.String)", m.toString()); m = r.getDeclaredMethod("setDescription", String.class); assertEquals("public void Room.setDescription(java.lang.String)", m.toString()); } @Test public void testThing() throws Exception { Class<Thing> t = Thing.class; // is abstract assertTrue(Modifier.isAbstract(t.getModifiers())); // constructor Constructor<Thing> c = t.getConstructor(String.class, String.class); assertEquals("public Thing(java.lang.String,java.lang.String)", c.toString()); // methods Method m = t.getDeclaredMethod("getDescription"); assertEquals("public java.lang.String Thing.getDescription()", m.toString()); m = t.getDeclaredMethod("getLong"); assertEquals("protected java.lang.String Thing.getLong()", m.toString()); m = t.getDeclaredMethod("getShort"); assertEquals("protected java.lang.String Thing.getShort()", m.toString()); m = t.getDeclaredMethod("getShortDescription"); assertEquals("public java.lang.String Thing.getShortDescription()", m.toString()); m = t.getDeclaredMethod("repr"); assertEquals("public abstract java.lang.String Thing.repr()", m.toString()); m = t.getDeclaredMethod("setLong", String.class); assertEquals("protected void Thing.setLong(java.lang.String)", m.toString()); m = t.getDeclaredMethod("setShort", String.class); assertEquals("protected void Thing.setShort(java.lang.String)", m.toString()); } @Test public void testTreasure() throws Exception { Class<Treasure> t = Treasure.class; // Extends assertEquals(t.getSuperclass(), Thing.class); // Implements assertTrue(Arrays.asList(t.getInterfaces()).contains(Lootable.class)); // constructors Constructor<Treasure> c = t.getConstructor(String.class, double.class); assertEquals("public Treasure(java.lang.String,double)", c.toString()); // methods Method m = t.getDeclaredMethod("canLoot", Thing.class); assertEquals(m.toString(), "public boolean Treasure.canLoot(Thing)"); m = t.getDeclaredMethod("decode", String.class); assertEquals(m.toString(), "public static Treasure Treasure.decode(java.lang.String)"); m = t.getDeclaredMethod("getValue"); assertEquals(m.toString(), "public double Treasure.getValue()"); m = t.getDeclaredMethod("repr"); assertEquals(m.toString(), "public java.lang.String Treasure.repr()"); } }
41.788599
113
0.655431
935057532a42375f621a9f8156087e61c34b3ad1
2,339
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.hadoop; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import org.elasticsearch.hadoop.util.StringUtils; import org.elasticsearch.hadoop.util.StringUtils.IpAndPort; public class EsEmbeddedServer { private static final String ES_PORTS_FILE_LOCATION = "es.test.ports.file.location"; private IpAndPort ipAndPort; public EsEmbeddedServer() { try { String path = System.getProperty(ES_PORTS_FILE_LOCATION); if (path == null) { // No local ES stood up. Better throw... throw new IllegalStateException("Could not find Elasticsearch ports file. Should " + "you be running tests with an external cluster?"); } File portsFile = new File(path); try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(portsFile)))) { for (String line = in.readLine(); line != null; line = in.readLine()) { if (line.contains("[") || line.contains("]") || line.isEmpty()) { continue; } ipAndPort = StringUtils.parseIpAddress(line); break; } } } catch (Exception e) { throw new EsHadoopException("Encountered exception during embedded node startup", e); } } public IpAndPort getIpAndPort() { return ipAndPort; } }
37.126984
113
0.652416
9c6495b0fc9f4ea6cff904428195d8eb1c6a79f5
191
package com.hkamran.ai; /** * Interface for the fitness function in a NEAT network. * @author hkamran * */ public interface NeatFitness { public double calculate(Network network); }
14.692308
56
0.717277
8ef13feb7c2f94e79fa35e8ac8b6f96422de291d
1,576
package DFAsimulation; import java.util.Scanner; public class Application { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String startingState = null; int acceptStatesCount = 0; String[] acceptStates; String word = null; String check = ""; //String[][] transactionTable = DFA.readyToUseExample(); //String[][] transactionTable = DFA.readyToUseExample2(); //String[][] transactionTable = DFA.readyToUseExample3(); String[][] transactionTable = DFA.getTransactionTableFromUser(); DFA.printTransactionTable(transactionTable); do { System.out.println("Enter starting state:"); startingState = scan.next(); } while (!DFA.checkNode(transactionTable, startingState)); System.out.println("How many accepting state(s) available?"); acceptStatesCount = scan.nextInt(); acceptStates = new String[acceptStatesCount]; for(int i = 0; i < acceptStatesCount; i++) { do { System.out.println("Enter accepting state(s):"); acceptStates[i] = scan.next(); } while (!DFA.checkNode(transactionTable, acceptStates[i])); } while(!check.equals("end")) { do { System.out.println("Enter a word to simulate: (the input)"); word = scan.next(); } while (!DFA.checkWord(transactionTable, word)); DFA.simulate(transactionTable,startingState,acceptStates,acceptStatesCount,word); System.out.println("Continue? (type 'end' to exit, or anything else to continue.)"); check = scan.next(); System.out.println(); } scan.close(); } }
25.419355
87
0.674492
9c7ec98dcf449e80afad672c16722ad449e2161c
10,031
/* * Thrifty * * Copyright (c) Microsoft Corporation * * 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 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.gen; import com.microsoft.thrifty.Adapter; import com.microsoft.thrifty.TType; import com.microsoft.thrifty.protocol.Protocol; import com.microsoft.thrifty.schema.BuiltinType; import com.microsoft.thrifty.schema.EnumType; import com.microsoft.thrifty.schema.ListType; import com.microsoft.thrifty.schema.MapType; import com.microsoft.thrifty.schema.NamespaceScope; import com.microsoft.thrifty.schema.ServiceType; import com.microsoft.thrifty.schema.SetType; import com.microsoft.thrifty.schema.StructType; import com.microsoft.thrifty.schema.ThriftType; import com.microsoft.thrifty.schema.TypedefType; import com.microsoft.thrifty.schema.UserType; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.NameAllocator; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import java.util.ArrayDeque; import java.util.Deque; /** * Generates Java code to read a field's value from an open Protocol object. * * Assumptions: * We are inside of {@link Adapter#read(Protocol)}. Further, we are * inside of a single case block for a single field. There are variables * in scope named "protocol" and "builder", representing the connection and * the struct builder. */ class GenerateReaderVisitor implements ThriftType.Visitor<Void> { private Deque<String> nameStack = new ArrayDeque<>(); private TypeResolver resolver; private NameAllocator nameAllocator; private MethodSpec.Builder read; private String fieldName; private ThriftType fieldType; private int scope; GenerateReaderVisitor(TypeResolver resolver, MethodSpec.Builder read, String fieldName, ThriftType fieldType) { this.resolver = resolver; this.read = read; this.fieldName = fieldName; this.fieldType = fieldType; } public void generate() { byte fieldTypeCode = resolver.getTypeCode(fieldType); if (fieldTypeCode == TType.ENUM) { // Enums are I32 on the wire fieldTypeCode = TType.I32; } String codeName = TypeNames.getTypeCodeName(fieldTypeCode); read.beginControlFlow("if (field.typeId == $T.$L)", TypeNames.TTYPE, codeName); nameStack.push("value"); fieldType.accept(this); nameStack.pop(); useReadValue("value"); read.nextControlFlow("else"); read.addStatement("$T.skip(protocol, field.typeId)", TypeNames.PROTO_UTIL); read.endControlFlow(); } protected void useReadValue(String localName) { read.addStatement("builder.$N($N)", fieldName, localName); } @Override public Void visitBool(BuiltinType boolType) { read.addStatement("$T $N = protocol.readBool()", TypeNames.BOOLEAN.unbox(), nameStack.peek()); return null; } @Override public Void visitByte(BuiltinType bytetype) { read.addStatement("$T $N = protocol.readByte()", TypeNames.BYTE.unbox(), nameStack.peek()); return null; } @Override public Void visitI16(BuiltinType i16Type) { read.addStatement("$T $N = protocol.readI16()", TypeNames.SHORT.unbox(), nameStack.peek()); return null; } @Override public Void visitI32(BuiltinType i32Type) { read.addStatement("$T $N = protocol.readI32()", TypeNames.INTEGER.unbox(), nameStack.peek()); return null; } @Override public Void visitI64(BuiltinType i64Type) { read.addStatement("$T $N = protocol.readI64()", TypeNames.LONG.unbox(), nameStack.peek()); return null; } @Override public Void visitDouble(BuiltinType doubleType) { read.addStatement("$T $N = protocol.readDouble()", TypeNames.DOUBLE.unbox(), nameStack.peek()); return null; } @Override public Void visitString(BuiltinType stringType) { read.addStatement("$T $N = protocol.readString()", TypeNames.STRING, nameStack.peek()); return null; } @Override public Void visitBinary(BuiltinType binaryType) { read.addStatement("$T $N = protocol.readBinary()", TypeNames.BYTE_STRING, nameStack.peek()); return null; } @Override public Void visitVoid(BuiltinType voidType) { throw new AssertionError("Cannot read void"); } @Override public Void visitEnum(EnumType enumType) { String target = nameStack.peek(); String qualifiedJavaName = getFullyQualifiedJavaName(enumType); read.addStatement("$1L $2N = $1L.findByValue(protocol.readI32())", qualifiedJavaName, target); return null; } @Override public Void visitList(ListType listType) { initNameAllocator(); TypeName elementType = resolver.getJavaClass(listType.elementType().getTrueType()); TypeName genericListType = ParameterizedTypeName.get(TypeNames.LIST, elementType); TypeName listImplType = resolver.listOf(elementType); String listInfo = "listMetadata" + scope; String idx = "i" + scope; String item = "item" + scope; read.addStatement("$T $N = protocol.readListBegin()", TypeNames.LIST_META, listInfo); read.addStatement("$T $N = new $T($N.size)", genericListType, nameStack.peek(), listImplType, listInfo); read.beginControlFlow("for (int $1N = 0; $1N < $2N.size; ++$1N)", idx, listInfo); ++scope; nameStack.push(item); listType.elementType().getTrueType().accept(this); nameStack.pop(); --scope; read.addStatement("$N.add($N)", nameStack.peek(), item); read.endControlFlow(); read.addStatement("protocol.readListEnd()"); return null; } @Override public Void visitSet(SetType setType) { initNameAllocator(); TypeName elementType = resolver.getJavaClass(setType.elementType().getTrueType()); TypeName genericSetType = ParameterizedTypeName.get(TypeNames.SET, elementType); TypeName setImplType = resolver.setOf(elementType); String setInfo = "setMetadata" + scope; String idx = "i" + scope; String item = "item" + scope; read.addStatement("$T $N = protocol.readSetBegin()", TypeNames.SET_META, setInfo); read.addStatement("$T $N = new $T($N.size)", genericSetType, nameStack.peek(), setImplType, setInfo); read.beginControlFlow("for (int $1N = 0; $1N < $2N.size; ++$1N)", idx, setInfo); ++scope; nameStack.push(item); setType.elementType().accept(this); nameStack.pop(); --scope; read.addStatement("$N.add($N)", nameStack.peek(), item); read.endControlFlow(); read.addStatement("protocol.readSetEnd()"); return null; } @Override public Void visitMap(MapType mapType) { initNameAllocator(); TypeName keyType = resolver.getJavaClass(mapType.keyType().getTrueType()); TypeName valueType = resolver.getJavaClass(mapType.valueType().getTrueType()); TypeName genericMapType = ParameterizedTypeName.get(TypeNames.MAP, keyType, valueType); TypeName mapImplType = resolver.mapOf(keyType, valueType); String mapInfo = "mapMetadata" + scope; String idx = "i" + scope; String key = "key" + scope; String value = "value" + scope; ++scope; read.addStatement("$T $N = protocol.readMapBegin()", TypeNames.MAP_META, mapInfo); read.addStatement("$T $N = new $T($N.size)", genericMapType, nameStack.peek(), mapImplType, mapInfo); read.beginControlFlow("for (int $1N = 0; $1N < $2N.size; ++$1N)", idx, mapInfo); nameStack.push(key); mapType.keyType().accept(this); nameStack.pop(); nameStack.push(value); mapType.valueType().accept(this); nameStack.pop(); read.addStatement("$N.put($N, $N)", nameStack.peek(), key, value); read.endControlFlow(); read.addStatement("protocol.readMapEnd()"); --scope; return null; } @Override public Void visitStruct(StructType userType) { String qualifiedJavaName = getFullyQualifiedJavaName(userType); read.addStatement("$1L $2N = $1L.ADAPTER.read(protocol)", qualifiedJavaName, nameStack.peek()); return null; } @Override public Void visitTypedef(TypedefType typedefType) { // throw AssertionError? typedefType.getTrueType().accept(this); return null; } @Override public Void visitService(ServiceType serviceType) { throw new AssertionError("Cannot read a service"); } private String getFullyQualifiedJavaName(UserType type) { if (type.isBuiltin() || type.isList() || type.isMap() || type.isSet() || type.isTypedef()) { throw new AssertionError("Only user and enum types are supported"); } String packageName = type.getNamespaceFor(NamespaceScope.JAVA); return packageName + "." + type.name(); } private void initNameAllocator() { if (nameAllocator == null) { nameAllocator = new NameAllocator(); nameAllocator.newName("protocol", "protocol"); nameAllocator.newName("builder", "builder"); nameAllocator.newName("value", "value"); } } }
34.35274
116
0.663144
cdf9599b1813f94c6ecc5ca069915de6185d5abf
1,612
/** * ************************************************************************ * * The contents of this file are subject to the MRPL 1.2 * * (the "License"), being the Mozilla Public License * * Version 1.1 with a permitted attribution clause; you may not use this * * file except in compliance with the License. You may obtain a copy of * * the License at http://www.floreantpos.org/license.html * * Software distributed under the License is distributed on an "AS IS" * * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * * License for the specific language governing rights and limitations * * under the License. * * The Original Code is FLOREANT POS. * * The Initial Developer of the Original Code is OROCUBE LLC * * All portions are Copyright (C) 2015 OROCUBE LLC * * All Rights Reserved. * ************************************************************************ */ package com.floreantpos.model.dao; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import com.floreantpos.model.Tax; public class TaxDAO extends BaseTaxDAO { /** * Default constructor. Can be used in place of getInstance() */ public TaxDAO() { } public Tax findByTaxRate(double taxRate) { Session session = null; try { session = createNewSession(); Criteria criteria = session.createCriteria(Tax.class); criteria.add(Restrictions.eq(Tax.PROP_RATE, taxRate)); return (Tax) criteria.uniqueResult(); } finally { closeSession(session); } } }
35.043478
77
0.629032
5e3013ebfcca73944006f4dc0b44389a56560b0d
119
import me.redteapot.junitathome.annot.Test; public class EmptyTest { @Test public void testEmpty() { } }
13.222222
43
0.672269
52312e765d7771986e35dd6e50a61713ae75bd43
6,696
/* * 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.facebook.presto.spi.block; import org.openjdk.jol.info.ClassLayout; import java.util.function.BiConsumer; import static io.airlift.slice.SizeOf.sizeOf; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public class RowBlock extends AbstractRowBlock { private static final int INSTANCE_SIZE = ClassLayout.parseClass(RowBlock.class).instanceSize(); private final int startOffset; private final int positionCount; private final boolean[] rowIsNull; private final int[] fieldBlockOffsets; private final Block[] fieldBlocks; private volatile long sizeInBytes; private final long retainedSizeInBytes; /** * Create a row block directly from columnar nulls and field blocks. */ public static Block fromFieldBlocks(boolean[] rowIsNull, Block[] fieldBlocks) { requireNonNull(rowIsNull, "rowIsNull is null"); int[] fieldBlockOffsets = new int[rowIsNull.length + 1]; for (int position = 0; position < rowIsNull.length; position++) { fieldBlockOffsets[position + 1] = fieldBlockOffsets[position] + (rowIsNull[position] ? 0 : 1); } validateConstructorArguments(0, rowIsNull.length, rowIsNull, fieldBlockOffsets, fieldBlocks); return new RowBlock(0, rowIsNull.length, rowIsNull, fieldBlockOffsets, fieldBlocks); } /** * Create a row block directly without per element validations. */ static RowBlock createRowBlockInternal(int startOffset, int positionCount, boolean[] rowIsNull, int[] fieldBlockOffsets, Block[] fieldBlocks) { validateConstructorArguments(startOffset, positionCount, rowIsNull, fieldBlockOffsets, fieldBlocks); return new RowBlock(startOffset, positionCount, rowIsNull, fieldBlockOffsets, fieldBlocks); } private static void validateConstructorArguments(int startOffset, int positionCount, boolean[] rowIsNull, int[] fieldBlockOffsets, Block[] fieldBlocks) { if (startOffset < 0) { throw new IllegalArgumentException("arrayOffset is negative"); } if (positionCount < 0) { throw new IllegalArgumentException("positionCount is negative"); } requireNonNull(rowIsNull, "rowIsNull is null"); if (rowIsNull.length - startOffset < positionCount) { throw new IllegalArgumentException("rowIsNull length is less than positionCount"); } requireNonNull(fieldBlockOffsets, "fieldBlockOffsets is null"); if (fieldBlockOffsets.length - startOffset < positionCount + 1) { throw new IllegalArgumentException("fieldBlockOffsets length is less than positionCount"); } requireNonNull(fieldBlocks, "fieldBlocks is null"); if (fieldBlocks.length <= 0) { throw new IllegalArgumentException("Number of fields in RowBlock must be positive"); } int firstFieldBlockPositionCount = fieldBlocks[0].getPositionCount(); for (int i = 1; i < fieldBlocks.length; i++) { if (firstFieldBlockPositionCount != fieldBlocks[i].getPositionCount()) { throw new IllegalArgumentException(format("length of field blocks differ: field 0: %s, block %s: %s", firstFieldBlockPositionCount, i, fieldBlocks[i].getPositionCount())); } } } /** * Use createRowBlockInternal or fromFieldBlocks instead of this method. The caller of this method is assumed to have * validated the arguments with validateConstructorArguments. */ private RowBlock(int startOffset, int positionCount, boolean[] rowIsNull, int[] fieldBlockOffsets, Block[] fieldBlocks) { super(fieldBlocks.length); this.startOffset = startOffset; this.positionCount = positionCount; this.rowIsNull = rowIsNull; this.fieldBlockOffsets = fieldBlockOffsets; this.fieldBlocks = fieldBlocks; this.sizeInBytes = -1; long retainedSizeInBytes = INSTANCE_SIZE + sizeOf(fieldBlockOffsets) + sizeOf(rowIsNull); for (Block fieldBlock : fieldBlocks) { retainedSizeInBytes += fieldBlock.getRetainedSizeInBytes(); } this.retainedSizeInBytes = retainedSizeInBytes; } @Override protected Block[] getFieldBlocks() { return fieldBlocks; } @Override protected int[] getFieldBlockOffsets() { return fieldBlockOffsets; } @Override protected int getOffsetBase() { return startOffset; } @Override protected boolean[] getRowIsNull() { return rowIsNull; } @Override public int getPositionCount() { return positionCount; } @Override public long getSizeInBytes() { if (sizeInBytes < 0) { calculateSize(); } return sizeInBytes; } private void calculateSize() { int startFieldBlockOffset = fieldBlockOffsets[startOffset]; int endFieldBlockOffset = fieldBlockOffsets[startOffset + positionCount]; int fieldBlockLength = endFieldBlockOffset - startFieldBlockOffset; long sizeInBytes = (Integer.BYTES + Byte.BYTES) * (long) positionCount; for (int i = 0; i < numFields; i++) { sizeInBytes += fieldBlocks[i].getRegionSizeInBytes(startFieldBlockOffset, fieldBlockLength); } this.sizeInBytes = sizeInBytes; } @Override public long getRetainedSizeInBytes() { return retainedSizeInBytes; } @Override public void retainedBytesForEachPart(BiConsumer<Object, Long> consumer) { for (int i = 0; i < numFields; i++) { consumer.accept(fieldBlocks[i], fieldBlocks[i].getRetainedSizeInBytes()); } consumer.accept(fieldBlockOffsets, sizeOf(fieldBlockOffsets)); consumer.accept(rowIsNull, sizeOf(rowIsNull)); consumer.accept(this, (long) INSTANCE_SIZE); } @Override public String toString() { return format("RowBlock{numFields=%d, positionCount=%d}", numFields, getPositionCount()); } }
34.694301
187
0.678465
af17292f1f1ee4652462c02f3652324f6bccf27d
1,503
package io.quantumdb.cli.xml; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.base.Strings; import io.quantumdb.core.schema.operations.CreateView; import io.quantumdb.core.schema.operations.SchemaOperations; import lombok.Data; @Data public class XmlCreateView implements XmlOperation<CreateView> { static final String TAG = "createView"; static XmlOperation convert(XmlElement element) { checkArgument(element.getTag().equals(TAG)); XmlCreateView operation = new XmlCreateView(); operation.setViewName(element.getAttributes().get("viewName")); operation.setRecursive(Boolean.TRUE.toString().equals(element.getAttributes().get("recursive"))); operation.setTemporary(Boolean.TRUE.toString().equals(element.getAttributes().get("temporary"))); operation.setQuery(Strings.emptyToNull(element.getChildren().stream() .filter(child -> child.getTag().equals(XmlQuery.TAG)) .map(child -> (XmlQuery) XmlQuery.convert(child)) .map(XmlQuery::getQuery) .findFirst() .orElseThrow(() -> new RuntimeException("No query specified!")) .trim())); return operation; } private String viewName; private boolean recursive; private boolean temporary; private String query; @Override public CreateView toOperation() { CreateView operation = SchemaOperations.createView(viewName); if (recursive) { operation.recursive(); } if (temporary) { operation.temporary(); } operation.as(query); return operation; } }
28.903846
99
0.75183
6e5d1fc0b9e74581093cfe114cf8ed41a55e0f50
263
package com.roharon.huformationi.wrapper.component; import com.roharon.huformationi.wrapper.component.componentType.SimpleText; import lombok.*; @Getter @Builder @ToString public class SimpleTextView implements Component { private SimpleText simpleText; }
20.230769
75
0.821293
a9375f2c32965fe066bf775bc8ee1ff6e99a48e8
1,969
package com.liferay.support.tools.display.context; import com.liferay.frontend.taglib.clay.servlet.taglib.util.NavigationItem; import com.liferay.frontend.taglib.clay.servlet.taglib.util.NavigationItemList; import com.liferay.portal.kernel.language.LanguageUtil; import com.liferay.portal.kernel.portlet.LiferayPortletRequest; import com.liferay.portal.kernel.portlet.LiferayPortletResponse; import com.liferay.portal.kernel.portlet.PortalPreferences; import com.liferay.portal.kernel.portlet.PortletPreferencesFactoryUtil; import java.util.List; import javax.portlet.PortletPreferences; import javax.servlet.http.HttpServletRequest; /** * * Dummy Factory Display Context * * @author Yasuyuki Takeo * */ public class DummyFactoryDisplayContext { private HttpServletRequest _request; private LiferayPortletRequest _liferayPortletRequest; private LiferayPortletResponse _liferayPortletResponse; private PortletPreferences _portletPreferences; private PortalPreferences _portalPreferences; public DummyFactoryDisplayContext(HttpServletRequest request, LiferayPortletRequest liferayPortletRequest, LiferayPortletResponse liferayPortletResponse, PortletPreferences portletPreferences) { _request = request; _liferayPortletRequest = liferayPortletRequest; _liferayPortletResponse = liferayPortletResponse; _portletPreferences = portletPreferences; _portalPreferences = PortletPreferencesFactoryUtil .getPortalPreferences( _request ); } /** * Get Navigation Bar Items * * @param label * @return NavigationItem List */ public List<NavigationItem> getNavigationBarItems( String label ) { return new NavigationItemList() { { add( navigationItem -> { navigationItem.setActive( true ); navigationItem.setHref( _liferayPortletResponse.createRenderURL(), "currentPageName", label ); navigationItem .setLabel( LanguageUtil.get( _request, label ) ); }); } }; } }
29.833333
79
0.790249
cb1f19731545c998f5420d32c5f1e44a089f8796
1,949
package com.chatapp.message.entity; import com.chatapp.message.dto.MessageDto; import com.chatapp.message.exceptions.CustomException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.security.Principal; import java.util.UUID; @RestController @RequestMapping(path = "api/v1/message") public record MessageController(MessageService messageService) { private static final Logger LOGGER = LoggerFactory.getLogger(MessageController.class); @PostMapping() public MessageDto.Display createMessage(@RequestBody MessageDto.Base baseMessage, HttpServletResponse response, Principal principal){ response.setStatus(HttpStatus.CREATED.value()); LOGGER.info(principal.getName()); return this.messageService.create(baseMessage.toMessageEntity()).toDisplayMessage(); } @GetMapping(path = "{messageId}") public MessageDto.Base readMessage(HttpServletResponse response, @PathVariable("messageId") UUID messageId) throws CustomException { response.setStatus(HttpStatus.FOUND.value()); return this.messageService.findById(messageId).toBaseMessage(); } @PutMapping(path = "{messageId}") public MessageDto.Base updateMessage(HttpServletResponse response, @RequestBody MessageDto.Update updateMessage, @PathVariable("messageId") UUID messageId) throws CustomException { response.setStatus(HttpStatus.OK.value()); return this.messageService.update(messageId, updateMessage).toBaseMessage(); } @DeleteMapping(path = "{messageId}") public void deleteMessage(HttpServletResponse response, @PathVariable("messageId") UUID messageId) throws CustomException { this.messageService.delete(messageId); response.setStatus(HttpStatus.OK.value()); } }
43.311111
137
0.753207
366448b87d491f4183109d5b547f0d672202cb17
1,361
package com.dcits.dcwlt.pay.api.fun; import com.dcits.dcwlt.common.core.utils.StringUtils; import com.dcits.dcwlt.common.core.utils.SpringUtils; import com.dcits.dcwlt.pay.api.domain.dcep.eventBatch.EventDealReqMsg; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 方法调用工厂类 * @author */ public class FunInvokerFactory { private static final Logger logger = LoggerFactory.getLogger(FunInvokerFactory.class); public static FunInvoker getFunInvoker(String exceptEventTrxCode) { String [] strArr = StringUtils.split(exceptEventTrxCode, '/'); if (strArr.length != 2) { logger.error("exceptEventTrxCode must be like bean/method, please check exceptEventTrxCode: {}", exceptEventTrxCode); return null; } try { FunInvoker funInvoker = new FunInvoker(); Object bean = SpringUtils.getBean(strArr[0]); String [] paramNames = {"eventDealReqMsg"}; funInvoker.setBean(bean); funInvoker.setMethod(bean.getClass().getDeclaredMethod(strArr[1], EventDealReqMsg.class)); funInvoker.setParamNames(paramNames); return funInvoker; } catch (Exception e) { logger.error("bean or method not exist, please check exceptEventTrxCode: {}", exceptEventTrxCode); } return null; } }
34.897436
129
0.673769
52dfc5dae8329d6a78267eb661e969e24e97507f
987
package com.gochinatv.cdn.api.shardingjdbc; import io.shardingjdbc.core.api.algorithm.sharding.PreciseShardingValue; import io.shardingjdbc.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm; import java.util.Collection; /** * ${DESCRIPTION} * * https://github.com/sharding-sphere/sharding-sphere-example/blob/2.0.3/sharding-jdbc-raw-jdbc-example/sharding-jdbc-raw-jdbc-java-example/src/main/java/io/shardingjdbc/example/jdbc/java/algorithm/ModuloShardingTableAlgorithm.java * @auhtor jacktomcat * @create 2018-05-13 上午10:12 */ public class ModuloShardingTableAlgorithm implements PreciseShardingAlgorithm<Long> { @Override public String doSharding(final Collection<String> tableNames, final PreciseShardingValue<Long> shardingValue) { for (String each : tableNames) { if (each.endsWith(shardingValue.getValue() % 2 + "")) { return each; } } throw new UnsupportedOperationException(); } }
35.25
231
0.736575
2ef6ce3b713aff1d7e5fb35ee29222c167623750
3,918
/* * (c) Copyright 2016 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.tokens.auth; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.palantir.logsafe.Preconditions; import com.palantir.logsafe.SafeArg; import com.palantir.logsafe.exceptions.SafeIllegalArgumentException; import java.security.MessageDigest; import java.util.BitSet; import org.immutables.value.Value; /** Value class representing an authentication bearer token. */ @Value.Immutable @ImmutablesStyle public abstract class BearerToken { private static final String VALIDATION_PATTERN_STRING = "^[A-Za-z0-9\\-\\._~\\+/]+=*$"; private static final BitSet allowedCharacters = new BitSet(); static { allowedCharacters.set('A', 'Z' + 1); allowedCharacters.set('a', 'z' + 1); allowedCharacters.set('0', '9' + 1); allowedCharacters.set('-'); allowedCharacters.set('.'); allowedCharacters.set('_'); allowedCharacters.set('~'); allowedCharacters.set('+'); allowedCharacters.set('/'); } @Value.Parameter @JsonValue public abstract String getToken(); // We use a hand-written getBytes() implementation for performance reasons. // Note that we don't need to worry about the character set (e.g., UTF-8) because // the set of allowable characters are single bytes. @Value.Derived @SuppressWarnings("DesignForExtension") byte[] getTokenAsBytes() { String token = getToken(); byte[] result = new byte[token.length()]; for (int i = 0; i < result.length; i++) { result[i] = (byte) token.charAt(i); } return result; } @JsonCreator public static BearerToken valueOf(String token) { Preconditions.checkArgument(token != null, "BearerToken cannot be null"); Preconditions.checkArgument(!token.isEmpty(), "BearerToken cannot be empty"); if (!isValidBearerToken(token)) { throw new SafeIllegalArgumentException( "BearerToken must match pattern", SafeArg.of("validationPattern", VALIDATION_PATTERN_STRING)); } return ImmutableBearerToken.of(token); } // Optimized implementation of the regular expression VALIDATION_PATTERN_STRING private static boolean isValidBearerToken(String token) { int length = token.length(); int cursor = 0; for (; cursor < length; cursor++) { if (!allowedCharacters.get(token.charAt(cursor))) { break; } } // Need at least one valid character if (cursor == 0) { return false; } // Only trailing '=' is allowed after valid characters for (; cursor < length; cursor++) { if (token.charAt(cursor) != '=') { return false; } } return true; } @Override public final String toString() { return getToken(); } @Override public final boolean equals(Object other) { return other instanceof BearerToken && MessageDigest.isEqual(((BearerToken) other).getTokenAsBytes(), getTokenAsBytes()); } @Override public final int hashCode() { return getToken().hashCode(); } }
32.92437
114
0.647014
26d32f1b2f41abdc951436bd4be41e135c3cf34f
2,808
package de.lsem.word; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import de.lsem.matrix.MaximumObjectComparer; import de.lsem.matrix.ObjectComparer; import de.lsem.matrix.StoreObjectComparer; import de.lsem.word.similarity.LevenshteinComparer; import de.lsem.word.similarity.LinWordNetComparer; import de.lsem.word.similarity.WordNetStemComparer; /* * Copyright (c) 2013 Christopher Klinkmüller * * This software is released under the terms of the * MIT license. See http://opensource.org/licenses/MIT * for more information. */ /** * * @author Christopher Klinkmüller * */ public class SimilarityTest { private String[][] wordpairs; private LevenshteinComparer levenshteinComparer; private WordNetStemComparer levenshteinStemComparer; private LinWordNetComparer linComparer; private WordNetStemComparer linStemComparer; private MaximumObjectComparer<String> maximumComparer; private WordNetStemComparer maximumStemComparer; private StoreObjectComparer<String> storeLevenshteinComparer; @Before public void setup() { this.levenshteinComparer = new LevenshteinComparer(); this.levenshteinStemComparer = new WordNetStemComparer(this.levenshteinComparer); this.linComparer = new LinWordNetComparer(); this.linStemComparer = new WordNetStemComparer(this.linComparer); this.maximumComparer = new MaximumObjectComparer<String>(this.levenshteinComparer, this.linComparer); this.maximumStemComparer = new WordNetStemComparer(this.maximumComparer); this.storeLevenshteinComparer = new StoreObjectComparer<String>(this.levenshteinComparer); this.wordpairs = new String[][]{{"document", "certificate"}, {"run", "go"}, {"walk", "talk"}, {"university", "universities"}}; } @Test public void testLevenshteinComparer() { this.testObjectComparer(this.levenshteinComparer); } @Test public void testLevenshteinStemComparer() { this.testObjectComparer(this.levenshteinStemComparer); } @Test public void testLinWordNetComparer() { this.testObjectComparer(this.linComparer); } @Test public void testLinWordNetStemComparer() { this.testObjectComparer(this.linStemComparer); } @Test public void testMaximumComparer() { this.testObjectComparer(this.maximumComparer); } @Test public void testMaximumStemComparer() { this.testObjectComparer(this.maximumStemComparer); } @Test public void testStoreObjectComparer() { for (int a = 0; a <= 5; a++) { this.testObjectComparer(this.storeLevenshteinComparer); } } private void testObjectComparer(ObjectComparer<String> comparer) { for (int a = 0; a < wordpairs.length; a++) { double value = this.levenshteinComparer.compare(wordpairs[a][0], wordpairs[a][1]); boolean test = value >= 0 && value <= 1; assertTrue(test); } } }
28.653061
128
0.766382
228c0a7740be71dfd2a9366414da561fbb15b577
314
package torukobyte.hrms.emailValidator; import org.springframework.stereotype.Service; import torukobyte.hrms.entities.concretes.User; @Service public class EmailValidatorManager { public String emailValidator(User user) { return "Doğrulama kodu " + user.getEmail() + " adresine gönderildi"; } }
26.166667
76
0.761146
47dd3513c88461d39c9416c977434471660671d2
3,076
import java.io.*; import java.util.Arrays; import java.util.*; class Solution{ // to sort the strings in lexicographically non-decreasing order. public void sortLexo(String[] arr){ // CASE_INSENSITIVE_ORDER: would do case insensitive sort Arrays.sort(arr, String.CASE_INSENSITIVE_ORDER); for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); } } // to sort the strings in lexicographically non-increasing order. public void sortLexoreverse(String[] arr){ // Collections.reverseOrder(): reverse the order of sorting Arrays.sort(arr, Collections.reverseOrder()); for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); } } //Helper method To count the distinct character in a string public int countDistinct(String s) { // Initialize map Map<Character, Integer> m = new HashMap<>(); for(int i = 0; i < s.length(); i++) { // Count distinct characters : Create a hashmap for the given string // if(the map already contains the character key then increment its value by 1) if (m.containsKey(s.charAt(i))) { m.put(s.charAt(i), m.get(s.charAt(i)) + 1); } // else( create a new key-value pair inside hashmap and initialize value to 1) else { m.put(s.charAt(i), 1); } } // size of hashmap would give the number of distinct character in the string ( Keys are always unique) return m.size(); } // to sort the strings in non-decreasing order of the number of distinct characters present in them. If two strings have the same // number of distinct characters present in them, then the lexicographically smaller string should appear first. public void sort_by_number_of_distinct_characters(String[] arr){ // Using a new Comparator: we can implement our own condition for sorting. Arrays.sort(arr, new Comparator<String>() { public int compare(String a, String b) { if (countDistinct(a) == countDistinct(b)) { // Check if size of string 1 // is same as string 2 then // return false because s1 should // not be placed before s2 return (b.length() - a.length()); } else { return (countDistinct(a) - countDistinct(b)); } } }); // Printing the output for(int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } // to sort the strings in non-decreasing order of their lengths. // If two strings have the same length, then the lexicographically smaller string should appear first. public void sort_by_length(String[] s){ int n = s.length; for (int i=1 ;i<n; i++) { String temp = s[i]; // Insert s[j] at its correct position int j = i - 1; while (j >= 0 && temp.length() < s[j].length()) { s[j+1] = s[j]; j--; } s[j+1] = temp; } // Printing the output. for (int i=0; i<n; i++) System.out.print(s[i]+" "); } }
29.864078
130
0.602081
063b3146122401c4153c5981db659bfaa200d445
1,840
/** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * 12.10.2011 by frentix GmbH, http://www.frentix.com * <p> */ package org.olat.modules.vitero.ui; import java.util.Date; import java.util.Iterator; import java.util.List; import org.olat.modules.vitero.model.ViteroBooking; /** * * Description:<br> * * <P> * Initial Date: 11 oct. 2011 <br> * * @author srosse, [email protected], http://www.frentix.com */ public class FilterBookings { public static void filterMyFutureBookings(final List<ViteroBooking> bookings, final List<ViteroBooking> signedInBookings) { //only the bookings in the future Date now = new Date(); for(Iterator<ViteroBooking> it=bookings.iterator(); it.hasNext(); ) { ViteroBooking booking = it.next(); Date end = booking.getEnd(); if(end.before(now)) { it.remove(); } else if(!booking.isAutoSignIn()) { boolean in = false; for(ViteroBooking signedInBooking:signedInBookings) { if(signedInBooking.getBookingId() == booking.getBookingId()) { in = true;//already in } } if(!in) { it.remove(); } } } } }
29.677419
124
0.68587
950f047a8d0c3bad0444a87188a22d45e6b79e72
9,263
/******************************************************************************* * Copyright (c) 2015 by dennis Corporation all right reserved. * 2015年7月7日 * *******************************************************************************/ package com.lelts.fragment.classroom; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.example.hello.R; import com.lels.bean.AnswerInfo; import com.lels.bean.ExamAnswerListInfo; import com.lels.bean.LodDialogClass; import com.lels.bean.StartAnswertestInfo; import com.lels.constants.Constants; import com.lelts.activity.classroomconnection.adapter.StartAnswerTestAdapter; import com.lelts.activity.classroomconnection.adapter.StartAnswertTestReportcardAdapter; import com.lelts.activity.classroomconnection.adapter.WholeTestReportAdapter; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.RequestParams; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.http.client.HttpRequest.HttpMethod; import android.app.Fragment; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.RelativeLayout; /** * <pre> * 业务名: * 功能说明: * 编写日期: 2015年7月7日 * 作者: 于耀东 * * 历史记录 * 1、修改日期: * 修改人: * 修改内容: * </pre> */ public class ReportCardFm extends Fragment{ private View mview; private ListView mlistview; private Context context; private StartAnswertTestReportcardAdapter madapter; private WholeTestReportAdapter wholeadapter; private List<StartAnswertestInfo> mlist; private Bundle bun; private int choose; private SharedPreferences share, teacherinfo; private String ccId,paperId; private List<AnswerInfo> mSinglelist; private List<ExamAnswerListInfo> examAnswerList; //判断是否有数据 private RelativeLayout txt_nullreport; /* (non-Javadoc) * @see android.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub mview = inflater.inflate(R.layout.fragment_report_card, null); return mview; } /* (non-Javadoc) * @see android.app.Fragment#onActivityCreated(android.os.Bundle) */ @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); initview(); LodDialogClass.showCustomCircleProgressDialog(getActivity(), "", "加载中..."); System.out.println("choose<==========>"+choose); if(choose==1){ findWholeSubmit(); }else if(choose == 2) findSingleSubmitModeStudentExamMark(); } /** * 方法说明:初始化控件 * */ private void initview() { // TODO Auto-generated method stub context = getActivity(); mlistview = (ListView) getActivity().findViewById(R.id.listview_report_card); share =getActivity().getSharedPreferences("userinfo", getActivity().MODE_PRIVATE); teacherinfo =getActivity().getSharedPreferences("teacherinfo", getActivity().MODE_PRIVATE); paperId = teacherinfo.getString("paperId", ""); ccId = teacherinfo.getString("ccId", ""); choose = teacherinfo.getInt("choose", -1); txt_nullreport = (RelativeLayout) getActivity().findViewById(R.id.txt_nullreport); } /** * 方法说明:网络获取整套提交的(考试当中和考试结束后显示的)学生成绩单 * */ private void findWholeSubmit() { // TODO Auto-generated method stub RequestParams params = new RequestParams(); params.addHeader("Authentication", share.getString("Token", "")); HttpUtils utils = new HttpUtils(); System.out.println("ccId========" + teacherinfo.getString("ccId", "") + "==========paperId=====" + paperId); utils.send(HttpMethod.GET, Constants.URL_findWholeSubmitModeStudentExamMark + "?ccId=" + ccId+"&paperId="+paperId, params, // + "?ccId=29908&paperId=9751", params, new RequestCallBack<String>() { @Override public void onFailure(HttpException arg0, String arg1) { // TODO Auto-generated method stub LodDialogClass.closeCustomCircleProgressDialog(); } @Override public void onSuccess(ResponseInfo<String> arg0) { // TODO Auto-generated method stub String result = arg0.result; try { JSONObject obj = new JSONObject(result); if (obj.getString("Data").endsWith("[]")) { System.out.println("无数据========"); txt_nullreport.setVisibility(View.VISIBLE); mlistview.setVisibility(View.GONE); }else{ txt_nullreport.setVisibility(View.GONE); mlistview.setVisibility(View.VISIBLE); } JSONArray data = obj.getJSONArray("Data"); mlist = new ArrayList<StartAnswertestInfo>(); for (int i = 0; i < data.length(); i++) { JSONObject obj_data = data.getJSONObject(i); StartAnswertestInfo info = new StartAnswertestInfo(); info.setAnswer(obj_data.getString("Accuracy")); info.setCode(obj_data.getString("sCode")); info.setName(obj_data.getString("sName")); info.setTime(obj_data.getString("CostTime")); info.setUrl(obj_data.getString("IconUrl")); info.setSex(obj_data.getString("nGender")); info.setCountdown(obj_data.getString("TargetDateDiff")); //新加数据 info.setsStudentId(obj_data.getString("sStudentId")); mlist.add(info); } madapter = new StartAnswertTestReportcardAdapter(context, mlist); mlistview.setAdapter(madapter); LodDialogClass.closeCustomCircleProgressDialog(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out .println("findWholeSubmit=====================" + result); } }); } /** * 方法说明:单题提交的(考试当中(心跳)和考试结束后显示的)学生成绩单 * */ private void findSingleSubmitModeStudentExamMark() { // TODO Auto-generated method stub RequestParams params = new RequestParams(); params.addHeader("Authentication", share.getString("Token", "")); HttpUtils utils = new HttpUtils(); System.out.println("ccId========" + teacherinfo.getString("ccId", "") + "==========paperId=====" + paperId); utils.send(HttpMethod.GET, Constants.URL_findSingleSubmitModeStudentExamMark + "?ccId=" + teacherinfo.getString("ccId", "")+"&paperId="+paperId, params, // + "?ccId=29908&paperId=9751", params, new RequestCallBack<String>() { @Override public void onFailure(HttpException arg0, String arg1) { // TODO Auto-generated method stub LodDialogClass.closeCustomCircleProgressDialog(); } @Override public void onSuccess(ResponseInfo<String> arg0) { // TODO Auto-generated method stub String result = arg0.result; try { JSONObject obj = new JSONObject(result); if (obj.getString("Data").equals("[]")) { System.out.println("无数据========"); txt_nullreport.setVisibility(View.VISIBLE); mlistview.setVisibility(View.GONE); }else{ txt_nullreport.setVisibility(View.GONE); mlistview.setVisibility(View.VISIBLE); } JSONArray data = obj.getJSONArray("Data"); mSinglelist = new ArrayList<AnswerInfo>(); for (int i = 0; i < data.length(); i++) { JSONObject obj_data = data.getJSONObject(i); String sName = obj_data.getString("sName"); int nGender = obj_data.getInt("nGender"); String CostTime = obj_data.getString("CostTime"); String sCode = obj_data.getString("sCode"); String IconUrl = obj_data.getString("IconUrl"); JSONArray exam = obj_data.getJSONArray("examAnswerList"); examAnswerList = new ArrayList<ExamAnswerListInfo>(); for (int j = 0; j < exam.length(); j++) { JSONObject exam_data = exam.getJSONObject(j); String QNumber = exam_data.getString("QNumber"); // "AnswerContent": "学生答案(当RightCount-ScoreCount<0,答案颜色是红色,否则是绿色)", String AnswerContent = exam_data.getString("AnswerContent"); int RightCount = exam_data.getInt("RightCount"); int ScoreCount = exam_data.getInt("ScoreCount"); ExamAnswerListInfo exam_info = new ExamAnswerListInfo(QNumber, AnswerContent, RightCount, ScoreCount); examAnswerList.add(exam_info); } AnswerInfo info = new AnswerInfo(sName,nGender,IconUrl,CostTime,sCode,examAnswerList); mSinglelist.add(info); System.out.println("mSinglelist====="+mSinglelist.toString()); } wholeadapter = new WholeTestReportAdapter(context, mSinglelist); mlistview.setAdapter(wholeadapter); LodDialogClass.closeCustomCircleProgressDialog(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out .println("findWholeSubmit=====================" + result); } }); } }
33.930403
114
0.67354
0fcf651186932ad7c983ce0f36dc879aad883215
4,875
package io.weblith.core.scopes; import static javax.ws.rs.core.Cookie.DEFAULT_VERSION; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import javax.ws.rs.WebApplicationException; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.NewCookie; import io.weblith.core.config.CookieConfig; public class CookieBuilder { private final static String KEY_VALUE_SEP = "="; private final static String ENTRY_SEP = "&"; private final CookieConfig config; private final String contextPath; public CookieBuilder(CookieConfig config, String contextPath) { this.config = config; this.contextPath = contextPath; } // TODO Reuse Cipher as in PersistentLoginManager ?? // private final BasicTextEncryptor textEncryptor; // if (this.secretKey.isPresent()) { // this.textEncryptor = new BasicTextEncryptor(); // this.textEncryptor.setPassword(this.secretKey.get()); // } else { // logger.warn("No secret key configured for cookie encryption ; therefore session cookie will not be encrypted"); // this.textEncryptor = null; // } public NewCookie remove(String name) { return new NewCookie(getName(name), "", getPath(), getDomain(), DEFAULT_VERSION, null, 0, null, false, false); } public NewCookie build(String name, String value, int maxAge) { return new NewCookie(getName(name), value, getPath(), getDomain(), DEFAULT_VERSION, null, maxAge, null, config.secure, config.httpsOnly); } public NewCookie build(String name, String value, int maxAge, Date expiry) { return new NewCookie(getName(name), value, getPath(), getDomain(), DEFAULT_VERSION, null, maxAge, expiry, config.secure, config.httpsOnly); } private String getName(String suffix) { Objects.requireNonNull(suffix, "Missing cookie name"); return this.config.prefix.map(p -> p + suffix).orElse(suffix); } private String getPath() { return this.config.path.orElse(contextPath); } private String getDomain() { return this.config.domain.orElse(null); } public static Map<String, String> decodeMap(String value) { Map<String, String> results = new HashMap<String, String>(); if (value != null && !value.isBlank()) { for (String entry : value.split(ENTRY_SEP)) { String[] keyValue = entry.split(KEY_VALUE_SEP); if (keyValue.length == 2) { results.put(decode(keyValue[0]), decode(keyValue[1])); } } } return results; } public static String decode(String value) { return URLDecoder.decode(value, StandardCharsets.UTF_8); } public static String encodeMap(Map<String, String> map) { if (map.isEmpty()) { return ""; } return map.entrySet() .stream() .map(e -> encode(e.getKey()) + "=" + encode(e.getValue())) .collect(Collectors.joining("&")); } public static String encode(String value) { return URLEncoder.encode(value, StandardCharsets.UTF_8); } public static String encryptMap(Map<String, String> map, String secret) { if (secret.isBlank()) { return encodeMap(map); } else { try { // return this.textEncryptor.encrypt(this.encode(map)); return encodeMap(map); } catch (Exception e) { throw new WebApplicationException(e); } } } public static Map<String, String> decryptMap(String value, String secret) { if (secret.isBlank()) { return decodeMap(value); } else { // return this.decode(this.textEncryptor.decrypt(value)); return decodeMap(value); } } /** * Constant time for same length String comparison, to prevent timing attacks */ public static boolean safeEquals(String a, String b) { if (a.length() != b.length()) { return false; } else { char equal = 0; for (int i = 0; i < a.length(); i++) { equal |= a.charAt(i) ^ b.charAt(i); } return equal == 0; } } public static void save(ContainerResponseContext responseContext, NewCookie cookie) { // Not working... responseContext.getCookies().put(cookie.getName(), cookie); responseContext.getHeaders().add(HttpHeaders.SET_COOKIE, cookie); } }
32.718121
129
0.610667
881acee0ac8e887cd554b3ae83b7cb70c3b0d238
2,646
/* * Licensed to the University Corporation for Advanced Internet Development, * Inc. (UCAID) under one or more contributor license agreements. See the * NOTICE file distributed with this work for additional information regarding * copyright ownership. The UCAID 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.opensaml.samlext.samlec.impl; import org.opensaml.common.BaseSAMLObjectProviderTestCase; import org.opensaml.samlext.samlec.GeneratedKey; /** * Tests {@link GeneratedKeyImpl} */ public class GeneratedKeyTest extends BaseSAMLObjectProviderTestCase { private String expectedValue; private String expectedSOAP11Actor; private Boolean expectedSOAP11MustUnderstand; /** Constructor */ public GeneratedKeyTest() { super(); singleElementFile = "/data/org/opensaml/samlext/samlec/impl/GeneratedKey.xml"; } /** {@inheritDoc} */ protected void setUp() throws Exception { super.setUp(); expectedValue = "AGeneratedKey"; expectedSOAP11Actor = "https://soap11actor.example.org"; expectedSOAP11MustUnderstand = true; } /** {@inheritDoc} */ public void testSingleElementMarshall() { GeneratedKeyBuilder builder = (GeneratedKeyBuilder) builderFactory.getBuilder(GeneratedKey.DEFAULT_ELEMENT_NAME); GeneratedKey key = builder.buildObject(); key.setSOAP11Actor(expectedSOAP11Actor); key.setSOAP11MustUnderstand(expectedSOAP11MustUnderstand); key.setValue(expectedValue); assertEquals(expectedDOM, key); } /** {@inheritDoc} */ public void testSingleElementUnmarshall() { GeneratedKey key = (GeneratedKey) unmarshallElement(singleElementFile); assertNotNull(key); assertEquals(expectedValue, key.getValue()); assertEquals("SOAP mustUnderstand had unxpected value", expectedSOAP11MustUnderstand, key.isSOAP11MustUnderstand()); assertEquals("SOAP actor had unxpected value", expectedSOAP11Actor, key.getSOAP11Actor()); } }
37.8
125
0.707105
32c5dcbf50c0ed60c8f165ba83605dd5a1d55db9
417
package com.appnerds.hrishikesh.firechat.global.database; import com.appnerds.hrishikesh.firechat.global.data_model.Chat; import com.appnerds.hrishikesh.firechat.global.data_model.Message; import rx.Observable; /** * Created by marco on 08/08/16. */ public interface GlobalDatabase { Observable<Message> observeAddMessage(); Observable<Chat> observeChat(); void sendMessage(Message message); }
18.954545
66
0.767386
187be0eddc69fb76a36574cd50b521e09a157b53
17,072
package br.com.letscode.web.rest; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import br.com.letscode.IntegrationTest; import br.com.letscode.domain.Play; import br.com.letscode.domain.Player; import br.com.letscode.repository.PlayRepository; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicLong; import javax.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; /** * Integration tests for the {@link PlayResource} REST controller. */ @IntegrationTest @AutoConfigureMockMvc @WithMockUser class PlayResourceIT { private static final Double DEFAULT_SCORE = 1.0; private static final Double UPDATED_SCORE = 1.0; private static final Instant DEFAULT_START = Instant.ofEpochMilli(0L); private static final Instant UPDATED_START = Instant.now().truncatedTo(ChronoUnit.MILLIS); private static final Instant DEFAULT_END = Instant.ofEpochMilli(0L); private static final Instant UPDATED_END = Instant.now().truncatedTo(ChronoUnit.MILLIS); private static final Integer DEFAULT_ERRORS = 1; private static final Integer UPDATED_ERRORS = 2; private static final String ENTITY_API_URL = "/api/plays"; private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; private static Random random = new Random(); private static AtomicLong count = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); @Autowired private PlayRepository playRepository; @Autowired private EntityManager em; @Autowired private MockMvc restPlayMockMvc; private Play play; /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Play createEntity(EntityManager em) { Play play = new Play().score(DEFAULT_SCORE).start(DEFAULT_START).end(DEFAULT_END).errors(DEFAULT_ERRORS); // Add required entity Player player; if (TestUtil.findAll(em, Player.class).isEmpty()) { player = PlayerResourceIT.createEntity(em); em.persist(player); em.flush(); } else { player = TestUtil.findAll(em, Player.class).get(0); } play.setPlayer(player); return play; } /** * Create an updated entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Play createUpdatedEntity(EntityManager em) { Play play = new Play().score(UPDATED_SCORE).start(UPDATED_START).end(UPDATED_END).errors(UPDATED_ERRORS); return play; } @BeforeEach public void initTest() { play = createEntity(em); } @Test @Transactional void startPlay() throws Exception { int databaseSizeBeforeCreate = playRepository.findAll().size(); // Create the Play restPlayMockMvc .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(play))) .andExpect(status().isCreated()); List<Play> playList = playRepository.findAll(); assertThat(playList).hasSize(databaseSizeBeforeCreate + 1); Play testPlay = playList.get(playList.size() - 1); assertThat(testPlay.getScore()).isEqualTo(DEFAULT_SCORE); assertThat(testPlay.getStart()).isEqualTo(DEFAULT_START); assertThat(testPlay.getEnd()).isEqualTo(DEFAULT_END); assertThat(testPlay.getErrors()).isEqualTo(DEFAULT_ERRORS); } @Test @Transactional void createPlayWithExistingId() throws Exception { // Create the Play with an existing ID play.setId( "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY0NTY4MTMwNn0.B0dqVTD53wa4qjDoZwc1SQK4ndrmDMaS7nGOl-dzTLD6sbxC9BAF3X-0_2O_pcsY_jqZwDKKkedUBL7shEC9hA" ); int databaseSizeBeforeCreate = playRepository.findAll().size(); // An entity with an existing ID cannot be created, so this API call must fail restPlayMockMvc .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(play))) .andExpect(status().isBadRequest()); // Validate the Play in the database List<Play> playList = playRepository.findAll(); assertThat(playList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional void getAllPlays() throws Exception { // Initialize the database playRepository.saveAndFlush(play); // Get all the playList restPlayMockMvc .perform(get(ENTITY_API_URL + "?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(play.getId()))) .andExpect(jsonPath("$.[*].score").value(hasItem(DEFAULT_SCORE))) .andExpect(jsonPath("$.[*].start").value(hasItem(DEFAULT_START.toString()))) .andExpect(jsonPath("$.[*].end").value(hasItem(DEFAULT_END.toString()))) .andExpect(jsonPath("$.[*].errors").value(hasItem(DEFAULT_ERRORS))); } @Test @Transactional void getPlay() throws Exception { // Initialize the database playRepository.saveAndFlush(play); // Get the play restPlayMockMvc .perform(get(ENTITY_API_URL_ID, play.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.id").value(play.getId())) .andExpect(jsonPath("$.score").value(DEFAULT_SCORE)) .andExpect(jsonPath("$.start").value(DEFAULT_START.toString())) .andExpect(jsonPath("$.end").value(DEFAULT_END.toString())) .andExpect(jsonPath("$.errors").value(DEFAULT_ERRORS)); } @Test @Transactional void getNonExistingPlay() throws Exception { // Get the play restPlayMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); } @Test @Transactional void putNewPlay() throws Exception { // Initialize the database playRepository.saveAndFlush(play); int databaseSizeBeforeUpdate = playRepository.findAll().size(); // Update the play Play updatedPlay = playRepository.findById(play.getId()).get(); // Disconnect from session so that the updates on updatedPlay are not directly saved in db em.detach(updatedPlay); updatedPlay.score(UPDATED_SCORE).start(UPDATED_START).end(UPDATED_END).errors(UPDATED_ERRORS); restPlayMockMvc .perform( put(ENTITY_API_URL_ID, updatedPlay.getId()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(updatedPlay)) ) .andExpect(status().isOk()); // Validate the Play in the database List<Play> playList = playRepository.findAll(); assertThat(playList).hasSize(databaseSizeBeforeUpdate); Play testPlay = playList.get(playList.size() - 1); assertThat(testPlay.getScore()).isEqualTo(UPDATED_SCORE); assertThat(testPlay.getStart()).isEqualTo(UPDATED_START); assertThat(testPlay.getEnd()).isEqualTo(UPDATED_END); assertThat(testPlay.getErrors()).isEqualTo(UPDATED_ERRORS); } @Test @Transactional void putNonExistingPlay() throws Exception { int databaseSizeBeforeUpdate = playRepository.findAll().size(); play.setId( "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY0NTY4MTMwNn0.B0dqVTD53wa4qjDoZwc1SQK4ndrmDMaS7nGOl-dzTLD6sbxC9BAF3X-0_2O_pcsY_jqZwDKKkedUBL7shEC9hA" ); // If the entity doesn't have an ID, it will throw BadRequestAlertException restPlayMockMvc .perform( put(ENTITY_API_URL_ID, play.getId()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(play)) ) .andExpect(status().isBadRequest()); // Validate the Play in the database List<Play> playList = playRepository.findAll(); assertThat(playList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void putWithIdMismatchPlay() throws Exception { int databaseSizeBeforeUpdate = playRepository.findAll().size(); play.setId( "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY0NTY4MTMwNn0.B0dqVTD53wa4qjDoZwc1SQK4ndrmDMaS7nGOl-dzTLD6sbxC9BAF3X-0_2O_pcsY_jqZwDKKkedUBL7shEC9hA" ); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restPlayMockMvc .perform( put(ENTITY_API_URL_ID, count.incrementAndGet()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(play)) ) .andExpect(status().isBadRequest()); // Validate the Play in the database List<Play> playList = playRepository.findAll(); assertThat(playList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void putWithMissingIdPathParamPlay() throws Exception { int databaseSizeBeforeUpdate = playRepository.findAll().size(); play.setId( "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY0NTY4MTMwNn0.B0dqVTD53wa4qjDoZwc1SQK4ndrmDMaS7nGOl-dzTLD6sbxC9BAF3X-0_2O_pcsY_jqZwDKKkedUBL7shEC9hA" ); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restPlayMockMvc .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(play))) .andExpect(status().isMethodNotAllowed()); // Validate the Play in the database List<Play> playList = playRepository.findAll(); assertThat(playList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void partialUpdatePlayWithPatch() throws Exception { // Initialize the database playRepository.saveAndFlush(play); int databaseSizeBeforeUpdate = playRepository.findAll().size(); // Update the play using partial update Play partialUpdatedPlay = new Play(); partialUpdatedPlay.setId(play.getId()); partialUpdatedPlay.start(UPDATED_START); restPlayMockMvc .perform( patch(ENTITY_API_URL_ID, partialUpdatedPlay.getId()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(partialUpdatedPlay)) ) .andExpect(status().isOk()); // Validate the Play in the database List<Play> playList = playRepository.findAll(); assertThat(playList).hasSize(databaseSizeBeforeUpdate); Play testPlay = playList.get(playList.size() - 1); assertThat(testPlay.getScore()).isEqualTo(DEFAULT_SCORE); assertThat(testPlay.getStart()).isEqualTo(UPDATED_START); assertThat(testPlay.getEnd()).isEqualTo(DEFAULT_END); assertThat(testPlay.getErrors()).isEqualTo(DEFAULT_ERRORS); } @Test @Transactional void fullUpdatePlayWithPatch() throws Exception { // Initialize the database playRepository.saveAndFlush(play); int databaseSizeBeforeUpdate = playRepository.findAll().size(); // Update the play using partial update Play partialUpdatedPlay = new Play(); partialUpdatedPlay.setId(play.getId()); partialUpdatedPlay.score(UPDATED_SCORE).start(UPDATED_START).end(UPDATED_END).errors(UPDATED_ERRORS); restPlayMockMvc .perform( patch(ENTITY_API_URL_ID, partialUpdatedPlay.getId()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(partialUpdatedPlay)) ) .andExpect(status().isOk()); // Validate the Play in the database List<Play> playList = playRepository.findAll(); assertThat(playList).hasSize(databaseSizeBeforeUpdate); Play testPlay = playList.get(playList.size() - 1); assertThat(testPlay.getScore()).isEqualTo(UPDATED_SCORE); assertThat(testPlay.getStart()).isEqualTo(UPDATED_START); assertThat(testPlay.getEnd()).isEqualTo(UPDATED_END); assertThat(testPlay.getErrors()).isEqualTo(UPDATED_ERRORS); } @Test @Transactional void patchNonExistingPlay() throws Exception { int databaseSizeBeforeUpdate = playRepository.findAll().size(); play.setId( "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY0NTY4MTMwNn0.B0dqVTD53wa4qjDoZwc1SQK4ndrmDMaS7nGOl-dzTLD6sbxC9BAF3X-0_2O_pcsY_jqZwDKKkedUBL7shEC9hA" ); // If the entity doesn't have an ID, it will throw BadRequestAlertException restPlayMockMvc .perform( patch(ENTITY_API_URL_ID, play.getId()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(play)) ) .andExpect(status().isBadRequest()); // Validate the Play in the database List<Play> playList = playRepository.findAll(); assertThat(playList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void patchWithIdMismatchPlay() throws Exception { int databaseSizeBeforeUpdate = playRepository.findAll().size(); play.setId( "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY0NTY4MTMwNn0.B0dqVTD53wa4qjDoZwc1SQK4ndrmDMaS7nGOl-dzTLD6sbxC9BAF3X-0_2O_pcsY_jqZwDKKkedUBL7shEC9hA" ); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restPlayMockMvc .perform( patch(ENTITY_API_URL_ID, count.incrementAndGet()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(play)) ) .andExpect(status().isBadRequest()); // Validate the Play in the database List<Play> playList = playRepository.findAll(); assertThat(playList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void patchWithMissingIdPathParamPlay() throws Exception { int databaseSizeBeforeUpdate = playRepository.findAll().size(); play.setId( "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY0NTY4MTMwNn0.B0dqVTD53wa4qjDoZwc1SQK4ndrmDMaS7nGOl-dzTLD6sbxC9BAF3X-0_2O_pcsY_jqZwDKKkedUBL7shEC9hA" ); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restPlayMockMvc .perform(patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(TestUtil.convertObjectToJsonBytes(play))) .andExpect(status().isMethodNotAllowed()); // Validate the Play in the database List<Play> playList = playRepository.findAll(); assertThat(playList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void deletePlay() throws Exception { // Initialize the database playRepository.saveAndFlush(play); int databaseSizeBeforeDelete = playRepository.findAll().size(); // Delete the play restPlayMockMvc .perform(delete(ENTITY_API_URL_ID, play.getId()).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); // Validate the database contains one less item List<Play> playList = playRepository.findAll(); assertThat(playList).hasSize(databaseSizeBeforeDelete - 1); } }
40.551069
205
0.68586
46393b2bcc02a660e5e632a3a41fcf39dff0d44c
1,202
/* * Copyright (c) 2014-2018 T-Systems Multimedia Solutions GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tsystems.mms.apm.performancesignature.dynatrace.rest.json.api; import de.tsystems.mms.apm.performancesignature.dynatrace.rest.json.model.Result; import retrofit2.Call; import retrofit2.http.GET; import static de.tsystems.mms.apm.performancesignature.dynatrace.rest.json.ApiClient.API_SUFFIX; public interface ServerManagementApi { /** * Request the version of the AppMon Server * Get the version of the running server. * * @return Call&lt;XmlResult&gt; */ @GET(API_SUFFIX + "server/version") Call<Result> getVersion(); }
33.388889
96
0.741265
ff5c167e77fa29f87871d1cfa346c7c8a10118c4
35,723
/* The MIT License (MIT) Copyright (c) 2015, Hans-Georg Becker, http://orcid.org/0000-0003-0432-294X Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package de.tu_dortmund.ub.service.catalogplus; import com.fasterxml.jackson.databind.ObjectMapper; import de.tu_dortmund.ub.service.catalogplus.model.RequestError; import de.tu_dortmund.ub.service.catalogplus.rds.RDSException; import de.tu_dortmund.ub.service.catalogplus.rds.ResourceDiscoveryService; import de.tu_dortmund.ub.service.catalogplus.vcs.VirtualClassificationSystem; import de.tu_dortmund.ub.util.impl.Lookup; import de.tu_dortmund.ub.util.impl.Mailer; import de.tu_dortmund.ub.util.output.ObjectToHtmlTransformation; import de.tu_dortmund.ub.util.output.TransformationException; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import javax.mail.MessagingException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.*; import java.util.Enumeration; import java.util.Properties; public class CatalogPlusEndpoint extends HttpServlet { // Configuration private Properties config = new Properties(); private Logger logger = Logger.getLogger(CatalogPlusEndpoint.class.getName()); private String format; private String language; private boolean isTUintern; private boolean isUBintern; public CatalogPlusEndpoint() throws IOException { this("conf/api-test.properties"); } public CatalogPlusEndpoint(String conffile) throws IOException { // Init properties try { InputStream inputStream = new FileInputStream(conffile); try { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); try { this.config.load(reader); } finally { reader.close(); } } finally { inputStream.close(); } } catch (IOException e) { System.out.println("FATAL ERROR: Die Datei '" + conffile + "' konnte nicht geöffnet werden!"); } // init logger PropertyConfigurator.configure(this.config.getProperty("service.log4j-conf")); this.logger.info("[" + this.config.getProperty("service.name") + "] " + "Starting 'CatalogPlusEndpoint' ..."); this.logger.info("[" + this.config.getProperty("service.name") + "] " + "conf-file = " + conffile); this.logger.info("[" + this.config.getProperty("service.name") + "] " + "log4j-conf-file = " + this.config.getProperty("service.log4j-conf")); } public void doOptions(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { httpServletResponse.setHeader("Access-Control-Allow-Methods", config.getProperty("Access-Control-Allow-Methods")); httpServletResponse.addHeader("Access-Control-Allow-Headers", config.getProperty("Access-Control-Allow-Headers")); httpServletResponse.setHeader("Accept", config.getProperty("Accept")); httpServletResponse.setHeader("Access-Control-Allow-Origin", config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.getWriter().println(); } public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); this.logger.debug("PathInfo = " + httpServletRequest.getPathInfo()); this.logger.debug("QueryString = " + httpServletRequest.getQueryString()); // analyse request path to define the service String path = httpServletRequest.getPathInfo(); String service = ""; if (path != null) { String[] params = path.substring(1, path.length()).split("/"); if (params.length == 1) { service = params[0]; } else if (path.startsWith("katalog/titel/")) { service = "api"; } } this.logger.debug("service = " + service); // analyse ip range String ips = httpServletRequest.getHeader("X-Forwarded-For"); this.isTUintern = this.analyseAccessRights(ips, config.getProperty("service.iprange.tu"), config.getProperty("service.iprange.tu.exceptions")); this.isUBintern = this.analyseAccessRights(ips, config.getProperty("service.iprange.ub"), config.getProperty("service.iprange.ub.exceptions")); this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Where is it from? " + httpServletRequest.getHeader("X-Forwarded-For") + ", " + isTUintern + ", " + isUBintern); // format this.format = "html"; if (httpServletRequest.getParameter("format") != null && !httpServletRequest.getParameter("format").equals("")) { this.format = httpServletRequest.getParameter("format"); } else { Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while ( headerNames.hasMoreElements() ) { String headerNameKey = headerNames.nextElement(); if (headerNameKey.equals("Accept")) { this.logger.debug("headerNameKey = " + httpServletRequest.getHeader( headerNameKey )); if (httpServletRequest.getHeader( headerNameKey ).contains("text/html")) { this.format = "html"; } else if (httpServletRequest.getHeader( headerNameKey ).contains("application/xml")) { this.format = "xml"; } else if (httpServletRequest.getHeader( headerNameKey ).contains("application/json")) { this.format = "json"; } } if (headerNameKey.equals("Accept-Language")) { this.language = httpServletRequest.getHeader( headerNameKey ); this.logger.debug("[" + config.getProperty("service.name") + "] " + "Accept-Language: " + this.language); } } } this.logger.info("format = " + this.format); // language if (this.language != null && this.language.startsWith("de")) { this.language = "de"; } else if (this.language != null && this.language.startsWith("en")) { this.language = "en"; } else if (httpServletRequest.getParameter("l") != null) { this.language = httpServletRequest.getParameter("l"); } else { this.language = "de"; } this.logger.info("language = " + this.language); // Debugging boolean debug = false; if (httpServletRequest.getParameter("debug") != null && httpServletRequest.getParameter("debug").equals("1")) { debug = true; } // is service valid? if (!service.equals("search") && !service.equals("typeahead") && !service.equals("getRecords") && !service.equals("api")) { RequestError requestError = new RequestError(); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription("The service '" + path + "' is not implemented."); requestError.setError("BAD REQUEST"); httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); this.sendRequestError(httpServletResponse, requestError); } else if (!service.equals("typeahead") && !this.format.equals("html") && !isUBintern) { RequestError requestError = new RequestError(); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription("You are not allowed to request results in '" + this.format + "'!"); requestError.setError("BAD REQUEST"); httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); this.sendRequestError(httpServletResponse, requestError); } else if (service.equals("typeahead") && !this.format.equals("json")) { RequestError requestError = new RequestError(); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription("Service 'typeahead' does not support format '" + this.format + "'!"); requestError.setError("BAD REQUEST"); httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); this.sendRequestError(httpServletResponse, requestError); } else { try { if (service.equals("search") || service.equals("getRecords") || service.equals("typeahead")) { // Query Properties requestParameter = this.handleRequestParameters(httpServletRequest); requestParameter.setProperty("lang", this.language); // Resource Discovery Service API if (Lookup.lookupAll(ResourceDiscoveryService.class).size() > 0) { ResourceDiscoveryService resourceDiscoveryService = Lookup.lookup(ResourceDiscoveryService.class); // init ResourceDiscoveryService resourceDiscoveryService.init(this.config); if (service.equals("search")) { if (requestParameter.getProperty("q").equals("") || requestParameter.getProperty("q").equals("*") || requestParameter.getProperty("q").equals("*:*") || (!requestParameter.getProperty("rows").equals("") && Integer.parseInt(requestParameter.getProperty("rows")) > 50) || (!requestParameter.getProperty("start").equals("") && Integer.parseInt(requestParameter.getProperty("start")) > 20)) { RequestError requestError = new RequestError(); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription("Malformed request!"); requestError.setError("BAD REQUEST"); httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); this.sendRequestError(httpServletResponse, requestError); } else { // Query try { if (this.format.equals("html")) { Properties renderParameters = new Properties(); renderParameters.setProperty("lang", this.language); renderParameters.setProperty("service", service); renderParameters.setProperty("isTUintern", Boolean.toString(this.isTUintern)); renderParameters.setProperty("isUBintern", Boolean.toString(this.isUBintern)); renderParameters.setProperty("debug", Boolean.toString(debug)); String mode = ""; if (httpServletRequest.getParameter("mode") != null) { mode = httpServletRequest.getParameter("mode"); } renderParameters.setProperty("mode", mode); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(resourceDiscoveryService.getSearchResultsAsHTML(requestParameter, renderParameters)); } if (this.format.equals("json")) { httpServletResponse.setContentType("application/json"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(resourceDiscoveryService.getSearchResultsAsJSON(requestParameter)); } if (this.format.equals("xml")) { httpServletResponse.setContentType("application/xml"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(resourceDiscoveryService.getSearchResultsAsXML(requestParameter)); } } catch (RDSException e) { this.logger.error("[" + this.config.getProperty("service.name") + "] Exception: " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " - " + e.getMessage()); RequestError requestError = new RequestError(); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(e.getMessage()); requestError.setError("SERVICE_UNAVAILABLE"); httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); this.sendRequestError(httpServletResponse, requestError); } } } else if (service.equals("getRecords")) { String institution_param = ""; if (httpServletRequest.getQueryString().contains("fq=Institution")) { for (String r : httpServletRequest.getParameterMap().keySet()) { if (r.equals("fq") && httpServletRequest.getParameter(r).startsWith("Institution")) { institution_param = "&fq=" + httpServletRequest.getParameter(r); break; } } this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "institution_param: " + institution_param); } try { if (this.format.equals("html")) { httpServletResponse.setContentType("text/html;charset=UTF-8"); Properties renderParameters = new Properties(); renderParameters.setProperty("lang", this.language); renderParameters.setProperty("service", service); renderParameters.setProperty("isTUintern", Boolean.toString(this.isTUintern)); renderParameters.setProperty("isUBintern", Boolean.toString(this.isUBintern)); renderParameters.setProperty("debug", Boolean.toString(debug)); renderParameters.setProperty("recordset", institution_param); String mode = ""; if (httpServletRequest.getParameter("mode") != null) { mode = httpServletRequest.getParameter("mode"); } renderParameters.setProperty("mode", mode); if (mode.equals("simplehit")) { renderParameters.setProperty("getRecordsBaseURL", httpServletRequest.getRequestURL().toString() + "?ids="); } if (mode.equals("embedded") || mode.equals("simplehit")) { httpServletResponse.setContentType("text/xml"); } httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(resourceDiscoveryService.getSearchResultsAsHTML(requestParameter, renderParameters)); } if (this.format.equals("json")) { httpServletResponse.setContentType("application/json"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(resourceDiscoveryService.getSearchResultsAsJSON(requestParameter)); } if (this.format.equals("xml")) { httpServletResponse.setContentType("application/xml"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(resourceDiscoveryService.getSearchResultsAsXML(requestParameter)); } } catch (RDSException e) { this.logger.error("[" + this.config.getProperty("service.name") + "] Exception: " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " - " + e.getMessage()); RequestError requestError = new RequestError(); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(e.getMessage()); requestError.setError("SERVICE_UNAVAILABLE"); httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); this.sendRequestError(httpServletResponse, requestError); } } else if (service.equals("typeahead")) { String prefix = ""; if (httpServletRequest.getParameter("q") != null) { prefix = httpServletRequest.getParameter("q"); } try { String json = resourceDiscoveryService.getSuggestions(prefix); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.setContentType("application/json;charset=utf-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(json); } catch (RDSException e) { this.logger.error("[" + this.config.getProperty("service.name") + "] Exception: " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " - " + e.getMessage()); RequestError requestError = new RequestError(); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(e.getMessage()); requestError.setError("SERVICE_UNAVAILABLE"); httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); this.sendRequestError(httpServletResponse, requestError); } } } else { this.logger.error("[" + this.config.getProperty("service.name") + "] Exception: " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " - No ResourceDiscoveryService configured"); RequestError requestError = new RequestError(); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription("Resource Discovery Service not configured!"); requestError.setError("SERVICE_UNAVAILABLE"); httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); this.sendRequestError(httpServletResponse, requestError); } } else { if (Lookup.lookupAll(VirtualClassificationSystem.class).size() > 0) { if (httpServletRequest.getParameter("class") != null && !httpServletRequest.getParameter("class").equals("")) { VirtualClassificationSystem virtualClassificationSystem = Lookup.lookup(VirtualClassificationSystem.class); // init VirtualClassificationSystem virtualClassificationSystem.init(this.config); if (this.format.equals("html")) { Properties renderParameters = new Properties(); renderParameters.setProperty("lang", this.language); renderParameters.setProperty("isTUintern", Boolean.toString(this.isTUintern)); renderParameters.setProperty("isUBintern", Boolean.toString(this.isUBintern)); renderParameters.setProperty("debug", Boolean.toString(debug)); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(virtualClassificationSystem.getClassAsHTML(httpServletRequest.getParameter("class"), renderParameters)); } if (this.format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(virtualClassificationSystem.getClassAsJSON(httpServletRequest.getParameter("class"))); } if (this.format.equals("xml")) { httpServletResponse.setContentType("application/xml;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(virtualClassificationSystem.getClassAsXML(httpServletRequest.getParameter("class"))); } } else { httpServletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Class parameter not valid!"); RequestError requestError = new RequestError(); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription("Class parameter not valid!"); requestError.setError("BAD_REQUEST"); httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); this.sendRequestError(httpServletResponse, requestError); } } else { this.logger.error("[" + this.config.getProperty("service.name") + "] Exception: " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " - No VirtualClassificationSystem configured"); RequestError requestError = new RequestError(); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription("Virtual Classification System not configured!"); requestError.setError("SERVICE_UNAVAILABLE"); httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); this.sendRequestError(httpServletResponse, requestError); } } } catch (Exception e) { this.logger.error("[" + this.config.getProperty("service.name") + "] Exception: " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " Service unavailable."); this.logger.error(e.getMessage(), e.getCause()); String stackTrace = ""; for (StackTraceElement stackTraceElement : e.getStackTrace()) { this.logger.error("\t" + stackTraceElement.toString()); stackTrace += stackTraceElement.toString() + "\n"; } httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Service unavailable."); RequestError requestError = new RequestError(); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription("Unexpected error in request: '" + httpServletRequest.getRequestURL() + "'!\n" + stackTrace); requestError.setError("SERVICE_UNAVAILABLE"); httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); this.sendRequestError(httpServletResponse, requestError); } } } private boolean analyseAccessRights(String ips, String iprange, String ipexceptions) { boolean allowed = false; try { if (ips != null) { String tmp[] = ips.split(", "); String ip = tmp[tmp.length - 1]; String[] ranges = iprange.split("\\|"); for (String range : ranges) { if (ip.matches(range)) { allowed = true; break; } } String[] exceptions = ipexceptions.split("\\|"); if (allowed) { for (String exception : exceptions) { if (ip.matches(exception)) { allowed = false; break; } } } } } catch (Exception e) { this.logger.error(e.getMessage(), e.getCause()); } return allowed; } private Properties handleRequestParameters(HttpServletRequest httpServletRequest) { String q = ""; if (httpServletRequest.getParameter("q") != null) { q = httpServletRequest.getParameter("q"); } String fq = ""; if (httpServletRequest.getParameterValues("fq") != null) { for (int i = 0; i < httpServletRequest.getParameterValues("fq").length; i++) { fq += httpServletRequest.getParameterValues("fq")[i]; if (i < httpServletRequest.getParameterValues("fq").length - 1) { fq += ";"; } } } String rq = ""; if (httpServletRequest.getParameterValues("rq") != null) { for (int i = 0; i < httpServletRequest.getParameterValues("rq").length; i++) { rq += httpServletRequest.getParameterValues("rq")[i]; if (i < httpServletRequest.getParameterValues("rq").length - 1) { rq += ";"; } } } String start = ""; if (httpServletRequest.getParameter("start") != null) { start = httpServletRequest.getParameter("start"); } String rows = ""; if (httpServletRequest.getParameter("rows") != null) { rows = httpServletRequest.getParameter("rows"); } String sort = ""; if (httpServletRequest.getParameter("sort") != null) { sort = httpServletRequest.getParameter("sort"); } String group = ""; if (httpServletRequest.getParameter("group") != null) { group = httpServletRequest.getParameter("group"); } // RDS: lokaler Katalog-Bestand String local = "0"; if (httpServletRequest.getParameter("local") != null && httpServletRequest.getParameter("local").equals("1")) { local = "1"; } // RDS: lokaler Bestand inkl. E-Holdings String holdings = "0"; if (httpServletRequest.getParameter("holdings") != null && httpServletRequest.getParameter("holdings").equals("1")) { holdings = "1"; } // record request String ids = ""; if (httpServletRequest.getParameter("ids") != null) { ids = httpServletRequest.getParameter("ids"); } Properties requestParameter = new Properties(); requestParameter.setProperty("q", q); requestParameter.setProperty("ids", ids); requestParameter.setProperty("start", start); requestParameter.setProperty("rows", rows); requestParameter.setProperty("sort", sort); requestParameter.setProperty("fq", fq); requestParameter.setProperty("rq", rq); requestParameter.setProperty("group", group); requestParameter.setProperty("local", local); requestParameter.setProperty("holdings", holdings); if (httpServletRequest.getParameter("news") != null && httpServletRequest.getParameter("news").equals("false")) { requestParameter.setProperty("news", "false"); } else { requestParameter.setProperty("news", "true"); } if (httpServletRequest.getParameter("exp") != null && httpServletRequest.getParameter("exp").equals("false")) { requestParameter.setProperty("exp", "false"); } else { requestParameter.setProperty("exp", "true"); } if (httpServletRequest.getParameter("eonly") != null && httpServletRequest.getParameter("eonly").equals("true")) { requestParameter.setProperty("eonly", "true"); } else { requestParameter.setProperty("eonly", "false"); } return requestParameter; } private void sendRequestError(HttpServletResponse httpServletResponse, RequestError requestError) { if (requestError.getCode() == HttpServletResponse.SC_SERVICE_UNAVAILABLE || requestError.getCode() == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) { try { Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf")); mailer.postMail("[" + this.config.getProperty("service.name") + "] Exception: " + requestError.getCode() + " Service unavailable.", requestError.getDescription()); } catch (MessagingException | IOException e1) { this.logger.error(e1.getMessage(), e1.getCause()); } } ObjectMapper mapper = new ObjectMapper(); httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAIA auth\""); httpServletResponse.setContentType("application/json"); try { if (this.format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); Properties parameters = new Properties(); parameters.setProperty("lang", this.language); parameters.setProperty("isTUintern", Boolean.toString(isTUintern)); parameters.setProperty("isUBintern", Boolean.toString(isUBintern)); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(requestError, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); this.format = "json"; } } // XML-Ausgabe mit JAXB if (this.format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(RequestError.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(requestError, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (this.format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), requestError); } } catch (Exception e) { e.printStackTrace(); } } }
48.801913
201
0.559332
4e3215fa003a94de59571180b7879671a5305eaf
503
package com.github.rod1andrade.entities; import com.github.rod1andrade.assets.Sprite; import com.github.rod1andrade.util.Loader; /** * @author Rodrigo Andrade */ public final class Mat extends RenderEntity { private static final Sprite matSprite = new Sprite(32, 0, 48, 32, Loader.spriteSheet); public Mat(int posX, int posY, int width, int height) { super(posX, posY, width, height, matSprite, null, false); } @Override public void update(float deltaTime) { } }
22.863636
90
0.701789
7d812bbb2a4dcaa4fee40d9b867cf8f5d85f4fa4
2,794
/* * MIT License * * Copyright (c) 2020 Ben Davies * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package uk.co.bjdavies.api.plugins; import java.util.Optional; /** * @author [email protected] (Ben Davies) * @since 1.0.0 */ public interface IPluginContainer { /** * This method will allow you to add a plugin to the container. * * @param name - The name of the plugin. * @param plugin - The plugin itself. */ void addPlugin(String name, Object plugin); /** * This method will allow you to add a plugin to the container. * * @param plugin - The plugin itself. */ void addPlugin(Object plugin); /** * This method allows you to remove a plugin from the container. * * @param name - This is the module that you want to remove. */ void removePlugin(String name); /** * This method checks whether the plugin specified exists in the container. * * @param name - The name of the plugin. * @return boolean */ boolean doesPluginExist(String name); /** * Return a plugin by its name * * @param name - The plugin name * @return Object */ Object getPlugin(String name); /** * This will attempt to shut down all plugins if they implement {@link IPluginEvents} */ void shutDownPlugins(); /** * This is the toString of the class will show the classes contents. * * @return String */ @Override String toString(); /** * Get a plugin settings from a namespace * * @param namespace - the namespace * @return {@link IPluginSettings} */ Optional<IPluginSettings> getPluginSettingsFromNamespace(String namespace); }
28.804124
89
0.671797
cd2ec37da8be8b4a6948fb042ad6ecfa35c01c98
1,206
package APL.types.functions.builtins.fns; import APL.*; import APL.errors.DomainError; import APL.types.*; import APL.types.functions.*; public class EvalBuiltin extends Builtin { @Override public String repr() { return "⍎"; } public EvalBuiltin(Scope sc) { super(sc); } public Value call(Value w) { Obj o = callObj(w); if (o instanceof Value) return (Value) o; throw new DomainError("⍎: was expected to return an array, got "+o.humanType(true), this); } public Obj callObj(Value w) { if (w instanceof ArrFun) return ((ArrFun) w).obj(); return Main.exec(w.asString(), sc); } public Value call(Value a, Value w) { Obj o = callObj(a, w); if (o instanceof Value) return (Value) o; throw new DomainError("⍎: was expected to return an array, got "+o.humanType(true), this); } public Obj callObj(Value a, Value w) { if (a instanceof ArrFun) { Obj obj = ((ArrFun) a).obj(); if (!(obj instanceof Fun)) throw new DomainError("⍎: ⍺ must be `function, was "+obj.humanType(true), this); return ((Fun) obj).callObj(w); } else { throw new DomainError("⍎: Expected ⍺ to be an arrayified function", this, a); } } }
30.15
113
0.636816
3130e36234509934744053844f45bad749d26f97
3,439
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.openejb.test.entity.cmp2; import org.apache.openejb.test.entity.cmp.BasicCmpHome; import javax.ejb.EJBHome; import javax.ejb.HomeHandle; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.rmi.MarshalledObject; /** * [6] Should be run as the sixth test suite of the BasicCmpTestClients */ public class Cmp2HomeHandleTests extends BasicCmp2TestClient { public Cmp2HomeHandleTests() { super("HomeHandle."); } protected void setUp() throws Exception { super.setUp(); final Object obj = initialContext.lookup("client/tests/entity/cmp2/BasicCmpHome"); ejbHome = (BasicCmpHome) obj; ejbHomeHandle = ejbHome.getHomeHandle(); } //================================= // Test home handle methods // public void test01_getEJBHome() { try { final EJBHome home = ejbHomeHandle.getEJBHome(); assertNotNull("The EJBHome is null", home); } catch (final Exception e) { fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } public void Xtest02_copyHandleByMarshalledObject() { try { final MarshalledObject obj = new MarshalledObject(ejbHomeHandle); final HomeHandle copy = (HomeHandle) obj.get(); assertNotNull("The HomeHandle copy is null", copy); final EJBHome home = copy.getEJBHome(); assertNotNull("The EJBHome is null", home); } catch (final Exception e) { fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } public void Xtest03_copyHandleBySerialize() { try { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(ejbHomeHandle); oos.flush(); oos.close(); final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); final ObjectInputStream ois = new ObjectInputStream(bais); final HomeHandle copy = (HomeHandle) ois.readObject(); assertNotNull("The HomeHandle copy is null", copy); final EJBHome home = copy.getEJBHome(); assertNotNull("The EJBHome is null", home); } catch (final Exception e) { fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } // // Test home handle methods //================================= }
36.978495
91
0.647281
e27d3f2f48d1ec1602c93b1a6970a131379b1b26
2,871
package main.java.tas.controller.tower.factory; /** * * Enumeration with all default towers present in the game * */ public enum DefaultTowers { /** * {@link main.java.tas.controller.tower.factory.ArcherFactory#basicArcher(main.java.tas.utils.Position, java.util.List)} */ BASICARCHER, /** * {@link main.java.tas.controller.tower.factory.ArcherFactory#biArcher(main.java.tas.utils.Position, java.util.List)} */ BIARCHER, /** * {@link main.java.tas.controller.tower.factory.ArcherFactory#triArcher(main.java.tas.utils.Position, java.util.List)} */ TRIARCHER, /** * {@link main.java.tas.controller.tower.factory.ArcherFactory#quadArcher(main.java.tas.utils.Position, java.util.List)} */ QUADARCHER, /** * {@link main.java.tas.controller.tower.factory.CannonFactory#basicCannon(main.java.tas.utils.Position, java.util.List)} */ BASICCANNON, /** * {@link main.java.tas.controller.tower.factory.CannonFactory#biCannon(main.java.tas.utils.Position, java.util.List)} */ BICANNON, /** * {@link main.java.tas.controller.tower.factory.CannonFactory#triCannon(main.java.tas.utils.Position, java.util.List)} */ TRICANNON, /** * {@link main.java.tas.controller.tower.factory.CannonFactory#quadCannon(main.java.tas.utils.Position, java.util.List)} */ QUADCANNON, /** * {@link main.java.tas.controller.tower.factory.FlameFactory#basicFlame(main.java.tas.utils.Position, java.util.List)} */ BASICFLAME, /** * {@link main.java.tas.controller.tower.factory.FlameFactory#biFlame(main.java.tas.utils.Position, java.util.List)} */ BIFLAME, /** * {@link main.java.tas.controller.tower.factory.FlameFactory#triFlame(main.java.tas.utils.Position, java.util.List)} */ TRIFLAME, /** * {@link main.java.tas.controller.tower.factory.FlameFactory#quadFlame(main.java.tas.utils.Position, java.util.List)} */ QUADFLAME, /** * {@link main.java.tas.controller.tower.factory.GasFactory#gasTower(main.java.tas.utils.Position, java.util.List)} */ GASTOWER, /** * {@link main.java.tas.controller.tower.factory.MortarFactory#basicMortar(main.java.tas.utils.Position, java.util.List)} */ BASICMORTAR, /** * {@link main.java.tas.controller.tower.factory.MortarFactory#superMortar(main.java.tas.utils.Position, java.util.List)} */ SUPERMORTAR, /** * {@link main.java.tas.controller.tower.factory.MortarFactory#godMortar(main.java.tas.utils.Position, java.util.List)} */ GODMORTAR, /** * {@link main.java.tas.controller.tower.factory.TeslaFactory#basicTesla(main.java.tas.utils.Position, java.util.List)} */ BASICTESLA, /** * {@link main.java.tas.controller.tower.factory.TeslaFactory#superTesla(main.java.tas.utils.Position, java.util.List)} */ SUPERTESLA, /** * {@link main.java.tas.controller.tower.factory.TeslaFactory#godTesla(main.java.tas.utils.Position, java.util.List)} */ GODTESLA }
33.383721
122
0.727273
61ad91ff0c679d40560bc60b245170944d687f07
1,708
package com.sweetmanor.demo.gui.swing.tree; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import com.sweetmanor.utils.FrameUtil; /** * 目录树示例 * * @version 1.0 2014-08-26 * @author ijlhjj */ public class DirectoryTreeDemo { JFrame frame = new JFrame("系统目录"); public void init() { File[] files = File.listRoots(); DefaultMutableTreeNode root = new DefaultMutableTreeNode("计算机"); for (File file : files) { root.add(new DefaultMutableTreeNode(file.getAbsolutePath())); } final JTree tree = new JTree(root); MouseListener ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); if (selRow != -1) { if (e.getClickCount() == 1) { System.out.println("单击事件:" + selRow + selPath); } else if (e.getClickCount() == 2) { System.out.println("双击事件:" + selRow + selPath); } } } }; tree.addMouseListener(ml); // tree.putClientProperty("JTree.lineStyle", "None");// 设置连接线类型 // tree.setRootVisible(false);// 设置根节点是否可见 tree.setShowsRootHandles(true);// 设置根节点显示折叠图标 tree.setEditable(true);// 设置树的可编辑状态,默认不可编辑 frame.add(new JScrollPane(tree)); frame.pack(); FrameUtil.center(frame); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static void main(String[] args) { new DirectoryTreeDemo().init(); } }
25.878788
67
0.699063
5a8fd9fdf174937b6bbf9f00c2beff71c20d6039
2,176
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|metrics package|; end_package begin_import import|import name|java operator|. name|lang operator|. name|annotation operator|. name|Retention import|; end_import begin_import import|import name|java operator|. name|lang operator|. name|annotation operator|. name|RetentionPolicy import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|yetus operator|. name|audience operator|. name|InterfaceAudience import|; end_import begin_comment comment|/** * This is a dummy annotation that forces javac to produce output for * otherwise empty package-info.java. * *<p>The result is maven-compiler-plugin can properly identify the scope of * changed files * *<p>See more details in *<a href="https://jira.codehaus.org/browse/MCOMPILER-205"> * maven-compiler-plugin: incremental compilation broken</a> */ end_comment begin_annotation_defn annotation|@ name|Retention argument_list|( name|RetentionPolicy operator|. name|SOURCE argument_list|) annotation|@ name|InterfaceAudience operator|. name|Private specifier|public annotation_defn|@interface name|PackageMarker block|{ } end_annotation_defn end_unit
26.536585
814
0.782169
4fefd2d69ae0af61a3edf040725d739dc62cd9ac
972
package com.newxton.nxtframework.service; import com.newxton.nxtframework.entity.NxtOrderFormPay; import java.util.List; /** * (NxtOrderFormPay)表服务接口 * * @author makejava * @since 2020-11-14 21:41:53 */ public interface NxtOrderFormPayService { /** * 通过ID查询单条数据 * * @param id 主键 * @return 实例对象 */ NxtOrderFormPay queryById(Long id); /** * 查询多条数据 * * @param offset 查询起始位置 * @param limit 查询条数 * @return 对象列表 */ List<NxtOrderFormPay> queryAllByLimit(int offset, int limit); /** * 新增数据 * * @param nxtOrderFormPay 实例对象 * @return 实例对象 */ NxtOrderFormPay insert(NxtOrderFormPay nxtOrderFormPay); /** * 修改数据 * * @param nxtOrderFormPay 实例对象 * @return 实例对象 */ NxtOrderFormPay update(NxtOrderFormPay nxtOrderFormPay); /** * 通过主键删除数据 * * @param id 主键 * @return 是否成功 */ boolean deleteById(Long id); }
17.357143
65
0.59465
e8ba74c18c465fce53317d695d3515daebeeb9a0
29,415
/* Generated By:JavaCC: Do not edit this line. LanguageDispatcher.java */ /**************************************************************************** Copyright 2001-2018 Sphenon GmbH Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ package com.sphenon.engines.generator.tchandler.classes; import com.sphenon.basics.context.*; import com.sphenon.engines.generator.*; import com.sphenon.engines.generator.tom.*; import com.sphenon.engines.generator.tchandler.*; import com.sphenon.engines.generator.returncodes.*; import java.io.Reader; import java.io.Writer; import java.io.IOException; public class LanguageDispatcher implements LanguageDispatcherConstants { protected Writer out; protected TCHLanguageDispatcher tch; public LanguageDispatcher (CallContext context, Reader in, TCHLanguageDispatcher tch) { this(in); this.out = out; this.tch = tch; } public String getPosition(CallContext context) { return "[line " + jj_input_stream.getBeginLine() + (jj_input_stream.getBeginLine() != jj_input_stream.getEndLine() ? ("-" + jj_input_stream.getEndLine()) : "") + ", column " + jj_input_stream.getBeginColumn() + (jj_input_stream.getBeginColumn() != jj_input_stream.getEndColumn() ? ("-" + jj_input_stream.getEndColumn()) : "") + "]"; } final public void Any(CallContext context, TCEvent tag_context_event, TOMNode current_node, StringBuffer value) throws ParseException, InvalidTemplateSyntax { Token token; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PERPER: token = jj_consume_token(PERPER); value.append("%%"); break; case PERCLO: token = jj_consume_token(PERCLO); value.append("%>"); break; case OPEPER: token = jj_consume_token(OPEPER); value.append("<%"); break; case ATCLO: token = jj_consume_token(ATCLO); value.append("@>"); break; case OPEAT: token = jj_consume_token(OPEAT); value.append("<@"); break; case BACKSL: token = jj_consume_token(BACKSL); value.append("\\"); break; case RETURN: token = jj_consume_token(RETURN); value.append("\n"); break; case ANY: token = jj_consume_token(ANY); value.append(token.image); break; case PPTAGB1: case PPTAGB2: PPTag(context, tag_context_event, current_node, value); break; default: jj_la1[0] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void NewLine(StringBuffer value) throws ParseException { Token token; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LN: token = jj_consume_token(LN); value.append(token.image); break; case LNCONT: jj_consume_token(LNCONT); break; default: jj_la1[1] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void BeginningOfLine(CallContext context, TCEvent tag_context_event, TOMNode current_node, StringBuffer value) throws ParseException, InvalidTemplateSyntax { Token token; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LNINDT: token = jj_consume_token(LNINDT); break; case WS: token = jj_consume_token(WS); value.append(token.image); break; case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case BACKSL: case RETURN: case PERPER: case ANY: Any(context, tag_context_event, current_node, value); break; default: jj_la1[2] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void RestOfLine(CallContext context, TCEvent tag_context_event, TOMNode current_node, StringBuffer value) throws ParseException, InvalidTemplateSyntax { Token token; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LNINDT: token = jj_consume_token(LNINDT); value.append(token.image); break; case WS: token = jj_consume_token(WS); value.append(token.image); break; case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case BACKSL: case RETURN: case PERPER: case ANY: Any(context, tag_context_event, current_node, value); break; default: jj_la1[3] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void NLLine(CallContext context, TCEvent tag_context_event, TOMNode current_node, StringBuffer value) throws ParseException, InvalidTemplateSyntax { Token token; NewLine(value); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNINDT: case WS: case BACKSL: case RETURN: case PERPER: case ANY: BeginningOfLine(context, tag_context_event, current_node, value); label_1: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNINDT: case WS: case BACKSL: case RETURN: case PERPER: case ANY: ; break; default: jj_la1[4] = jj_gen; break label_1; } RestOfLine(context, tag_context_event, current_node, value); } break; default: jj_la1[5] = jj_gen; ; } } final public StringBuffer FirstContent(CallContext context, TCEvent tag_context_event, TOMNode current_node) throws ParseException, InvalidTemplateSyntax { Token token; StringBuffer value; value = new StringBuffer(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNINDT: case WS: case BACKSL: case RETURN: case PERPER: case ANY: BeginningOfLine(context, tag_context_event, current_node, value); label_2: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNINDT: case WS: case BACKSL: case RETURN: case PERPER: case ANY: ; break; default: jj_la1[6] = jj_gen; break label_2; } RestOfLine(context, tag_context_event, current_node, value); } label_3: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LNCONT: case LN: ; break; default: jj_la1[7] = jj_gen; break label_3; } NLLine(context, tag_context_event, current_node, value); } break; case LNCONT: case LN: label_4: while (true) { NLLine(context, tag_context_event, current_node, value); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LNCONT: case LN: ; break; default: jj_la1[8] = jj_gen; break label_4; } } break; default: jj_la1[9] = jj_gen; jj_consume_token(-1); throw new ParseException(); } {if (true) return value;} throw new Error("Missing return statement in function"); } final public StringBuffer Content(CallContext context, TCEvent tag_context_event, TOMNode current_node, StringBuffer value) throws ParseException, InvalidTemplateSyntax { Token token; if (value == null) { value = new StringBuffer(); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNINDT: case WS: case BACKSL: case RETURN: case PERPER: case ANY: label_5: while (true) { RestOfLine(context, tag_context_event, current_node, value); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNINDT: case WS: case BACKSL: case RETURN: case PERPER: case ANY: ; break; default: jj_la1[10] = jj_gen; break label_5; } } label_6: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LNCONT: case LN: ; break; default: jj_la1[11] = jj_gen; break label_6; } NLLine(context, tag_context_event, current_node, value); } break; case LNCONT: case LN: label_7: while (true) { NLLine(context, tag_context_event, current_node, value); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LNCONT: case LN: ; break; default: jj_la1[12] = jj_gen; break label_7; } } break; default: jj_la1[13] = jj_gen; jj_consume_token(-1); throw new ParseException(); } {if (true) return value;} throw new Error("Missing return statement in function"); } final public TOMNode FirstText(CallContext context, TOMNode current_node) throws ParseException, InvalidTemplateSyntax { Token token; StringBuffer value=null; value = FirstContent(context, TCEvent.TAG, current_node); {if (true) return tch.handleText(context, current_node, value.toString());} throw new Error("Missing return statement in function"); } final public TOMNode Text(CallContext context, TOMNode current_node) throws ParseException, InvalidTemplateSyntax { Token token; StringBuffer value=null; value = Content(context, TCEvent.TAG, current_node, null); {if (true) return tch.handleText(context, current_node, value.toString());} throw new Error("Missing return statement in function"); } final public StringBuffer PossiblyNestedComment(CallContext context, TOMNode current_node, StringBuffer value) throws ParseException, InvalidTemplateSyntax { Token token; if (value == null) { value = new StringBuffer(); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TCMTB: jj_consume_token(TCMTB); break; case TCMTB2: jj_consume_token(TCMTB2); break; default: jj_la1[14] = jj_gen; jj_consume_token(-1); throw new ParseException(); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNCONT: case LNINDT: case WS: case BACKSL: case RETURN: case LN: case PERPER: case ANY: Content(context, null, current_node, value); break; default: jj_la1[15] = jj_gen; ; } label_8: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TCMTB: case CODCB: case CODIB: case OUTCB: case DIRCB: case CODEB: case TCMTB2: case CODEE: case OUTCE: case DIRCE: ; break; default: jj_la1[16] = jj_gen; break label_8; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TCMTB: case TCMTB2: PossiblyNestedComment(context, current_node, value); break; case CODCB: token = jj_consume_token(CODCB); value.append(token.image); break; case CODIB: token = jj_consume_token(CODIB); value.append(token.image); break; case OUTCB: token = jj_consume_token(OUTCB); value.append(token.image); break; case OUTCE: token = jj_consume_token(OUTCE); value.append(token.image); break; case CODEB: token = jj_consume_token(CODEB); value.append(token.image); break; case CODEE: token = jj_consume_token(CODEE); value.append(token.image); break; case DIRCB: token = jj_consume_token(DIRCB); value.append(token.image); break; case DIRCE: token = jj_consume_token(DIRCE); value.append(token.image); break; default: jj_la1[17] = jj_gen; jj_consume_token(-1); throw new ParseException(); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNCONT: case LNINDT: case WS: case BACKSL: case RETURN: case LN: case PERPER: case ANY: Content(context, null, current_node, value); break; default: jj_la1[18] = jj_gen; ; } } jj_consume_token(TCMTE); {if (true) return value;} throw new Error("Missing return statement in function"); } final public TOMNode TemplateComment(CallContext context, TOMNode current_node) throws ParseException, InvalidTemplateSyntax { Token token; StringBuffer value=null; value = PossiblyNestedComment(context, current_node, null); {if (true) return tch.handleTemplateComment(context, current_node, value.toString());} throw new Error("Missing return statement in function"); } final public TOMNode JavaCodeGeneration(CallContext context, TOMNode current_node) throws ParseException, InvalidTemplateSyntax { Token token; StringBuffer value=null; jj_consume_token(CODEB); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNCONT: case LNINDT: case WS: case BACKSL: case RETURN: case LN: case PERPER: case ANY: value = Content(context, TCEvent.JAVA_CODE_TAG, current_node, null); break; default: jj_la1[19] = jj_gen; ; } jj_consume_token(CODEE); {if (true) return tch.handleJavaCodeGeneration(context, current_node, value == null ? "" : value.toString());} throw new Error("Missing return statement in function"); } final public TOMNode JavaCodeClass(CallContext context, TOMNode current_node) throws ParseException, InvalidTemplateSyntax { Token token; StringBuffer value=null; jj_consume_token(CODCB); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNCONT: case LNINDT: case WS: case BACKSL: case RETURN: case LN: case PERPER: case ANY: value = Content(context, TCEvent.JAVA_CODE_TAG, current_node, null); break; default: jj_la1[20] = jj_gen; ; } jj_consume_token(CODEE); {if (true) return tch.handleJavaCodeClass(context, current_node, value == null ? "" : value.toString());} throw new Error("Missing return statement in function"); } final public TOMNode JavaCodeImport(CallContext context, TOMNode current_node) throws ParseException, InvalidTemplateSyntax { Token token; StringBuffer value=null; jj_consume_token(CODIB); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNCONT: case LNINDT: case WS: case BACKSL: case RETURN: case LN: case PERPER: case ANY: value = Content(context, TCEvent.JAVA_CODE_TAG, current_node, null); break; default: jj_la1[21] = jj_gen; ; } jj_consume_token(CODEE); {if (true) return tch.handleJavaCodeImport(context, current_node, value == null ? "" : value.toString());} throw new Error("Missing return statement in function"); } final public TOMNode OutputCode(CallContext context, TOMNode current_node) throws ParseException, InvalidTemplateSyntax { Token token; StringBuffer value=null; jj_consume_token(OUTCB); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNCONT: case LNINDT: case WS: case BACKSL: case RETURN: case LN: case PERPER: case ANY: value = Content(context, TCEvent.JAVA_EXPRESSION_TAG, current_node, null); break; default: jj_la1[22] = jj_gen; ; } jj_consume_token(OUTCE); {if (true) return tch.handleJavaExpression(context, current_node, value == null ? "" : value.toString());} throw new Error("Missing return statement in function"); } final public TOMNode DirectiveCode(CallContext context, TOMNode current_node) throws ParseException, InvalidTemplateSyntax { Token token; StringBuffer value=null; jj_consume_token(DIRCB); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNCONT: case LNINDT: case WS: case BACKSL: case RETURN: case LN: case PERPER: case ANY: value = Content(context, TCEvent.TEMPLATE_CODE_TAG, current_node, null); break; default: jj_la1[23] = jj_gen; ; } jj_consume_token(DIRCE); {if (true) return tch.handleTemplateCode(context, current_node, value == null ? "" : value.toString());} throw new Error("Missing return statement in function"); } final public TOMNode Tag(CallContext context, TCEvent tag_context_event, TOMNode current_node) throws ParseException, InvalidTemplateSyntax { Token token; StringBuffer value=null; jj_consume_token(TAGB); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNCONT: case LNINDT: case WS: case BACKSL: case RETURN: case LN: case PERPER: case ANY: value = Content(context, TCEvent.TAG_TAG, current_node, null); break; default: jj_la1[24] = jj_gen; ; } jj_consume_token(TAGE); {if (true) return tch.handleTag(context, tag_context_event, current_node, value == null ? "" : value.toString());} throw new Error("Missing return statement in function"); } final public void PPTag(CallContext context, TCEvent tag_context_event, TOMNode current_node, StringBuffer value) throws ParseException, InvalidTemplateSyntax { Token token; StringBuffer tag_value=null; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PPTAGB1: jj_consume_token(PPTAGB1); break; case PPTAGB2: jj_consume_token(PPTAGB2); break; default: jj_la1[25] = jj_gen; jj_consume_token(-1); throw new ParseException(); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNCONT: case LNINDT: case WS: case BACKSL: case RETURN: case LN: case PERPER: case ANY: tag_value = Content(context, TCEvent.TAG_TAG, current_node, null); break; default: jj_la1[26] = jj_gen; ; } jj_consume_token(TAGE); tch.handlePPTag(context, tag_context_event, current_node, value, tag_value == null ? "" : tag_value.toString()); } final public TOMNode ASCII(CallContext context, TOMNode current_node) throws ParseException, InvalidTemplateSyntax { Token token; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNCONT: case LNINDT: case WS: case BACKSL: case RETURN: case LN: case PERPER: case ANY: current_node = FirstText(context, current_node); break; default: jj_la1[27] = jj_gen; ; } label_9: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TCMTB: case CODCB: case CODIB: case OUTCB: case DIRCB: case CODEB: case TAGB: case TCMTB2: ; break; default: jj_la1[28] = jj_gen; break label_9; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TCMTB: case TCMTB2: current_node = TemplateComment(context, current_node); break; case CODEB: current_node = JavaCodeGeneration(context, current_node); break; case CODCB: current_node = JavaCodeClass(context, current_node); break; case CODIB: current_node = JavaCodeImport(context, current_node); break; case OUTCB: current_node = OutputCode(context, current_node); break; case DIRCB: current_node = DirectiveCode(context, current_node); break; case TAGB: current_node = Tag(context, TCEvent.TAG, current_node); break; default: jj_la1[29] = jj_gen; jj_consume_token(-1); throw new ParseException(); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPEPER: case PERCLO: case PPTAGB1: case PPTAGB2: case OPEAT: case ATCLO: case LNCONT: case LNINDT: case WS: case BACKSL: case RETURN: case LN: case PERPER: case ANY: current_node = Text(context, current_node); break; default: jj_la1[30] = jj_gen; ; } } jj_consume_token(0); {if (true) return current_node;} throw new Error("Missing return statement in function"); } public LanguageDispatcherTokenManager token_source; SimpleCharStream jj_input_stream; public Token token, jj_nt; private int jj_ntk; private int jj_gen; final private int[] jj_la1 = new int[31]; static private int[] jj_la1_0; static { jj_la1_0(); } private static void jj_la1_0() { jj_la1_0 = new int[] {0xd8ec080,0x2100000,0xdeec080,0xdeec080,0xdeec080,0xdeec080,0xdeec080,0x2100000,0x2100000,0xffec080,0xdeec080,0x2100000,0x2100000,0xffec080,0x202,0xffec080,0x3a7e,0x3a7e,0xffec080,0xffec080,0xffec080,0xffec080,0xffec080,0xffec080,0xffec080,0x28000,0xffec080,0xffec080,0x37e,0x37e,0xffec080,}; } public LanguageDispatcher(java.io.InputStream stream) { this(stream, null); } public LanguageDispatcher(java.io.InputStream stream, String encoding) { try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source = new LanguageDispatcherTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 31; i++) jj_la1[i] = -1; } public void ReInit(java.io.InputStream stream) { ReInit(stream, null); } public void ReInit(java.io.InputStream stream, String encoding) { try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 31; i++) jj_la1[i] = -1; } public LanguageDispatcher(java.io.Reader stream) { jj_input_stream = new SimpleCharStream(stream, 1, 1); token_source = new LanguageDispatcherTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 31; i++) jj_la1[i] = -1; } public void ReInit(java.io.Reader stream) { jj_input_stream.ReInit(stream, 1, 1); token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 31; i++) jj_la1[i] = -1; } public LanguageDispatcher(LanguageDispatcherTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 31; i++) jj_la1[i] = -1; } public void ReInit(LanguageDispatcherTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 31; i++) jj_la1[i] = -1; } final private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { jj_gen++; return token; } token = oldToken; jj_kind = kind; throw generateParseException(); } final public Token getNextToken() { if (token.next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; jj_gen++; return token; } final public Token getToken(int index) { Token t = token; for (int i = 0; i < index; i++) { if (t.next != null) t = t.next; else t = t.next = token_source.getNextToken(); } return t; } final private int jj_ntk() { if ((jj_nt=token.next) == null) return (jj_ntk = (token.next=token_source.getNextToken()).kind); else return (jj_ntk = jj_nt.kind); } private java.util.Vector jj_expentries = new java.util.Vector(); private int[] jj_expentry; private int jj_kind = -1; public ParseException generateParseException() { jj_expentries.removeAllElements(); boolean[] la1tokens = new boolean[28]; for (int i = 0; i < 28; i++) { la1tokens[i] = false; } if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 31; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } } } } for (int i = 0; i < 28; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.addElement(jj_expentry); } } int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = (int[])jj_expentries.elementAt(i); } return new ParseException(token, exptokseq, tokenImage); } final public void enable_tracing() { } final public void disable_tracing() { } }
30.015306
320
0.56325
56d512c0955b8286f30008419b75f9f45617bd61
1,048
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems; import edu.wpi.first.wpilibj2.command.SubsystemBase; import com.revrobotics.CANSparkMax; import com.revrobotics.CANSparkMaxLowLevel.MotorType; import frc.robot.Constants; /** Add your docs here. */ public class Intake extends SubsystemBase { // Put methods for controlling this subsystem // here. Call these from Commands. //private static final double kEncoderConversion = 1.0 * 2 * Math.PI / 53.3; private CANSparkMax intakeMotor; //private CANEncoder intakeEncoder; public Intake() { intakeMotor = new CANSparkMax(Constants.INTAKE, MotorType.kBrushless); } public void takeIn(boolean run) { if (run) intakeMotor.set(Constants.MOTOR_SPEED); else intakeMotor.set(0); //System.out.println("run"); } public CANSparkMax getMotor() { return intakeMotor; } }
27.578947
78
0.73187
f8c63b6ca9b87f15df3fbf3582897b574011d694
4,599
/* * Copyright 2009-2020 Tilmann Zaeschke * * 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.zoodb.internal.server.index; import java.util.List; import java.util.NoSuchElementException; import org.zoodb.internal.server.DiskIO.PAGE_TYPE; import org.zoodb.internal.server.IOResourceProvider; import org.zoodb.internal.server.StorageChannelOutput; import org.zoodb.internal.util.CloseableIterator; /** * Interfaces for database indices and their iterators. * * * @author Tilmann Zaeschke * */ public interface LongLongIndex { class LLEntry { private final long key; private final long value; public LLEntry(long k, long v) { key = k; value = v; } public long getKey() { return key; } public long getValue() { return value; } } //Interface for index iterators that can be deregistered. //TODO remove if we remove registerable iterators. interface LongLongIterator<E> extends CloseableIterator<E> { } //TODO remove? //TODO the methods are deprecated because we should avoid too many implementations' //TODO check whether this is still a problem for performance interface LLEntryIterator extends LongLongIterator<LLEntry> { @Deprecated boolean hasNextULL(); @Deprecated LLEntry nextULL(); @Deprecated long nextKey(); } /** * Interface with special methods for unique indices. */ interface LongLongUIndex extends LongLongIndex { LLEntry findValue(long key); /** * @param key OID * @return the previous value * @throws NoSuchElementException if key is not found */ long removeLong(long key); /** * @param key OID * @param failValue The value to return in case the key has no entry. * @return the previous value */ long removeLongNoFail(long key, long failValue); /** * Special method to remove entries. When removing the entry, * it checks whether other entries in the given range exist. * If none exist, the value is reported as free page to FSM. * * In effect, when used in the POS-index, an empty range indicates that there are no more * objects on a given page (pageId=value), therefore the page can be reported as free. * * @param pos The pos number * @param min min * @param max max * @return The previous value */ long deleteAndCheckRangeEmpty(long pos, long min, long max); } void insertLong(long key, long value); /** * If the tree is unique, this simply removes the entry with the given key. If the tree * is not unique, it removes only entries where key AND value match. * @param key The key * @param value The value * @return the value. * @throws NoSuchElementException if the key or key/value pair was not found. */ long removeLong(long key, long value); String print(); /** * Before updating the index, the method checks whether the entry already exists. * In that case the entry is not updated (non-unique is anyway not updated in that case) * and false is returned. * @param key The key * @param value The value * @return False if the entry was already used. Otherwise true. */ boolean insertLongIfNotSet(long key, long value); int statsGetLeavesN(); int statsGetInnerN(); void clear(); LLEntryIterator iterator(); LLEntryIterator iterator(long min, long max); LongLongIterator<LLEntry> descendingIterator(); LongLongIterator<LLEntry> descendingIterator(long max, long min); long getMinKey(); long getMaxKey(); /** * Write the index (dirty pages only) to disk. * @param out Output channel * @return pageId of the root page */ int write(StorageChannelOutput out); long size(); /** * * @return The data type to which this index is associated. */ PAGE_TYPE getDataType(); IOResourceProvider getIO(); /** * * @return A list of all page IDs used in this index. */ List<Integer> debugPageIds(); int statsGetWrittenPagesN(); boolean isDirty(); }
26.583815
92
0.686236
b274db20b3b9de8fe26858e9c11f851955d9e676
3,000
/* * Copyright 2015 Open LVC Project. * * This file is part of Open LVC Disco. * * 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.openlvc.disco.pdu; import java.math.BigInteger; import java.util.Collection; /** * A Utility class that provides size constants and functions relating to the DIS specification. */ public class DisSizes { //---------------------------------------------------------- // STATIC VARIABLES //---------------------------------------------------------- // SIZES (specified in bytes) public static final int UI8_SIZE = 1; public static final int UI16_SIZE = 2; public static final int UI32_SIZE = 4; public static final int UI64_SIZE = 8; public static final int FLOAT32_SIZE = 4; public static final int FLOAT64_SIZE = 8; // MAXIMUM VALUES public static final short UI8_MAX_VALUE = 0xFF; public static final int UI16_MAX_VALUE = 0xFFFF; public static final long UI32_MAX_VALUE = 0xFFFFFFFFl; public static final BigInteger UI64_MAX_VALUE = BigInteger.valueOf( 2 ).pow( 64 ).subtract( BigInteger.ONE ); /** * The maximum value that can fit into the PDU Header's length field (specified in bytes). */ // MTU - IPv4 Header - UDP Header // 1500 20 8 = 1472 public static final int PDU_MAX_SIZE = 1472; //---------------------------------------------------------- // INSTANCE VARIABLES //---------------------------------------------------------- //---------------------------------------------------------- // CONSTRUCTORS //---------------------------------------------------------- //---------------------------------------------------------- // INSTANCE METHODS //---------------------------------------------------------- //---------------------------------------------------------- // STATIC METHODS //---------------------------------------------------------- /** * Returns the size, in bytes, of the the specified collection of DIS <code>IPDUComponent</code>s * * @param collection The collection to calculate the size of * * @return An int representing the size, in bytes, of the specified collection */ public static final int getByteLengthOfCollection( Collection<? extends IPduComponent> collection ) { int size = 0; for( IPduComponent component : collection ) size += component.getByteLength(); return size; } }
36.144578
110
0.543
4acaab62de76d7d45e9538fc4aae29a203c62029
10,932
package com.gmail.mooman219; import java.awt.AWTException; import java.awt.Robot; import java.awt.Toolkit; import java.awt.event.KeyEvent; /** * @author Joseph Cumbo (mooman219) */ public class Keyboard { private final Robot robot; public Keyboard() throws AWTException { this.robot = new Robot(); } public Keyboard(Robot robot) { this.robot = robot; } public void type(String word) { for (int i = 0; i < word.length(); i++) { type(word.charAt(i)); } } public Robot getRobot() { return robot; } public void select(int shiftLeft, int shiftRight) { Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_NUM_LOCK, false); robot.keyRelease(KeyEvent.VK_CONTROL); for (int i = 0; i < shiftLeft; i++) { robot.keyPress(KeyEvent.VK_LEFT); robot.keyRelease(KeyEvent.VK_LEFT); } robot.keyPress(KeyEvent.VK_SHIFT); for (int i = 0; i < shiftRight; i++) { robot.keyPress(KeyEvent.VK_RIGHT); robot.keyRelease(KeyEvent.VK_RIGHT); } robot.keyRelease(KeyEvent.VK_SHIFT); Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_NUM_LOCK, true); robot.waitForIdle(); robot.keyPress(KeyEvent.VK_CONTROL); robot.keyRelease(KeyEvent.VK_CONTROL); } public void type(char character) { switch (character) { case 'a': type(KeyEvent.VK_A); break; case 'b': type(KeyEvent.VK_B); break; case 'c': type(KeyEvent.VK_C); break; case 'd': type(KeyEvent.VK_D); break; case 'e': type(KeyEvent.VK_E); break; case 'f': type(KeyEvent.VK_F); break; case 'g': type(KeyEvent.VK_G); break; case 'h': type(KeyEvent.VK_H); break; case 'i': type(KeyEvent.VK_I); break; case 'j': type(KeyEvent.VK_J); break; case 'k': type(KeyEvent.VK_K); break; case 'l': type(KeyEvent.VK_L); break; case 'm': type(KeyEvent.VK_M); break; case 'n': type(KeyEvent.VK_N); break; case 'o': type(KeyEvent.VK_O); break; case 'p': type(KeyEvent.VK_P); break; case 'q': type(KeyEvent.VK_Q); break; case 'r': type(KeyEvent.VK_R); break; case 's': type(KeyEvent.VK_S); break; case 't': type(KeyEvent.VK_T); break; case 'u': type(KeyEvent.VK_U); break; case 'v': type(KeyEvent.VK_V); break; case 'w': type(KeyEvent.VK_W); break; case 'x': type(KeyEvent.VK_X); break; case 'y': type(KeyEvent.VK_Y); break; case 'z': type(KeyEvent.VK_Z); break; case 'A': type(KeyEvent.VK_SHIFT, KeyEvent.VK_A); break; case 'B': type(KeyEvent.VK_SHIFT, KeyEvent.VK_B); break; case 'C': type(KeyEvent.VK_SHIFT, KeyEvent.VK_C); break; case 'D': type(KeyEvent.VK_SHIFT, KeyEvent.VK_D); break; case 'E': type(KeyEvent.VK_SHIFT, KeyEvent.VK_E); break; case 'F': type(KeyEvent.VK_SHIFT, KeyEvent.VK_F); break; case 'G': type(KeyEvent.VK_SHIFT, KeyEvent.VK_G); break; case 'H': type(KeyEvent.VK_SHIFT, KeyEvent.VK_H); break; case 'I': type(KeyEvent.VK_SHIFT, KeyEvent.VK_I); break; case 'J': type(KeyEvent.VK_SHIFT, KeyEvent.VK_J); break; case 'K': type(KeyEvent.VK_SHIFT, KeyEvent.VK_K); break; case 'L': type(KeyEvent.VK_SHIFT, KeyEvent.VK_L); break; case 'M': type(KeyEvent.VK_SHIFT, KeyEvent.VK_M); break; case 'N': type(KeyEvent.VK_SHIFT, KeyEvent.VK_N); break; case 'O': type(KeyEvent.VK_SHIFT, KeyEvent.VK_O); break; case 'P': type(KeyEvent.VK_SHIFT, KeyEvent.VK_P); break; case 'Q': type(KeyEvent.VK_SHIFT, KeyEvent.VK_Q); break; case 'R': type(KeyEvent.VK_SHIFT, KeyEvent.VK_R); break; case 'S': type(KeyEvent.VK_SHIFT, KeyEvent.VK_S); break; case 'T': type(KeyEvent.VK_SHIFT, KeyEvent.VK_T); break; case 'U': type(KeyEvent.VK_SHIFT, KeyEvent.VK_U); break; case 'V': type(KeyEvent.VK_SHIFT, KeyEvent.VK_V); break; case 'W': type(KeyEvent.VK_SHIFT, KeyEvent.VK_W); break; case 'X': type(KeyEvent.VK_SHIFT, KeyEvent.VK_X); break; case 'Y': type(KeyEvent.VK_SHIFT, KeyEvent.VK_Y); break; case 'Z': type(KeyEvent.VK_SHIFT, KeyEvent.VK_Z); break; case '`': type(KeyEvent.VK_BACK_QUOTE); break; case '0': type(KeyEvent.VK_0); break; case '1': type(KeyEvent.VK_1); break; case '2': type(KeyEvent.VK_2); break; case '3': type(KeyEvent.VK_3); break; case '4': type(KeyEvent.VK_4); break; case '5': type(KeyEvent.VK_5); break; case '6': type(KeyEvent.VK_6); break; case '7': type(KeyEvent.VK_7); break; case '8': type(KeyEvent.VK_8); break; case '9': type(KeyEvent.VK_9); break; case '-': type(KeyEvent.VK_MINUS); break; case '=': type(KeyEvent.VK_EQUALS); break; case '~': type(KeyEvent.VK_SHIFT, KeyEvent.VK_BACK_QUOTE); break; case '!': type(KeyEvent.VK_SHIFT, KeyEvent.VK_1); break; case '@': type(KeyEvent.VK_SHIFT, KeyEvent.VK_2); break; case '#': type(KeyEvent.VK_SHIFT, KeyEvent.VK_3); break; case '$': type(KeyEvent.VK_SHIFT, KeyEvent.VK_4); break; case '%': type(KeyEvent.VK_SHIFT, KeyEvent.VK_5); break; case '^': type(KeyEvent.VK_SHIFT, KeyEvent.VK_6); break; case '&': type(KeyEvent.VK_SHIFT, KeyEvent.VK_7); break; case '*': type(KeyEvent.VK_SHIFT, KeyEvent.VK_8); break; case '(': type(KeyEvent.VK_SHIFT, KeyEvent.VK_9); break; case ')': type(KeyEvent.VK_SHIFT, KeyEvent.VK_0); break; case '_': type(KeyEvent.VK_SHIFT, KeyEvent.VK_MINUS); break; case '+': type(KeyEvent.VK_ADD); break; case '\t': type(KeyEvent.VK_TAB); break; case '\n': type(KeyEvent.VK_ENTER); break; case '[': type(KeyEvent.VK_OPEN_BRACKET); break; case ']': type(KeyEvent.VK_CLOSE_BRACKET); break; case '\\': type(KeyEvent.VK_BACK_SLASH); break; case '{': type(KeyEvent.VK_SHIFT, KeyEvent.VK_OPEN_BRACKET); break; case '}': type(KeyEvent.VK_SHIFT, KeyEvent.VK_CLOSE_BRACKET); break; case '|': type(KeyEvent.VK_SHIFT, KeyEvent.VK_BACK_SLASH); break; case ';': type(KeyEvent.VK_SEMICOLON); break; case ':': type(KeyEvent.VK_SHIFT, KeyEvent.VK_SEMICOLON); break; case '\'': type(KeyEvent.VK_QUOTE); break; case '"': type(KeyEvent.VK_SHIFT, KeyEvent.VK_QUOTE); break; case ',': type(KeyEvent.VK_COMMA); break; case '<': type(KeyEvent.VK_SHIFT, KeyEvent.VK_COMMA); break; case '.': type(KeyEvent.VK_PERIOD); break; case '>': type(KeyEvent.VK_SHIFT, KeyEvent.VK_PERIOD); break; case '/': type(KeyEvent.VK_SLASH); break; case '?': type(KeyEvent.VK_SHIFT, KeyEvent.VK_SLASH); break; case ' ': type(KeyEvent.VK_SPACE); break; default: System.err.println("Unable to type key '" + character + "'."); } } /* * This is more performant over using variable sized arrays as a parameter. */ private void type(int keya) { robot.keyPress(keya); robot.keyRelease(keya); } private void type(int keya, int keyb) { robot.keyPress(keya); robot.keyPress(keyb); robot.keyRelease(keyb); robot.keyRelease(keya); } }
29.950685
84
0.416118
59bc23706212779becd164cd451ee75c7f8b52ae
135
package com.istudio.tkg.server.model.response; import lombok.Data; @Data public class EnterGameResponse { private int status; }
13.5
46
0.762963
1a0166caebe66791a2fea528c2d76df9e20ee09e
7,189
/* */ package org.gdstash.ui.select; /* */ /* */ import java.awt.Component; /* */ import java.awt.Container; /* */ import java.awt.Font; /* */ import java.util.LinkedList; /* */ import java.util.List; /* */ import javax.swing.BorderFactory; /* */ import javax.swing.GroupLayout; /* */ import javax.swing.JCheckBox; /* */ import javax.swing.UIManager; /* */ import javax.swing.border.Border; /* */ import javax.swing.border.TitledBorder; /* */ import org.gdstash.db.SelectionCriteria; /* */ import org.gdstash.ui.GDStashFrame; /* */ import org.gdstash.ui.util.AdjustablePanel; /* */ import org.gdstash.util.GDMsgFormatter; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class ItemRarityPane /* */ extends AdjustablePanel /* */ { /* */ private JCheckBox cbCommon; /* */ private JCheckBox cbMagical; /* */ private JCheckBox cbRare; /* */ private JCheckBox cbEpic; /* */ private JCheckBox cbLegendary; /* */ /* */ public ItemRarityPane(int direction) { /* 36 */ adjustUI(); /* */ /* 38 */ GroupLayout layout = null; /* 39 */ GroupLayout.SequentialGroup hGroup = null; /* 40 */ GroupLayout.SequentialGroup vGroup = null; /* */ /* 42 */ layout = new GroupLayout((Container)this); /* 43 */ setLayout(layout); /* */ /* 45 */ layout.setAutoCreateGaps(true); /* */ /* */ /* 48 */ layout.setAutoCreateContainerGaps(true); /* */ /* */ /* 51 */ hGroup = layout.createSequentialGroup(); /* */ /* */ /* 54 */ hGroup /* 55 */ .addGroup(layout.createParallelGroup() /* 56 */ .addComponent(this.cbCommon) /* 57 */ .addComponent(this.cbMagical) /* 58 */ .addComponent(this.cbRare) /* 59 */ .addComponent(this.cbEpic) /* 60 */ .addComponent(this.cbLegendary)); /* */ /* */ /* 63 */ vGroup = layout.createSequentialGroup(); /* */ /* */ /* 66 */ vGroup /* 67 */ .addGroup(layout.createParallelGroup() /* 68 */ .addComponent(this.cbCommon)) /* 69 */ .addGroup(layout.createParallelGroup() /* 70 */ .addComponent(this.cbMagical)) /* 71 */ .addGroup(layout.createParallelGroup() /* 72 */ .addComponent(this.cbRare)) /* 73 */ .addGroup(layout.createParallelGroup() /* 74 */ .addComponent(this.cbEpic)) /* 75 */ .addGroup(layout.createParallelGroup() /* 76 */ .addComponent(this.cbLegendary)); /* */ /* 78 */ if (direction == 0) { /* 79 */ layout.setHorizontalGroup(vGroup); /* 80 */ layout.setVerticalGroup(hGroup); /* */ } else { /* 82 */ layout.setHorizontalGroup(hGroup); /* 83 */ layout.setVerticalGroup(vGroup); /* */ } /* */ /* 86 */ layout.linkSize(0, new Component[] { this.cbCommon, this.cbMagical }); /* 87 */ layout.linkSize(0, new Component[] { this.cbCommon, this.cbRare }); /* 88 */ layout.linkSize(0, new Component[] { this.cbCommon, this.cbEpic }); /* 89 */ layout.linkSize(0, new Component[] { this.cbCommon, this.cbLegendary }); /* */ /* 91 */ layout.linkSize(1, new Component[] { this.cbCommon, this.cbMagical }); /* 92 */ layout.linkSize(1, new Component[] { this.cbCommon, this.cbRare }); /* 93 */ layout.linkSize(1, new Component[] { this.cbCommon, this.cbEpic }); /* 94 */ layout.linkSize(1, new Component[] { this.cbCommon, this.cbLegendary }); /* */ } /* */ /* */ /* */ public void adjustUI() { /* 99 */ Font fntLabel = UIManager.getDefaults().getFont("Label.font"); /* 100 */ Font fntCheck = UIManager.getDefaults().getFont("CheckBox.font"); /* 101 */ if (fntCheck == null) fntCheck = fntLabel; /* 102 */ Font fntBorder = UIManager.getDefaults().getFont("TitledBorder.font"); /* 103 */ if (fntBorder == null) fntBorder = fntLabel; /* */ /* 105 */ fntLabel = fntLabel.deriveFont(GDStashFrame.iniConfig.sectUI.fontSize); /* 106 */ fntCheck = fntCheck.deriveFont(GDStashFrame.iniConfig.sectUI.fontSize); /* 107 */ fntBorder = fntBorder.deriveFont(GDStashFrame.iniConfig.sectUI.fontSize); /* */ /* 109 */ Border lowered = BorderFactory.createEtchedBorder(1); /* 110 */ Border raised = BorderFactory.createEtchedBorder(0); /* 111 */ Border compound = BorderFactory.createCompoundBorder(raised, lowered); /* 112 */ TitledBorder text = BorderFactory.createTitledBorder(compound, GDMsgFormatter.getString(GDMsgFormatter.rbGD, "TXT_RARITY_ITEM")); /* 113 */ text.setTitleFont(fntBorder); /* */ /* 115 */ setBorder(text); /* */ /* 117 */ if (this.cbCommon == null) this.cbCommon = new JCheckBox(); /* 118 */ this.cbCommon.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "RARITY_ITEM_COMMON")); /* 119 */ this.cbCommon.setFont(fntCheck); /* */ /* 121 */ if (this.cbMagical == null) this.cbMagical = new JCheckBox(); /* 122 */ this.cbMagical.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "RARITY_ITEM_MAGICAL")); /* 123 */ this.cbMagical.setFont(fntCheck); /* */ /* 125 */ if (this.cbRare == null) this.cbRare = new JCheckBox(); /* 126 */ this.cbRare.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "RARITY_ITEM_RARE")); /* 127 */ this.cbRare.setFont(fntCheck); /* */ /* 129 */ if (this.cbEpic == null) this.cbEpic = new JCheckBox(); /* 130 */ this.cbEpic.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "RARITY_ITEM_EPIC")); /* 131 */ this.cbEpic.setFont(fntCheck); /* */ /* 133 */ if (this.cbLegendary == null) this.cbLegendary = new JCheckBox(); /* 134 */ this.cbLegendary.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "RARITY_ITEM_LEGENDARY")); /* 135 */ this.cbLegendary.setFont(fntCheck); /* */ } /* */ /* */ public void clear() { /* 139 */ this.cbCommon.setSelected(false); /* 140 */ this.cbMagical.setSelected(false); /* 141 */ this.cbRare.setSelected(false); /* 142 */ this.cbEpic.setSelected(false); /* 143 */ this.cbLegendary.setSelected(false); /* */ } /* */ /* */ public void addCriteria(SelectionCriteria criteria) { /* 147 */ criteria.itemRarity = getRarityList(); /* */ } /* */ /* */ public List<String> getRarityList() { /* 151 */ List<String> list = new LinkedList<>(); /* */ /* 153 */ if (this.cbCommon.isSelected()) list.add("Common"); /* 154 */ if (this.cbMagical.isSelected()) list.add("Magical"); /* 155 */ if (this.cbRare.isSelected()) list.add("Rare"); /* 156 */ if (this.cbEpic.isSelected()) list.add("Epic"); /* 157 */ if (this.cbLegendary.isSelected()) list.add("Legendary"); /* */ /* 159 */ return list; /* */ } /* */ } /* Location: C:\game\Grim Dawn\GDStash.jar!\org\gdstas\\ui\select\ItemRarityPane.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
43.047904
143
0.576993
744cff0f9b058389798eb77441e264dfaeebeb94
357
package com.javacourse.examples; import java.math.BigDecimal; public class VarExample { @SuppressWarnings("unused") public static void main(String[] args) { var a = new BigDecimal("10.2"); int t = 20; var b = (t > 10)?"t è maggiore di 10":30; b = 40; System.out.println(b); b = "prova"; System.out.println(b); } }
17.85
44
0.607843
227e679616c4bba5708c2624b702f30473c7653b
1,332
package ghissues; import act.controller.annotation.UrlContext; import act.db.DbBind; import act.db.jpa.JPADao; import act.db.sql.tx.Transactional; import act.util.PropertySpec; import ghissues.gh823.Gh823User; import org.osgl.$; import org.osgl.mvc.annotation.*; import javax.inject.Inject; @UrlContext("823") public class Gh823 extends BaseController { @Inject private JPADao<Integer, Gh823User> userDao; @GetAction("users") public Iterable<Gh823User> list() { return userDao.findAll(); } @GetAction("users/{user}") public Gh823User get(@DbBind Gh823User user) { return user; } @PostAction("users") @PropertySpec("id") public Gh823User createUser(Gh823User user) { return userDao.save(user); } @PostAction("users2") @PropertySpec("id") @Transactional public Gh823User createUser2(Gh823User user) { return userDao.save(user); } @PutAction("users/{user}") public Gh823User update(@DbBind Gh823User user, Gh823User data) { $.merge(data).to(user); return userDao.save(user); } @PutAction("users2/{user}") @Transactional public Gh823User updateWithExplicitTransaction(@DbBind Gh823User user, Gh823User data) { $.merge(data).to(user); return userDao.save(user); } }
23.368421
92
0.671922
ba179e9e4d4d3f17ac723642ef1fb4a32f737b6d
1,590
//| Copyright - The University of Edinburgh 2015 | //| | //| 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 uk.ac.ed.epcc.webapp.servlet.navigation; import uk.ac.ed.epcc.webapp.AppContext; import uk.ac.ed.epcc.webapp.config.FilteredProperties; /** * @author spb * */ public class PageNodeMaker extends AbstractNodeMaker { /** * @param conn */ public PageNodeMaker(AppContext conn) { super(conn); } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.servlet.navigation.NodeMaker#makeNode(java.lang.String, uk.ac.ed.epcc.webapp.config.FilteredProperties) */ @Override public Node makeNode(String name, FilteredProperties props) { return new PageNode(); } }
38.780488
133
0.548428
09fa90e8ba5578a50ee0092abe36d3978043c564
2,139
package com.baomidou.plugin.idea.mybatisx.smartjpa.component.mapping; import com.intellij.psi.PsiAnnotation; import com.intellij.psi.PsiField; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; /** * The type Mybatis plus 2 mapping resolver. */ public class MybatisPlus2MappingResolver extends AbstractMybatisPlusMappingResolver { /** * The constant TABLE_FIELD. */ public static final String TABLE_FIELD = "com.baomidou.mybatisplus.annotations.TableField"; /** * The constant TABLE_NAME. */ public static final String TABLE_NAME = "com.baomidou.mybatisplus.annotations.TableName"; /** * The constant TABLE_ID. */ public static final String TABLE_ID = "com.baomidou.mybatisplus.annotations.TableId"; /** * The constant BASE_MAPPER. */ public static final String BASE_MAPPER = "com.baomidou.mybatisplus.mapper.BaseMapper"; /** * Instantiates a new Mybatis plus 2 mapping resolver. */ public MybatisPlus2MappingResolver() { } @Override protected @NotNull String getTableNameAnnotation() { return TABLE_NAME; } @Override protected @NotNull String getTableFieldAnnotation(@NotNull PsiField field) { String columnName = null; // 获取 mp 的 TableField 注解 PsiAnnotation fieldAnnotation = field.getAnnotation(TABLE_FIELD); if (fieldAnnotation != null) { columnName = getAttributeValue(fieldAnnotation, AbstractMybatisPlusMappingResolver.VALUE); } // 获取 mp 的 id 注解 if (StringUtils.isBlank(columnName)) { PsiAnnotation idAnnotation = field.getAnnotation(TABLE_ID); if (idAnnotation != null) { columnName = getAttributeValue(idAnnotation, AbstractMybatisPlusMappingResolver.VALUE); } } // 获取 jpa 注解 if (StringUtils.isBlank(columnName)) { columnName = getColumnNameByJpaOrCamel(field); } return columnName; } @Override protected String getBaseMapperClassName() { return BASE_MAPPER; } }
30.126761
103
0.673679
54252546a64383d9ce995eba098e9614f7b70efd
2,091
package org.plugin.loreSystem; import java.util.ArrayList; import java.util.List; import org.caveandcliff.Implemenation; import org.api.CustomEnchantment; import org.api.ResponseManager; import org.api.TagWrapper; import org.bukkit.ChatColor; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.plugin.tagSystem.TagManager; public interface LoreAdder { final TagWrapper tagWrapper = TagManager.getInstance().getImplemenation(); //Adds the lore to an item. By default will make it look like vanilla. default ItemStack addLore(ItemStack item, CustomEnchantment ench, int lvl){ if (item.getEnchantments().isEmpty() && tagWrapper.getTags(item).isEmpty()) {item = tagWrapper.addGlow(item);} if (tagWrapper.checkTag(item, ench.getId())) {item = removeLore(item, ench);} ItemMeta meta = item.getItemMeta(); List<String> lore = meta.getLore(); if (lore == null) { lore = new ArrayList<String>(); } lore.add(0, ChatColor.RESET + "" + ChatColor.GRAY + ench.getName() + " " + RomanNumeral.toRoman(lvl)); meta.setLore(lore); item.setItemMeta(meta); return item; } //Searches for the name of the item in the lore and will remove it if an exact match is found. default ItemStack removeLore(ItemStack item, CustomEnchantment ench) { ItemMeta meta = item.getItemMeta(); List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<String>(); int x = -1; for (int i = 0; i < lore.size(); i++) { String string = ChatColor.stripColor(lore.get(i)); string = string.substring(0, string.lastIndexOf(" ")); if (string.equals(ench.getName())) {x = i;} } if (x == -1) { ResponseManager.getInstance().setResponseId(5); return item; } lore.remove(x); meta.setLore(lore); item.setItemMeta(meta); if (tagWrapper.getTags(item).isEmpty()) { if (TagManager.getInstance().getImplemenation().getClass() != Implemenation.class) { if (!item.getEnchantments().isEmpty()) { return item; } } item = tagWrapper.removeGlow(item); } return item; } }
28.643836
112
0.693926
b19081ed585e23628af3dd7c4756a2b3651e8562
1,344
package com.zipcode.justcode.clamfortress.ClamFortress.models.game.models.items.artifacts; import com.zipcode.justcode.clamfortress.ClamFortress.models.game.interfaces.*; import com.zipcode.justcode.clamfortress.ClamFortress.models.game.models.*; import com.zipcode.justcode.clamfortress.ClamFortress.models.game.models.items.*; import com.zipcode.justcode.clamfortress.ClamFortress.models.game.models.managers.*; import com.zipcode.justcode.clamfortress.ClamFortress.models.game.utilities.persistence.*; public class ProjectileEnhancer extends AbstractArtifact implements Unique { public ProjectileEnhancer() { super("Projectile Enhancer", "Upon pickup, set the accuracy of all of your projectile weapons to 100%."); } @Override public void onObtain() { for (AbstractItem item : Database.getCurrentGame().getVillage().getInventory().getItems()) { if (item instanceof Projectile) { Projectile fItem = (Projectile)item; if (fItem.getAccuracy() < 100) { fItem.setAccuracy(100); OutputManager.addToBot("Projectile Enhancer set accuracy of " + item.getName() + " to 100%!"); } } } } @Override public ProjectileEnhancer clone() { return new ProjectileEnhancer(); } }
39.529412
114
0.688988
c77c096da7978746f5a69adef7daf0334147a64d
349
package cn.admin.service; import cn.admin.entity.SystemMenu; import cn.commons.common.PublicResultJosn; public interface MenuService { public PublicResultJosn add(SystemMenu menu); public PublicResultJosn delete(Long id); public PublicResultJosn update(SystemMenu menu); public PublicResultJosn select(SystemMenu menu); }
20.529412
50
0.773639
3b84c6a8b65ea9babf4beb7fe28976fa7bb0f549
4,794
package hu.elte.animaltracker.model.tracking; import hu.elte.animaltracker.model.zones.ZoneUnit; import ij.IJ; import ij.ImagePlus; import ij.io.FileInfo; import ij.io.TiffDecoder; import ij.plugin.AVI_Reader; import ij.plugin.FileInfoVirtualStack; import ij.plugin.FolderOpener; import ij.process.ColorProcessor; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * This is a configuration class which contains any necessary information about * a 2D single target tracking process. You can save and load it by using the * Serializable interface. * * This class is useful if when analyzing a large number of configured videos * without manual interaction. (Batch mode) * * */ public class TrackingTask implements Serializable { private static final long serialVersionUID = -4659181866943835308L; protected transient ImagePlus imp; protected CoreTracker coreTracker; protected ObjectLocation[] point; protected int firstFrame, lastFrame; protected ZoneUnit trackingArea; public TrackingTask(ImagePlus imp, CoreTracker coreTracker) { super(); this.imp = imp; this.coreTracker = coreTracker; lastFrame = imp.getStackSize(); } private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); String path = imp.getOriginalFileInfo().directory + File.separator + imp.getOriginalFileInfo().fileName; oos.writeObject(path); // is virtual? oos.writeBoolean(imp.getStack().isVirtual()); // is color? oos.writeBoolean(imp.getProcessor() instanceof ColorProcessor); } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); String path = (String) ois.readObject(); File file = new File(path); boolean isVirtual = ois.readBoolean(); boolean isColor = ois.readBoolean(); FileInfo info = new FileInfo(); info.directory = file.getParent(); info.fileName = file.getName(); if (file.isDirectory()) { FolderOpener opener = new FolderOpener(); opener.openAsVirtualStack(isVirtual); imp = opener.openFolder(file.getPath()); imp.setFileInfo(info); return; } else if (file.getName().contains(".avi")) { AVI_Reader avi = new AVI_Reader(); imp = new ImagePlus(file.getName(), avi.makeStack(file.getPath(), 1, -1, isVirtual, !isColor, false)); imp.setFileInfo(info); return; } else if (file.getName().contains(".tif") && isVirtual) { TiffDecoder td = new TiffDecoder(file.getParent(), file.getName()); FileInfo[] infos; IJ.showStatus("Decoding TIFF header..."); try { infos = td.getTiffInfo(); } catch (IOException e) { String msg = e.getMessage(); if (msg == null || msg.equals("")) msg = "" + e; IJ.log("TiffDecoder: " + msg); return; } FileInfoVirtualStack vs = new FileInfoVirtualStack(infos[0], false); imp = new ImagePlus(file.getName(), vs); imp.setFileInfo(info); return; } imp = new ImagePlus(file.getPath()); imp.setFileInfo(info); } /** * Returns the number of the starting frame. * * @return one-based frame index. */ public int getFirstFrame() { return firstFrame; } /** * Sets the starting frame. * * @param firstFrame * one-based frame index. */ public void setFirstFrame(int firstFrame) { this.firstFrame = firstFrame; } /** * Returns the number of the end frame. * * @return one-based frame index. */ public int getLastFrame() { return lastFrame; } /** * Sets the end frame. * * @param lastFrame * one-based frame index. */ public void setLastFrame(int lastFrame) { this.lastFrame = lastFrame; } /** * Returns the array of ObjectLocations. * * @return */ public ObjectLocation[] getPoint() { return point; } /** * Sets the array of ObjectLocations. * * @param point */ public void setPoint(ObjectLocation[] point) { this.point = point; } /** * Returns the video recording. * * @return */ public ImagePlus getImage() { return imp; } /** * Returns the CoreTracker object. * * @return */ public CoreTracker getCoreTracker() { return coreTracker; } /** * Returns the tracking area. * * @return */ public ZoneUnit getTrackingArea() { return trackingArea; } /** * Sets the tracking area. * * @param trackingArea */ public void setTrackingArea(ZoneUnit trackingArea) { coreTracker.getThresholder().setMask(trackingArea, imp.getWidth(), imp.getHeight()); this.trackingArea = trackingArea; } /** * Sets the CoreTracker object. * * @param coreTracker */ public void setCoreTracker(CoreTracker coreTracker) { this.coreTracker = coreTracker; } }
23.048077
79
0.690029
11efbac57732bd818844b21e6d6ca280b5800a22
846
package nablarch.test.core.db; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.math.BigDecimal; /** * BigDecimal型をPKに持つテーブル。 */ @Entity @Table(name = "BIG_DECIMAL_TABLE") public class BigDecimalTable { public BigDecimalTable() { } public BigDecimalTable(BigDecimal decimalPkCol, BigDecimal decimalCol) { this.decimalPkCol = decimalPkCol; this.decimalCol = decimalCol; } public BigDecimalTable(BigDecimal decimalPkCol) { this.decimalPkCol = decimalPkCol; } @Id @Column(name = "DECIMAL_PK_COL", precision = 15, scale = 10, nullable = false) public BigDecimal decimalPkCol; @Column(name = "DECIMAL_COL", precision = 15, scale = 10, nullable = true) public BigDecimal decimalCol; }
24.171429
82
0.713948
2f8a26e05477461eb60cf9476c86a7d6cc5e81ad
4,852
package org.horrgs.twitterbot.commands; import com.rosaloves.bitlyj.Bitly; import com.rosaloves.bitlyj.Url; import org.horrgs.twitterbot.HorrgsTwitter; import org.horrgs.twitterbot.api.FileManager; import org.horrgs.twitterbot.api.Site; import org.horrgs.twitterbot.io.NewsJSON; import org.json.JSONException; import org.json.JSONObject; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterException; import java.net.URL; /** * Created by horrgs on 9/18/15. */ public class News implements SubCommand, NewsJSON { Site site = new Site("https://ajax.googleapis.com/ajax/services/search/news?v=1.0&"); @Override public void onCommand(Status status, String[] args) { StatusUpdate statusUpdate = new StatusUpdate(""); long r1 = status.getId(); String[] topics = {"h", "w", "b", "n", "t", "el", "p", "e", "s", "m"}; try { if (args.length == 1) { statusUpdate = new StatusUpdate("@" + status.getUser().getScreenName() + " " + "@" + status.getUser().getScreenName() + " " + "You gave no argument.\nAn argument is required.\n%news <topic> [site]"); statusUpdate.setInReplyToStatusId(r1); HorrgsTwitter.twitter.updateStatus(statusUpdate); } else if (args.length == 2 && args[1].length() <= 2) { boolean contains = false; char topic = args[1].toLowerCase().charAt(0); for (int x = 0; x < topics.length; x++) { if (topics[x].equals(String.valueOf(topic))) { contains = true; break; } } NewsJSON[] newsJSON = getArticles("topic=", String.valueOf(topic)); if (contains) { for (int x = 0; x < newsJSON.length; x++) { try { String url = newsJSON[x].getStringURL(x); //Url url = Bitly.as(FileManager.getInstance().getKey("bitlyApiUsername"), FileManager.getInstance().getKey("bitlyApiKey")).call(Bitly.shorten(newsJSON[x].getStringURL(x))); statusUpdate = new StatusUpdate("@" + status.getUser().getScreenName() + " " + newsJSON[x].getTitle(x) + " " + url); statusUpdate.setInReplyToStatusId(r1); HorrgsTwitter.twitter.updateStatus(statusUpdate); Thread.sleep(3000); } catch (InterruptedException ex) { ex.printStackTrace(); } } } else { statusUpdate = new StatusUpdate("@" + status.getUser().getScreenName() + " " + "Error in executing \"news\" command.\nYou gave an invalid topic."); statusUpdate.setInReplyToStatusId(r1); HorrgsTwitter.twitter.updateStatus(statusUpdate); } } } catch (TwitterException ex) { ex.printStackTrace(); } } @Override public String getHelp() { return "Get's the news on the specified topic from the (optional) specified source."; } @Override public String getPermission() { return "tweetbot.user.news"; } @Override public String getTitle(int x) { return site.get(getJSONObject(x), "title").toString().replace("&#39;", "'"); } @Override public String getStringURL(int x) { return site.get(getJSONObject(x), "unescapedUrl"); } @Override public String getPublisher(int x) { return site.get(getJSONObject(x), ""); } @Override public void setTitle(String title) { } @Override public String setURL(String url) { return null; } @Override public String setURL(URL url) { return null; } public NewsJSON[] getArticles(String args, String val) { NewsJSON[] newsJSON = new NewsJSON[4]; site.startJson(false, args, val); try { Thread.sleep(3000); for(int x = 0; x < 4; x++) { try { setJSONObject(x, site.getJsonObject().getJSONObject("responseData").getJSONArray("results").getJSONObject(x)); newsJSON[x] = this; } catch (JSONException ex) { ex.printStackTrace(); } } }catch (InterruptedException ex) { ex.printStackTrace(); } return newsJSON; } private JSONObject[] jsonObject = new JSONObject[4]; public JSONObject getJSONObject(int x) { return jsonObject[x]; } public void setJSONObject(int obj, JSONObject jsonObject) { this.jsonObject[obj] = jsonObject; } }
35.940741
215
0.552762
03ec602bb00756a3bf9af0588b7d661fc6e1914d
1,311
package usedclass; /*StringBuffer类的初使用*/ public class Example27 { public static void main(String[] args) { System.out.println("1.添加--------------------"); add(); System.out.println("2.修改--------------------"); update(); System.out.println("3.删除--------------------"); delete(); } //添加 public static void add(){ StringBuffer str = new StringBuffer(); str.append("ABC"); //字符串结尾添加 "ABC" System.out.println("append添加结果:" + str); str.insert(3,"DE"); //指定位置添加 System.out.println("insert添加结果:" + str); } // 修改 public static void update(){ StringBuffer str = new StringBuffer("ABAAA"); str.setCharAt(2,'C'); //修改指定位置的数据 System.out.println("修改指定位置字符结果:" + str); str.replace(3,5,"DE"); //修改指定字段的数据 System.out.println("替换指定位置字符(串)结果:" + str); str.reverse(); System.out.println("字符串反转结果:" + str); } //删除 public static void delete(){ StringBuffer str = new StringBuffer("ABCDEFG"); str.delete(3,7); System.out.println("删除指定位置结果:" + str); str.deleteCharAt(2); System.out.println("删除指定位置结果:" + str); str.delete(0,str.length()); System.out.println("清空缓冲区结果:" + str); } }
28.5
55
0.527079
fbedaa0ebb49a0fde802d99215eed8876f8bf89d
366
package ru.mydesignstudio.spring.core.injection.with.proxy; public class ParentBean { private ChildBean childBean; public void setChildBean(ChildBean childBean) { this.childBean = childBean; } public ChildBean getChildBean() { return childBean; } public int doSomething() { return childBean.doSomething(); } }
20.333333
59
0.674863
bc7ac6f0fc4be4099c79e79ee258c2a9da6ec3e4
2,173
/** * Copyright 2005-2019 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.krad.datadictionary; import org.kuali.rice.krad.datadictionary.parse.BeanTag; import org.kuali.rice.krad.document.Document; import org.kuali.rice.krad.document.TransactionalDocumentAuthorizerBase; import org.kuali.rice.krad.document.TransactionalDocumentBase; import org.kuali.rice.krad.document.TransactionalDocumentPresentationControllerBase; /** * Data dictionary entry class for {@link org.kuali.rice.krad.document.TransactionalDocument}. * * @author Kuali Rice Team ([email protected]) */ @BeanTag(name = "transactionalDocumentEntry") public class TransactionalDocumentEntry extends DocumentEntry { private static final long serialVersionUID = 5746921563371805425L; /** * Constructs this {@code TransactionalDocumentEntry} with document presentation and authorization defaults. */ public TransactionalDocumentEntry() { super(); setDocumentClass(getStandardDocumentBaseClass()); documentAuthorizerClass = TransactionalDocumentAuthorizerBase.class; documentPresentationControllerClass = TransactionalDocumentPresentationControllerBase.class; } /** * Returns the default base class for a {@link org.kuali.rice.krad.document.TransactionalDocument}. * * @return the default base class for a {@link org.kuali.rice.krad.document.TransactionalDocument} */ public Class<? extends Document> getStandardDocumentBaseClass() { return TransactionalDocumentBase.class; } }
40.240741
113
0.746434
e7f9e3b1f40729328a8b59b44b14dcd956f0f1c3
558
package cloud.unionj.model; import lombok.Data; /** * @author created by wubin * @version v0.0.1 * description: cloud.unionj.model * date:2021/6/30 */ @Data public class Doc { private String api; private String createAt; private String service; private String version; private Git git; @Data public static class Git { private String commitId; private String commitIdAbbr; private String branch; private String commitAt; private String commitUser; private String closestTag; private String fullMessage; } }
18.6
34
0.709677
d26dfe68526742579d51f3ba0a8c809d43127ea0
20,573
package engine; import java.io.IOException; import java.util.List; import java.util.Set; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import com.cucumber.listener.Reporter; import pages.CQLWorkspacepage; import pages.LoginPageUMLS; public class ActionEngine extends TestEngine { private int count = 0; public boolean IsElementexistwait(By by, String elementName) throws Exception { boolean retValue = false; try { count++; Thread.sleep(1000); if (((WebElement) by).getSize() != null) { retValue = true; System.out.println("The element: '" + elementName + "' is displayed successfully."); } } catch (Exception e) { if (count >= 5) { throw new Exception("Element Not found or Element state not ready to perform action"); } else { IsElementExists(by, elementName); } } return retValue; } public void search(By by, String nameToSearch, String elementName) throws Exception{ try { List<WebElement> searchList=driver.findElements(by); Actions act=new Actions(driver); for (WebElement searchDefi:searchList){ if (searchDefi.getText().equals(nameToSearch)){ act.moveToElement(searchDefi).doubleClick().perform(); } } Reporter.addStepLog("Value selected: "+ elementName); } catch (Exception e) { Reporter.addStepLog("Element Not found or Element state not ready to perform action"); throw new Exception ("Element Not found or Element state not ready to perform action"); } } public void waitForElemenent( By element, String elementName) throws Exception{ int waitTime = Integer.parseInt( config.getProperty("ElementSyncTimeOut")); try{ WebDriverWait wait = new WebDriverWait(driver, waitTime); wait.until(ExpectedConditions.visibilityOf(driver.findElement(element))); Reporter.addStepLog("Waited For element for "+waitTime+" Sec"); } catch(Exception e){ Reporter.addStepLog("Wait element Exception"); throw new Exception ("Wait element Exception"); } } public void waitForElementToBClickable( By element, String elementName) throws Exception{ int waitTime = Integer.parseInt( config.getProperty("ElementSyncTimeOut")); try{ WebDriverWait wait = new WebDriverWait(driver, waitTime); wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(element))); Reporter.addStepLog("Waited For element for "+waitTime+" Sec"); } catch(Exception e){ Reporter.addStepLog("Wait element Exception"); throw new Exception ("Wait element Exception"); } } public void FieldDisabled(By by,String elementName)throws Exception{ try { if (driver.findElement(by).isDisplayed()) { Reporter.addStepLog("The '"+elementName+"' is disabled"); } } catch(Exception e) { Reporter.addStepLog("The '"+elementName+"' is enabled"); } } public void tooltip(By by,String elementName,String getattribute)throws Exception{ try { WebElement element = driver.findElement(by); String tooltip = element.getAttribute(getattribute); Reporter.addStepLog("The '"+elementName+"' Tool tip read as "+tooltip); Thread.sleep(1000); } catch(Exception e) { Reporter.addStepLog("Element Not found or Element state not ready to perform action"); throw new Exception ("Element Not found or Element state not ready to perform action"); } } public void buttonDisabled(By by)throws Exception{ try { if (!driver.findElement(by).isEnabled()) { Reporter.addStepLog("Button is disabled"); } }catch(Exception e){ Reporter.addStepLog("Button is enabled"); throw new Exception ("Element Not found or Element state not ready to perform action"); } } public void verifyText(By by, String expected, String elementName) throws Exception{ try { String actual=driver.findElement(by).getText(); if (actual.equals(expected)){ Reporter.addStepLog("Successfully displayed: "+elementName); } else { Reporter.addStepLog("Expected Text not displayed: "+elementName); } } catch (Exception e) { Reporter.addStepLog("Display was unsuccessful: "+elementName); throw new Exception ("Element Not found or Element state not ready to perform action"); } } public void clickKeyboardControl(By by, String elementName) throws Exception{ try { WebElement element = driver.findElement(by); element.sendKeys(Keys.ENTER); Reporter.addStepLog("Clicked on the element: "+elementName+ " Using keyboard control successfully"); Thread.sleep(2000); } catch (Exception e) { Reporter.addStepLog("Element Not found or Element state not ready to perform action"); throw new Exception ("Element Not found or Element state not ready to perform action"); } } public void saveDefiOrParaOrFunc(By by, String elementName) throws Exception{ try { click(by, "Click save icon"); } catch (Exception e) { throw new Exception ("Element Not found or Element state not ready to perform action"); } } public void verifyAttributeValue(By by, String attribute, String attributeValue, String elementName) throws Exception{ try { driver.findElement(by).getAttribute(attribute).equalsIgnoreCase(attributeValue); // extentReportsLog(true, String.format("Verified: '%s'", elementName)); } catch (Exception e) { // extentReportsLog(false, String.format("Fail: '%s'", elementName)); throw new Exception ("Element Not found or Element state not ready to perform action"); } } public void gotoInsertOptionAttributes() throws Throwable { selectByVisibleText(CQLWorkspacepage.dropdownItemType, "Attributes", "Item Type Dropdown"); Thread.sleep(2000); } public void selectInsert(By by, String value, String elementName) throws Exception{ try { List <WebElement> dropdown=driver.findElements(by); int sz=dropdown.size()-1; Select val=new Select(dropdown.get(sz)); val.selectByValue(value); // extentReportsLog(true, String.format("Value selected: '%s'", elementName)); } catch (Exception e) { // extentReportsLog(false, String.format("Value not selected: '%s'", elementName)); throw new Exception ("Element Not found or Element state not ready to perform action"); } } public void verifyDisabled(By by, String elementName) throws Exception{ try { List <WebElement> dropdown=driver.findElements(by); int sz=dropdown.size()-1; boolean status=dropdown.get(sz).isEnabled(); if (status==false) { // extentReportsLog(true, String.format("dropdown: '%s' is disabled", elementName)); } } catch (Exception e) { // extentReportsLog(false, String.format("dropdown: '%s' is enabled", elementName)); throw new Exception ("Element Not found or Element state not ready to perform action"); } } public void closeAttribute(By by, String elementName) throws Exception{ try { click(by, "Close the Attribute"); // extentReportsLog(true, String.format("Value selected: '%s'", elementName)); } catch (Exception e) { // extentReportsLog(false, String.format("Value not selected: '%s'", elementName)); throw new Exception ("Element Not found or Element state not ready to perform action"); } } public void click(By by, String elementName) throws Exception{ try { driver.findElement(by).click(); Reporter.addStepLog("Clicked on the element: "+elementName+ " successfully"); } catch (Exception e) { Reporter.addStepLog("Failed to click on the element: "+elementName+ " successfully"); throw new Exception ("Element Not found or Element state not ready to perform action"); } } /** * Method Name: Jclick * Purpose: click on element * @throws Exception * */ public void jclick(By by, String elementName) throws Exception{ try { // waitForElementToBClickable(by, elementName); JavascriptExecutor js = (JavascriptExecutor)driver; WebElement element=driver.findElement(by); js.executeScript("arguments[0].click();", element); } catch (Exception e) { throw new Exception ("Element Not found or Element state not ready to perform action"); } } /** * Javascript click. * * @param element the element * @throws Exception */ public void jsClick(By by, String elementName) throws Exception{ try{ waitForElementToBClickable(by, elementName); WebElement element = driver.findElement(by); JavascriptExecutor executor = (JavascriptExecutor)driver; executor.executeScript("arguments[0].click();", element); }catch(Exception e){ throw new Exception ("Element Not found or Element state not ready to perform action"); } } /** * Method Name: clear * Purpose: clear method remove existing text in text area fields * @param by * @param text * @param elementName * @throws Exception */ public void clear(By by, String elementName) throws Exception{ try { driver.findElement(by).clear(); Reporter.addStepLog("Clear text from field "+elementName); } catch (Exception e) { Reporter.addStepLog("Either the element is not found or element state is not ready perforam action"); throw new Exception ("Element Not found or element state not ready to perform action"); } } /** * Method Name: type * Purpose: sends the given text * @throws Exception * */ public void type(By by, String text, String elementName) throws Exception{ try { driver.findElement(by).sendKeys(text); Reporter.addStepLog("Entered the text: '"+text +"' in the element: '"+elementName+"' successfully."); } catch (Exception e) { Reporter.addStepLog("Failed to enter the text: '"+text +"' in the element: '"+elementName+"'."); throw new Exception ("Element Not found or Element state not not ready to perform action"); } } /** * Method Name: waitForVisibility * Purpose: waits for the visibility of given element for the specified time * @throws InterruptedException * @throws IOException * */ public void waitForVisibility(By by, String elementName, int timeOut) throws IOException{ WebDriverWait wait = new WebDriverWait(driver, timeOut); try { wait.until(ExpectedConditions.visibilityOfElementLocated(by)); // extentReportsLog(true, "Waited for visibility of the element: '"+elementName+"' and is found successfully."); } catch (Exception e) { // extentReportsLog(false, "Failed to find the element: '"+elementName+"'. " + e.getMessage()); } } public boolean selectByVisibleText(By locator, String value, String locatorName) throws Throwable { boolean flag = false; try { WebElement dropDownListBox = driver.findElement(locator); Select clickThis = new Select(dropDownListBox); clickThis.selectByVisibleText(value); flag = true; // extentReportsLog(true, "Selected the value: '"+value+"' for the element: '"+locatorName+"' successfully."); return true; } catch (Exception e) { // extentReportsLog(false, "Failed to select the value: '"+value+"' for the element: '"+locatorName+"' "+ e.getMessage()); return false; } finally { if (flag == false) { /*this.reporter.failureReport("Select", "'"+value+"'" + "is Not Select from the DropDown " + locatorName);*/ // throw new ElementNotFoundException("", "", ""); } else if (flag == true) { /*this.reporter.SuccessReport("Select", "'"+value+"'" + " is Selected from the DropDown " + locatorName);*/ } } } public boolean selectByIndex(By locator, int value, String locatorName) throws Throwable { boolean flag = false; try { WebElement dropDownListBox = driver.findElement(locator); Select clickThis = new Select(dropDownListBox); clickThis.selectByIndex(value); flag = true; // extentReportsLog(true, "Selected the value: '"+value+"' for the element: '"+locatorName+"' successfully."); return true; } catch (Exception e) { // extentReportsLog(false, "Failed to select the value: '"+value+"' for the element: '"+locatorName+"' "+ e.getMessage()); return false; } finally { if (flag == false) { /*this.reporter.failureReport("Select", "'"+value+"'" + "is Not Select from the DropDown " + locatorName);*/ // throw new ElementNotFoundException("", "", ""); } else if (flag == true) { /*this.reporter.SuccessReport("Select", "'"+value+"'" + " is Selected from the DropDown " + locatorName);*/ } } } /** * Method Name: assertElementExists * Purpose: Assert for element * @param by * @param elementName * @throws IOException */ public void assertElementExists(By by, String elementName) throws IOException{ try { driver.findElement(by).isDisplayed(); // extentReportsLog(true, "Expected element is visibile: Element:"+elementName); } catch (Exception e) { // extentReportsLog(false, "Expected element is NOT visibile Element:"+elementName); } } /** * Method Name: IsElementExists * Purpose: Method verify is element IsDisplyed and return true /false * @param by * @param elementName * @return * @throws IOException */ public boolean IsElementExists(By by, String elementName) throws IOException{ try { waitForElementToBClickable(by, elementName); if(driver.findElement(by).isDisplayed()); Reporter.addStepLog("The element: '"+elementName + "' is displayed successfully."); return true; } catch (Exception e) { Reporter.addStepLog("Failed to find the element: '" +elementName+"'."); return false; } } /** * Method Name: IsElementExists * Purpose: Method verify is element IsDisplyed and return true /false * @param by * @param elementName * @return * @throws Exception */ public void waitForElementPresent(By by, String elementName) throws Exception{ for (int i = 0; i < 60; i++) { if(driver.findElements(by).size()>0){ break; } else{ Thread.sleep(1000); System.out.println("No element is found trying again..." + elementName); } if(i==59){ // extentReportsLog(false, "Expected element(s) NOT found"); throw new Exception("Expected element(s) NOT found"); } } } /** * Method Name: getElementAttributeValue * Purpose: Method return element's specified attribute value; * @param by * @param elementName * @param attribute * @return String element attribute value * @throws Exception */ /*public String getElementAttributeValue(By by, String elementName, String attribute) throws Exception{ try { String attvalue= driver.findElement(by).getAttribute(attribute); extentReportsLog(true,"Get Attribute value form Element"); return attvalue; } catch (Exception e) { extentReportsLog(false, "Either element or Specified attribute NOT exists"); throw new Exception ("Either element or Specified attribute NOT exists"); } }*/ public String getElementAttributeValue(By by, String attribute) throws Exception{ try { String attvalue= driver.findElement(by).getAttribute(attribute); // extentReportsLog(true,"Get Attribute value form Element"); return attvalue; } catch (Exception e) { // extentReportsLog(false, "Either element or Specified attribute NOT exists"); throw new Exception ("Either element or Specified attribute NOT exists"); } } public void switchToSpecificWindowAndVerifyElement( String windowTitle,By elementToVerify, String elementName) throws Exception{ try { Set<String>allWindows= driver.getWindowHandles(); for(String child_wndow : allWindows){ driver.switchTo().window(child_wndow); // extentReportsLog(true,"Navigated to the window: '"+windowTitle+"' successfully."); if(driver.getTitle().contains(windowTitle)){ waitForElemenent(elementToVerify, elementName); IsElementExists(elementToVerify, elementName); } } driver.close(); } catch (Exception e) { // extentReportsLog(false, "Failed to navigate to window and verify the element: '"+ elementName+"'."); throw new Exception ("Either element or Specified attribute NOT exists"); } } // public void extentReportsLog(boolean status, // String messageString) throws IOException{ // if (status) // { // if (alwasyTakeScreenShot) // { // logger.log(LogStatus.PASS, // messageString + // logger.addScreenCapture(screenShotForPass(driver))); // }else{ // logger.log(LogStatus.PASS, messageString); // } // } // // else{ // logger.log(LogStatus.FAIL, // messageString /*+ // logger.addScreenCapture(screenShotForPass(driver))*/); //TODO: // } // } public void hoverOn(By by, String elementName) throws Exception{ try { waitForElementToBClickable(by, elementName); Actions actions = new Actions(driver); actions.moveToElement(driver.findElement(by)).build().perform(); // extentReportsLog(true, "Hovered on the element: '"+elementName+"' successfully."); } catch (Exception e) { // extentReportsLog(false, "Failed to hover on the element: '"+elementName+"'."); throw new Exception ("Element Not found or Element state not not ready to perform action"); } } /** * Method Name: searchMeasure * Purpose: Search a Measure * Created by: Gayathri Sathyanarayana * @throws Exception * */ public void searchMeasure(By by, String measureName, String elementName) throws Exception{ try { waitForElementToBClickable(by, elementName); type(by, measureName, elementName); // click(by, elementName); // extentReportsLog(true, String.format("Entered Measure name and displays the Measure: '%s' successfully.", measureName)); } catch (Exception e) { // extentReportsLog(false, String.format("Failed to search the measure: '%s'.", measureName)); throw new Exception ("Element Not found or Element state not ready to perform action"); } } /** * Method Name: clickMeasure * Purpose: Open a Measure * Created by: Gayathri Sathyanarayana * @throws Exception * */ public void clickMeasure(By by, By searchBy, String measureName, String elementName) throws Exception{ try { searchMeasure(by, measureName, elementName); click(searchBy, elementName); // extentReportsLog(true, String.format("Measure is opened : '%s' successfully.", measureName)); } catch (Exception e) { // extentReportsLog(false, String.format("Failed to open the measure: '%s'.", measureName)); throw new Exception ("Element Not found or Element state not ready to perform action"); } } /** * Method Name: checkEraserIcon * Purpose: Check for the presence of the eraser icon * Created by: Gayathri Sathyanarayana * @throws Exception * */ public void checkEraserIcon(By by, String elementName) throws Exception{ try { Boolean status =driver.findElement(by).isEnabled(); if (!status) {} // extentReportsLog(true, String.format("Eraser Icon is disabled in: '%s'", elementName)); } catch (Exception e) { // extentReportsLog(false, String.format("Eraser Icon is enabled in: '%s'", elementName)); throw new Exception ("Element Not found or Element state not ready to perform action"); } } /** * Method Name: checkEraserIcon * Purpose: Check for the presence of the eraser icon * Created by: Gayathri Sathyanarayana * @throws Exception * */ public void assertText(By by, String expected, String elementName) throws Exception{ try { Assert.assertEquals(driver.findElement(by).getText(), expected); // extentReportsLog(true, String.format("Verified: '%s'", elementName)); } catch (Exception e) { // extentReportsLog(false, String.format("Fail: '%s'", elementName)); throw new Exception ("Element Not found or Element state not ready to perform action"); } } }
32.969551
129
0.678268
0fb7decd850b7969266a3c4ddd4c32b58d3379b7
107
/** * Classes which implement modules of the gui. */ package org.optimizationBenchmarking.gui.modules;
26.75
49
0.747664
950e112b3ae4149c292399cd540fa76480343b9e
1,480
package iudx.ingestion.pipeline.redis; import static iudx.ingestion.pipeline.common.Constants.REDIS_SERVICE_ADDRESS; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.client.WebClientOptions; import io.vertx.serviceproxy.ServiceBinder; public class RedisVerticle extends AbstractVerticle { private static final Logger LOGGER = LogManager.getLogger(RedisVerticle.class); private RedisService redisService; private ServiceBinder binder; private MessageConsumer<JsonObject> consumer; private RedisClient client; @Override public void start() throws Exception { new RedisClient(vertx, config()).start() .onSuccess(handler -> { client = handler; redisService = new RedisServiceImpl(client); binder = new ServiceBinder(vertx); consumer = binder .setAddress(REDIS_SERVICE_ADDRESS) .register(RedisService.class, redisService); }).onFailure(handler -> { LOGGER.error("failed to start redis client"); }); WebClientOptions options = new WebClientOptions(); options.setTrustAll(true) .setVerifyHost(false) .setSsl(true); } @Override public void stop() { if (client != null) { client.close(); } binder.unregister(consumer); } }
26.909091
81
0.706081
520a63b1cc6be3dfebe288ad907cf44ea3e35cfb
4,119
package gtm; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * reference to a list of stations included in the fare * */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "carrier", "code", "name" }) public class FareReferenceStationSet { /** * RICS company code or the upcoming compatible ERA company code. In case proprietary codes are used on a bilateral base the codes must have at least 5 positions and start with x * (Required) * */ @JsonProperty("carrier") @JsonPropertyDescription("RICS company code or the upcoming compatible ERA company code. In case proprietary codes are used on a bilateral base the codes must have at least 5 positions and start with x") private String carrier; /** * * (Required) * */ @JsonProperty("code") private String code; @JsonProperty("name") private String name; /** * RICS company code or the upcoming compatible ERA company code. In case proprietary codes are used on a bilateral base the codes must have at least 5 positions and start with x * (Required) * */ @JsonProperty("carrier") public String getCarrier() { return carrier; } /** * RICS company code or the upcoming compatible ERA company code. In case proprietary codes are used on a bilateral base the codes must have at least 5 positions and start with x * (Required) * */ @JsonProperty("carrier") public void setCarrier(String carrier) { this.carrier = carrier; } /** * * (Required) * */ @JsonProperty("code") public String getCode() { return code; } /** * * (Required) * */ @JsonProperty("code") public void setCode(String code) { this.code = code; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public void setName(String name) { this.name = name; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(FareReferenceStationSet.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('['); sb.append("carrier"); sb.append('='); sb.append(((this.carrier == null)?"<null>":this.carrier)); sb.append(','); sb.append("code"); sb.append('='); sb.append(((this.code == null)?"<null>":this.code)); sb.append(','); sb.append("name"); sb.append('='); sb.append(((this.name == null)?"<null>":this.name)); sb.append(','); if (sb.charAt((sb.length()- 1)) == ',') { sb.setCharAt((sb.length()- 1), ']'); } else { sb.append(']'); } return sb.toString(); } @Override public int hashCode() { int result = 1; result = ((result* 31)+((this.name == null)? 0 :this.name.hashCode())); result = ((result* 31)+((this.carrier == null)? 0 :this.carrier.hashCode())); result = ((result* 31)+((this.code == null)? 0 :this.code.hashCode())); return result; } @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other instanceof FareReferenceStationSet) == false) { return false; } FareReferenceStationSet rhs = ((FareReferenceStationSet) other); return ((((this.name == rhs.name)||((this.name!= null)&&this.name.equals(rhs.name)))&&((this.carrier == rhs.carrier)||((this.carrier!= null)&&this.carrier.equals(rhs.carrier))))&&((this.code == rhs.code)||((this.code!= null)&&this.code.equals(rhs.code)))); } }
30.286765
265
0.574654
6ac47aa26fa10ab99bd07b1dfc89c4a0b8b8fcb1
2,546
/* * MIT License * * Copyright (c) 2020-present Cloudogu GmbH and Contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package sonia.scm.api.v2.resources; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import sonia.scm.plugin.Extension; import sonia.scm.repository.GitRepositoryHandler; import sonia.scm.repository.NamespaceAndName; import sonia.scm.repository.RepositoryManager; import sonia.scm.web.AbstractRepositoryJsonEnricher; import javax.inject.Inject; import javax.inject.Provider; @Extension public class GitRepositoryConfigEnricher extends AbstractRepositoryJsonEnricher { private final Provider<ScmPathInfoStore> scmPathInfoStore; private final RepositoryManager manager; @Inject public GitRepositoryConfigEnricher(Provider<ScmPathInfoStore> scmPathInfoStore, ObjectMapper objectMapper, RepositoryManager manager) { super(objectMapper); this.scmPathInfoStore = scmPathInfoStore; this.manager = manager; } @Override protected void enrichRepositoryNode(JsonNode repositoryNode, String namespace, String name) { if (GitRepositoryHandler.TYPE_NAME.equals(manager.get(new NamespaceAndName(namespace, name)).getType())) { String repositoryConfigLink = new LinkBuilder(scmPathInfoStore.get().get(), GitConfigResource.class) .method("getRepositoryConfig") .parameters(namespace, name) .href(); addLink(repositoryNode, "configuration", repositoryConfigLink); } } }
41.064516
137
0.778476
7727b70ba0062cbb9db6d3d446fdeeba33b007ea
2,060
package org.infobip.prometheus.prtgexporter.prtg; // special thanks to 'rees' from https://stackoverflow.com/a/52244937 // since this is from Stack Overflow in its entirety, this specific library // shall be licensed under the CC-BY-SA, separate from the Apache2 license // used for the rest of the project import java.io.IOException; import java.io.InputStream; public class TokenReplacingStream extends InputStream { private final InputStream source; private final byte[] oldBytes; private final byte[] newBytes; private int tokenMatchIndex = 0; private int bytesIndex = 0; private boolean unwinding; private int mismatch; private int numberOfTokensReplaced = 0; public TokenReplacingStream(InputStream source, byte[] oldBytes, byte[] newBytes) { assert oldBytes.length > 0; this.source = source; this.oldBytes = oldBytes; this.newBytes = newBytes; } @Override public int read() throws IOException { if (unwinding) { if (bytesIndex < tokenMatchIndex) { return oldBytes[bytesIndex++]; } else { bytesIndex = 0; tokenMatchIndex = 0; unwinding = false; return mismatch; } } else if (tokenMatchIndex == oldBytes.length) { if (bytesIndex == newBytes.length) { bytesIndex = 0; tokenMatchIndex = 0; numberOfTokensReplaced++; } else { return newBytes[bytesIndex++]; } } int b = source.read(); if (b == oldBytes[tokenMatchIndex]) { tokenMatchIndex++; } else if (tokenMatchIndex > 0) { mismatch = b; unwinding = true; } else { return b; } return read(); } @Override public void close() throws IOException { source.close(); } public int getNumberOfTokensReplaced() { return numberOfTokensReplaced; } }
27.837838
87
0.585922
36f48ac697cd8bfd805b53e7b56454a2752aa067
975
package com.espressif.iot.action.device.espbutton; import com.espressif.iot.command.device.espbutton.EspCommandEspButtonGroupCreate; import com.espressif.iot.command.device.espbutton.IEspCommandEspButtonGroupCreate; import com.espressif.iot.device.IEspDevice; import com.espressif.iot.espbutton.BEspButton; import com.espressif.iot.espbutton.IEspButtonGroup; public class EspActionEspButtonGroupCreate implements IEspActionEspButtonGroupCreate { @Override public IEspButtonGroup doActionEspButtonCreateGroup(IEspDevice inetDevice, String buttonMac) { IEspCommandEspButtonGroupCreate command = new EspCommandEspButtonGroupCreate(); long groupId = command.doCommandEspButtonCreateGroup(inetDevice, buttonMac); if (groupId > 0) { IEspButtonGroup group = BEspButton.getInstance().allocEspButtonGroup(); group.setId(groupId); return group; } return null; } }
34.821429
96
0.747692
98e04f3091642c7c1ff2a7b44fcbe4148efc22b1
5,738
package configgen.genjava.code; import configgen.gen.LangSwitch; import configgen.genjava.*; import configgen.util.CachedIndentPrinter; import configgen.value.AllValue; import java.util.Map; final class GenConfigCodeSchema { static void generate(AllValue vdb, LangSwitch ls, CachedIndentPrinter ps) { ps.println("package " + Name.codeTopPkg + ";"); ps.println(); ps.println("import configgen.genjava.*;"); ps.println(); ps.println("public class ConfigCodeSchema {"); ps.println(); print(SchemaParser.parse(vdb, ls), ps); ps.println("}"); } private static void print(SchemaInterface schemaInterface, CachedIndentPrinter ip) { { ip.println1("public static Schema getCodeSchema() {"); ip.inc(); ip.inc(); String name = "schema"; ip.println("SchemaInterface %s = new SchemaInterface();", name); for (Map.Entry<String, Schema> stringSchemaEntry : schemaInterface.implementations.entrySet()) { String key = stringSchemaEntry.getKey(); String func = key.replace('.', '_'); ip.println("%s.addImp(\"%s\", %s());", name, key, func); } ip.dec(); ip.dec(); ip.println2("return %s;", name); ip.println1("}"); ip.println(); } Visitor visitor = new Visitor() { @Override public void visit(SchemaPrimitive schemaPrimitive) { throw new IllegalStateException(); } @Override public void visit(SchemaRef schemaRef) { throw new IllegalStateException(); } @Override public void visit(SchemaList schemaList) { throw new IllegalStateException(); } @Override public void visit(SchemaMap schemaMap) { throw new IllegalStateException(); } @Override public void visit(SchemaBean schemaBean) { String name = "s" + ip.indent(); ip.println("SchemaBean %s = new SchemaBean(%s);", name, schemaBean.isTable ? "true" : "false"); for (SchemaBean.Column column : schemaBean.columns) { ip.println("%s.addColumn(\"%s\", %s);", name, column.name, parse(column.schema)); } } @Override public void visit(SchemaInterface schemaInterface) { String name = "s" + ip.indent(); ip.println("SchemaInterface %s = new SchemaInterface();", name); for (Map.Entry<String, Schema> stringSchemaEntry : schemaInterface.implementations.entrySet()) { ip.println("{"); ip.inc(); String subName = "s" + ip.indent(); stringSchemaEntry.getValue().accept(this); ip.println("%s.addImp(\"%s\", %s);", name, stringSchemaEntry.getKey(), subName); ip.dec(); ip.println("}"); } } @Override public void visit(SchemaEnum schemaEnum) { String name = "s" + ip.indent(); ip.println("SchemaEnum %s = new SchemaEnum(%s, %s);", name, schemaEnum.isEnumPart ? "true" : "false", schemaEnum.hasIntValue ? "true" : "false"); for (Map.Entry<String, Integer> entry : schemaEnum.values.entrySet()) { if (schemaEnum.hasIntValue) { ip.println("%s.addValue(\"%s\", %d);", name, entry.getKey(), entry.getValue()); } else { ip.println("%s.addValue(\"%s\");", name, entry.getKey()); } } } }; for (Map.Entry<String, Schema> stringSchemaEntry : schemaInterface.implementations.entrySet()) { String key = stringSchemaEntry.getKey(); String func = key.replace('.', '_'); ip.println1("private static Schema %s() {", func); ip.inc(); ip.inc(); String name = "s" + ip.indent(); stringSchemaEntry.getValue().accept(visitor); ip.dec(); ip.dec(); ip.println2("return %s;", name); ip.println1("}"); ip.println(); } } private static String parse(Schema schema) { return schema.accept(new VisitorT<String>() { @Override public String visit(SchemaPrimitive schemaPrimitive) { return "SchemaPrimitive." + schemaPrimitive.name(); } @Override public String visit(SchemaRef schemaRef) { return "new SchemaRef(\"" + schemaRef.type + "\")"; } @Override public String visit(SchemaList schemaList) { return "new SchemaList(" + parse(schemaList.ele) + ")"; } @Override public String visit(SchemaMap schemaMap) { return "new SchemaMap(" + parse(schemaMap.key) + ", " + parse(schemaMap.value) + ")"; } @Override public String visit(SchemaBean schemaBean) { throw new IllegalStateException(); } @Override public String visit(SchemaInterface schemaInterface) { throw new IllegalStateException(); } @Override public String visit(SchemaEnum schemaEnum) { throw new IllegalStateException(); } }); } }
34.359281
161
0.511851
4c2d6d67947760b51f007a402783088f6b83ee18
3,000
package alien4cloud.tosca.parser.impl.advanced; import javax.annotation.Resource; import alien4cloud.utils.VersionUtil; import alien4cloud.utils.version.InvalidVersionException; import org.alien4cloud.tosca.model.CSARDependency; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import org.yaml.snakeyaml.nodes.Node; import alien4cloud.paas.exception.NotSupportedException; import alien4cloud.tosca.parser.INodeParser; import alien4cloud.tosca.parser.ParsingContextExecution; import alien4cloud.tosca.parser.ParsingError; import alien4cloud.tosca.parser.ParsingErrorLevel; import alien4cloud.tosca.parser.impl.ErrorCode; import alien4cloud.tosca.parser.impl.base.ScalarParser; import lombok.extern.slf4j.Slf4j; /** * Import parser that doesn't validate anything * For validation of version or presence in catalog, see {@link ImportParser} */ @Slf4j @Component public class LaxImportParser implements INodeParser<CSARDependency> { @Resource private ScalarParser scalarParser; @Override public CSARDependency parse(Node node, ParsingContextExecution context) { String valueAsString = scalarParser.parse(node, context); if (StringUtils.isNotBlank(valueAsString)) { if (valueAsString.contains(":")) { String[] dependencyStrs = valueAsString.split(":"); if (dependencyStrs.length == 2) { String dependencyName = dependencyStrs[0]; String dependencyVersion = dependencyStrs[1]; // check that version has the righ format try { VersionUtil.parseVersion(dependencyVersion); } catch (InvalidVersionException e) { context.getParsingErrors() .add(new ParsingError(ParsingErrorLevel.WARNING, ErrorCode.SYNTAX_ERROR, "Version specified in the dependency is not a valid version.", node.getStartMark(), "Dependency should be specified as name:version", node.getEndMark(), "Import")); return null; } return new CSARDependency(dependencyName, dependencyVersion); } context.getParsingErrors().add(new ParsingError(ParsingErrorLevel.WARNING, ErrorCode.SYNTAX_ERROR, "Import definition is not valid", node.getStartMark(), "Dependency should be specified as name:version", node.getEndMark(), "Import")); } else { context.getParsingErrors() .add(new ParsingError(ParsingErrorLevel.WARNING, ErrorCode.SYNTAX_ERROR, "Relative import is currently not supported in Alien 4 Cloud", node.getStartMark(), "Dependency should be specified as name:version", node.getEndMark(), "Import")); } } return null; } }
48.387097
159
0.656667
b10dcaf0532f2152e8901dbf91576bbc27ee60dc
4,188
package com.xthena.sckf.web; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import com.xthena.api.user.UserConnector; import com.xthena.core.hibernate.PropertyFilter; import com.xthena.core.mapper.BeanMapper; import com.xthena.core.page.Page; import com.xthena.core.spring.MessageHelper; import com.xthena.ext.export.Exportor; import com.xthena.ext.export.TableModel; import com.xthena.sckf.domain.JyBm; import com.xthena.sckf.manager.JyBmManager; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller @RequestMapping("sckf") public class JyBmController { private JyBmManager jyBmManager; private Exportor exportor; private BeanMapper beanMapper = new BeanMapper(); private UserConnector userConnector; private MessageHelper messageHelper; @RequestMapping("jyBm-info-list") public String list(@ModelAttribute Page page, @RequestParam Map<String, Object> parameterMap, Model model) { List<PropertyFilter> propertyFilters = PropertyFilter .buildFromMap(parameterMap); page = jyBmManager.pagedQuery(page, propertyFilters); model.addAttribute("page", page); return "sckf/jyBm-info-list"; } @RequestMapping("jyBm-info-input") public String input(@RequestParam(value = "id", required = false) Long id, Model model) { if (id != null) { JyBm jyBm = jyBmManager.get(id); model.addAttribute("model", jyBm); } return "sckf/jyBm-info-input"; } @RequestMapping("jyBm-info-save") public String save(@ModelAttribute JyBm jyBm, @RequestParam Map<String, Object> parameterMap, RedirectAttributes redirectAttributes) { JyBm dest = null; Long id = jyBm.getFid(); if (id != null) { dest = jyBmManager.get(id); beanMapper.copy(jyBm, dest); } else { dest = jyBm; } jyBmManager.save(dest); messageHelper.addFlashMessage(redirectAttributes, "core.success.save", "保存成功"); return "redirect:/sckf/jyBm-info-list.do"; } @RequestMapping("jyBm-info-remove") public String remove(@RequestParam("selectedItem") List<Long> selectedItem, RedirectAttributes redirectAttributes) { List<JyBm> jyBms = jyBmManager.findByIds(selectedItem); jyBmManager.removeAll(jyBms); messageHelper.addFlashMessage(redirectAttributes, "core.success.delete", "删除成功"); return "redirect:/sckf/jyBm-info-list.do"; } @RequestMapping("jyBm-info-export") public void export(@ModelAttribute Page page, @RequestParam Map<String, Object> parameterMap, HttpServletResponse response) throws Exception { List<PropertyFilter> propertyFilters = PropertyFilter .buildFromMap(parameterMap); page = jyBmManager.pagedQuery(page, propertyFilters); List<JyBm> jyBms = (List<JyBm>) page.getResult(); TableModel tableModel = new TableModel(); //tableModel.setName("jyBm info"); //tableModel.addHeaders("id", "name"); tableModel.setData(jyBms); exportor.export(response, tableModel); } // ~ ====================================================================== @Resource public void setJyBmManager(JyBmManager jyBmManager) { this.jyBmManager = jyBmManager; } @Resource public void setExportor(Exportor exportor) { this.exportor = exportor; } @Resource public void setUserConnector(UserConnector userConnector) { this.userConnector = userConnector; } @Resource public void setMessageHelper(MessageHelper messageHelper) { this.messageHelper = messageHelper; } }
30.129496
79
0.667383
6296ad7e9a64dd138f28157961d634932f380580
371
package com.zype.android.webapi.events.search; import com.zype.android.webapi.RequestTicket; import com.zype.android.webapi.events.DataEvent; import com.zype.android.webapi.model.search.SearchResponse; public class SearchEvent extends DataEvent<SearchResponse> { public SearchEvent(RequestTicket ticket, SearchResponse data) { super(ticket, data); } }
28.538462
67
0.784367
695131c6eb88dc33310d4a56b29d07fed35752ee
771
package javacore.introducaoClasses.teste; import javacore.introducaoClasses.dominio.Carro; public class CarroTeste01 { public static void main(String[] args) { Carro carro1 = new Carro(); Carro carro2 = new Carro(); carro1.nome = "Fusca azul"; carro1.modelo = "Sport"; carro1.ano = 1976; carro2.nome = "Celtinha"; carro2.modelo = "Sport"; carro2.ano = 2004; System.out.println("Carro 1"); System.out.println(carro1.nome); System.out.println(carro1.modelo); System.out.println(carro1.ano); System.out.println("\nCarro 2"); System.out.println(carro2.nome); System.out.println(carro2.modelo); System.out.println(carro2.ano); } }
24.09375
48
0.610895
aa16981686fd2f2c04e32300c1a4506caf852318
2,760
package com.github.mittyrobotics.autonomous; import com.github.mittyrobotics.autonomous.pathfollowing.PurePursuitPath; import com.github.mittyrobotics.autonomous.pathfollowing.Point2D; public class BallPositionConstants { //All balls labeled clockwise, starting from the blue ball at the acute corner of red alliance //reference: https://cad.onshape.com/documents/e491d0b03d0534894c2f50ee/w/746eeb7ee6910a6cbe50eb65/e/6f25d3aee97d55ef18af9901 //desmos field: https://www.desmos.com/calculator/xksceznwio //RED ALLIANCE public final Point2D RED_1 = new Point2D(25.910, 150.790); public final Point2D RED_2 = new Point2D(124.946, 88.303); public final Point2D RED_TERMINAL = new Point2D(282.080, 117.725); public final Point2D RED_3 = new Point2D(129.396, -81.643); public final Point2D BLUE_1 = new Point2D(-33.767, 149.227); public final Point2D BLUE_2 = new Point2D(149.227, 33.767); public final Point2D BLUE_3 = new Point2D(88.303, -124.946); //BLUE ALLIANCE public final Point2D BLUE_4 = new Point2D(-25.910, -150.790); public final Point2D BLUE_5 = new Point2D(-124.946, -88.303); public final Point2D BLUE_TERMINAL = new Point2D(-282.080, -117.725); public final Point2D BLUE_6 = new Point2D(-129.396, 81.643); public final Point2D RED_4 = new Point2D(33.767, -149.227); public final Point2D RED_5 = new Point2D(-149.227, -33.767); public final Point2D RED_6 = new Point2D(-88.303, 124.946); //RED ALLIANCE METRIC public final Point2D RED_1_METRIC = RED_1.multiply(PurePursuitPath.TO_METERS); public final Point2D RED_2_METRIC = RED_2.multiply(PurePursuitPath.TO_METERS); public final Point2D RED_TERMINAL_METRIC = RED_TERMINAL.multiply(PurePursuitPath.TO_METERS); public final Point2D RED_3_METRIC = RED_3.multiply(PurePursuitPath.TO_METERS); public final Point2D BLUE_1_METRIC = BLUE_1.multiply(PurePursuitPath.TO_METERS); public final Point2D BLUE_2_METRIC = BLUE_2.multiply(PurePursuitPath.TO_METERS); public final Point2D BLUE_3_METRIC = BLUE_3.multiply(PurePursuitPath.TO_METERS); //BLUE ALLIANCE METRIC public final Point2D BLUE_4_METRIC = BLUE_4.multiply(PurePursuitPath.TO_METERS); public final Point2D BLUE_5_METRIC = BLUE_5.multiply(PurePursuitPath.TO_METERS); public final Point2D BLUE_TERMINAL_METRIC = BLUE_TERMINAL.multiply(PurePursuitPath.TO_METERS); public final Point2D BLUE_6_METRIC = BLUE_6.multiply(PurePursuitPath.TO_METERS); public final Point2D RED_4_METRIC = RED_4.multiply(PurePursuitPath.TO_METERS); public final Point2D RED_5_METRIC = RED_5.multiply(PurePursuitPath.TO_METERS); public final Point2D RED_6_METRIC = RED_6.multiply(PurePursuitPath.TO_METERS); }
40.588235
129
0.763043
070c4e30b1bdb87cb9548c4f04bf047b722ab509
624
package seedu.address.logic.commands; //import static org.junit.Assert.assertEquals; import org.junit.Test; //import seedu.address.model.statistics.PlayerStatistics; //import seedu.address.storage.JsonSerializableStatistics; public class StatsStorageTest { @Test public void statsStorage_toModelType_success() { //JsonSerializableStatistics jsonStats = new JsonSerializableStatistics("0", "0", "0", "0", "0"); //PlayerStatistics playerStats = new PlayerStatistics(); //PlayerStatistics playerStatsB = jsonStats.toModelType(); //assertEquals(playerStats, playerStatsB); } }
28.363636
105
0.735577
d21db72707659bc08f45fca5920e5ba06a16b80e
4,147
package algo.leetcode; import java.util.*; public class StickersSpellWord { public int[] getStringFinger(String s){ int[] res = new int[26]; for(int i = 0; i < s.length(); i ++){ res[s.charAt(i)-'a'] ++; } return res; } public int minStickers(String[] stickers, String target) { int[][] sticks = new int[stickers.length][26]; List<Integer> lefters = new ArrayList<>(); int[] targ = getStringFinger(target); for(int i = 0; i < stickers.length; i ++){ sticks[i] = getStringFinger(stickers[i]); if(checkTargetExist(sticks[i], targ)){ lefters.add(i); } } int res = getStickersCover(sticks, targ, lefters); return res==Integer.MAX_VALUE?-1:res; } public int[] removeTargetCount(int[] origin, int[] target){ int[] temp = new int[26]; for(int j = 0; j < 26; j ++){ if(origin[j] != 0 && target[j]!=0){ temp[j] = Math.max(0, target[j] - origin[j]); }else{ temp[j] = target[j]; } } return temp; } public boolean checkTargetExist(int[] origin, int[] target){ for(int j = 0; j < 26; j ++){ if(origin[j] != 0 && target[j]!=0){ return true; } } return false; } public boolean checkTargetZero(int[] target){ for(int i = 0; i < 26; i ++){ if(target[i] != 0)return false; } return true; } public int getStickersCover(int[][] stickers, int[] target, List<Integer> lefters){ if(checkTargetZero(target))return 0; int minStep = Integer.MAX_VALUE; for (int index: lefters) { List<Integer> left = new ArrayList<>(); int[] temp = removeTargetCount(stickers[index], target); for (int ii: lefters) { if(checkTargetExist(stickers[ii], temp)){ left.add(ii); } } int step = getStickersCover(stickers, temp, left); if(step != Integer.MAX_VALUE){ minStep = Math.min(minStep, 1 + step); } } return minStep; } String toKey(int[] arr){ StringBuilder sb=new StringBuilder(); boolean allZ=true; for (int i=0;i<26;++i){ int n=arr[i]; sb.append(n).append(","); if (n>0)allZ=false; } if (allZ)return ""; return sb.toString(); } public int minStickers2(String[] stickers, String target) { if (target.isEmpty())return 0; int ns=stickers.length; int tl=target.length(); int[][] letters=new int[ns][26]; for (int i=0;i<stickers.length;++i){ String s=stickers[i]; for (char c:s.toCharArray())++letters[i][c-'a']; } int[] targetLetters=new int[27]; for (char c:target.toCharArray())++targetLetters[c-'a']; targetLetters[26]=0; String key=toKey(targetLetters); int ans=0; if (key.isEmpty())return 0; Queue<int[]> q=new LinkedList<>(); Set<String> seenKey= new HashSet<>(); seenKey.add(key); q.add(targetLetters); while (!q.isEmpty()){ int[]cur=q.remove(); for (int i=0;i<ns;++i){ int[] next=cur.clone(); int[]letter=letters[i]; for (int j=0;j<26;++j){ if (letter[j]>=0) next[j]=Math.max(next[j]-letter[j], 0); } ++next[26]; String nextKey=toKey(next); if (nextKey.isEmpty())return next[26]; if (seenKey.add(nextKey)){ q.add(next); } } } return -1; } public static void main(String[] args){ String[] vals = {"with", "example", "science"}; System.out.print(new StickersSpellWord().minStickers(vals, "thehat")); } }
30.947761
87
0.479865
b3c8b6d402869aa600232f062ee11712d85a25e1
6,873
package com.axeac.app.sdk.ui.container; import android.app.Activity; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.os.Handler; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.axeac.app.sdk.R; import com.axeac.app.sdk.tools.StringUtil; import com.axeac.app.sdk.utils.CommonUtil; import com.axeac.app.sdk.utils.DensityUtil; import com.axeac.app.sdk.utils.StaticObject; /** * describe:Paging Container * 分页签 * <br>以分页签的形式显示信息,组容器外边缘为圆角矩形。 * @author axeac * @version 1.0.0 */ public class TabContainer extends Container { /** * TOP\LEFT\RIGHT\BOTTOM,设置浮动图标浮动的位置 * <br>默认值为TOP * */ private String direction = "top"; /** * 当前设置和返回当前选择的Tab页 * <br>默认值:1 * */ private int activeTab = 1; /** * 存储标签名字的list集合 * */ private List<String> names = new ArrayList<String>(); /** * 存储索引位置的list集合 * */ private List<Integer> indexs = new ArrayList<Integer>(); /** * 存储组件id的list集合 * */ private List<String> compIds = new ArrayList<String>(); /** * 存储标签视图的list集合 * */ private List<TextView> btns = new ArrayList<TextView>(); private LinearLayout layout; private LinearLayout navTop; private LinearLayout tabContent; private int maxTabCount; public TabContainer(Activity ctx) { super(ctx); layout = (LinearLayout) LayoutInflater.from(ctx).inflate(R.layout.axeac_tab_container, null); tabContent = (LinearLayout) layout.findViewById(R.id.tab_content); navTop = (LinearLayout) layout.findViewById(R.id.tab_nav_top); bgColor = "238238238"; } @Override public void setLayout(String layout) { } /** * 设置浮动图标浮动位置 * @param direction * direction 可选值:TOP\LEFT\RIGHT\BOTTOM * */ public void setDirection(String direction) { this.direction = direction; } /** * 设置当前设置和返回当前选择的Tab页 * @param activeTab * activeTab 默认值:1 * */ public void setActiveTab(String activeTab) { this.activeTab = Integer.parseInt(activeTab); } /** * 设置标签名称 * @param names * names 格式示例:标签1,标签2,标签3 * */ public void setNames(String names) { String[] name = StringUtil.split(names, ","); for (int i = 0; i < name.length; i++) { this.names.add(name[i]); } } @Override public void add(String compId, boolean isReturn) { } /** * 添加索引和组件id * @param compId * 组件id * @param val * * */ public void add(String compId, String val) { if(StaticObject.ComponentMap.get(compId) != null && StaticObject.ComponentMap.get(compId).addable){ childs.put(compId,StaticObject.ComponentMap.get(compId)); StaticObject.ComponentMap.get(compId).addable = false; String[] vals = StringUtil.split(val, ","); if (vals.length == 2) { indexs.add(Integer.parseInt(vals[1].trim())); } else { indexs.add(0); } compIds.add(compId); if (CommonUtil.getBoolean(vals[0])) { StaticObject.ReturnComponentMap.put(compId, StaticObject.ComponentMap.get(compId)); } } } /** * 执行方法 * */ @Override public void execute() { maxTabCount = showActiveTabNav(); showActiveTabContent("next"); int r = Integer.parseInt(bgColor.substring(0, 3)); int g = Integer.parseInt(bgColor.substring(3, 6)); int b = Integer.parseInt(bgColor.substring(6, 9)); tabContent.setBackgroundColor(Color.rgb(r, g, b)); if (this.bgImage != null && !"".equals(bgImage)) { BitmapDrawable draw; try { draw = new BitmapDrawable(this.ctx.getResources(),BitmapFactory.decodeStream(this.ctx.getResources().getAssets().open(bgImage + ".png"))); tabContent.setBackgroundDrawable(draw); } catch (IOException e) { } } tabContent.getBackground().setAlpha((int)(255 * ((float)this.alpha/100))); tabContent.addView(this.layoutContainer.getLayout()); } /** * 返回标签页数 * @return * 标签页数 * */ private int showActiveTabNav() { if (names.size() > 0) { for (int i = 0; i < names.size(); i++) { TextView btn = new TextView(ctx); btn.setSingleLine(); btn.setPadding(0, 10, 0, 10); btn.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL)); if(names.size() == 1){ btn.setLayoutParams(new ViewGroup.LayoutParams(StaticObject.deviceWidth / 3, ViewGroup.LayoutParams.WRAP_CONTENT)); } else if (names.size() == 2){ btn.setLayoutParams(new ViewGroup.LayoutParams(StaticObject.deviceWidth / 2, ViewGroup.LayoutParams.WRAP_CONTENT)); } else { btn.setLayoutParams(new ViewGroup.LayoutParams(StaticObject.deviceWidth / names.size(), ViewGroup.LayoutParams.WRAP_CONTENT)); } btn.setHeight(DensityUtil.dip2px(ctx, 42)); btn.setBackgroundResource(R.drawable.axeac_tab_bg_normal); btn.setGravity(Gravity.CENTER); btn.setText(names.get(i)); btn.setTextColor(Color.BLACK); btn.setTag(i); btn.setOnClickListener(listener); btns.add(btn); navTop.addView(btn); } return names.size(); } return 0; } private View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { int index = (Integer) v.getTag() + 1; if (activeTab != index) { if (index > activeTab) { activeTab = index; showActiveTabContent("next"); } else { activeTab = index; showActiveTabContent("last"); } } } }; /** * 显示标签内容 * @param o * 可选值:next last * */ private void showActiveTabContent(String o) { for (int i = 0; i < maxTabCount; i++) { if (names.size() > 0) { btns.get(i).setBackgroundResource(R.drawable.axeac_tab_bg_normal); btns.get(i).setTextColor(Color.BLACK); } } if (activeTab > maxTabCount) { return; } if (names.size() > 0) { btns.get(activeTab - 1).setBackgroundResource(R.drawable.axeac_tab_bg_selected); // btns.get(activeTab - 1).setTextColor(Color.WHITE); } this.layoutContainer.removeAll(); ctx.getWindow().getDecorView().post(new Runnable() { @Override public void run() { new Handler().post(new Runnable() { @Override public void run() { for (int i = 0; i < indexs.size(); i++) { if (activeTab == indexs.get(i)) { if (!clear) { TabContainer.this.layoutContainer.addViewIn(childs.get(compIds.get(i))); } } } } }); } }); } /** * 显示最后一页标签 * */ public void showLastTab() { if (activeTab > 1) { activeTab = activeTab - 1; } else { activeTab = maxTabCount; } showActiveTabContent("last"); } /** * 显示下一页标签 * */ public void showNextTab() { if (activeTab < maxTabCount) { activeTab = activeTab + 1; } else { activeTab = 1; } showActiveTabContent("next"); } @Override public View getView() { return layout; } }
24.723022
142
0.669722
3f4343ed412b6062672cd65335f940c4a147ec65
3,519
package datawave.iterators; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.accumulo.core.data.ByteSequence; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.iterators.IterationInterruptedException; import org.apache.accumulo.core.iterators.IteratorEnvironment; import org.apache.accumulo.core.iterators.SortedKeyValueIterator; import org.apache.accumulo.core.iterators.system.InterruptibleIterator; import com.google.common.collect.TreeMultimap; /** * */ public class SortedMultiMapIterator implements InterruptibleIterator { private Iterator<Entry<Key,Value>> iter; private Entry<Key,Value> entry; private TreeMultimap<Key,Value> map; private Range range; private AtomicBoolean interruptFlag; private int interruptCheckCount = 0; public SortedMultiMapIterator deepCopy(IteratorEnvironment env) { return new SortedMultiMapIterator(map, interruptFlag); } private SortedMultiMapIterator(TreeMultimap<Key,Value> map, AtomicBoolean interruptFlag) { this.map = map; iter = null; this.range = new Range(); entry = null; this.interruptFlag = interruptFlag; } public SortedMultiMapIterator(TreeMultimap<Key,Value> map) { this(map, null); } @Override public Key getTopKey() { return entry.getKey(); } @Override public Value getTopValue() { return entry.getValue(); } @Override public boolean hasTop() { return entry != null; } @Override public void next() throws IOException { if (entry == null) throw new IllegalStateException(); if (interruptFlag != null && interruptCheckCount++ % 100 == 0 && interruptFlag.get()) throw new IterationInterruptedException(); if (iter.hasNext()) { entry = iter.next(); if (range.afterEndKey(entry.getKey())) { entry = null; } } else entry = null; } @Override public void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive) throws IOException { if (interruptFlag != null && interruptFlag.get()) throw new IterationInterruptedException(); this.range = range; Key key = range.getStartKey(); if (key == null) { key = new Key(); } iter = map.entries().iterator(); if (iter.hasNext()) { entry = iter.next(); while (entry.getKey().compareTo(key) <= 0) entry = iter.next(); if (range.afterEndKey(entry.getKey())) { entry = null; } } else entry = null; while (hasTop() && range.beforeStartKey(getTopKey())) { next(); } } public void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> options, IteratorEnvironment env) throws IOException { throw new UnsupportedOperationException(); } @Override public void setInterruptFlag(AtomicBoolean flag) { this.interruptFlag = flag; } }
28.379032
136
0.616937
6f9520a25078d93b7e1ca988812dc876734c7c01
1,730
/** * Copyright (C) 2011 Smithsonian Astrophysical Observatory * * 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 cfa.vo.sedlib.io; import java.io.OutputStream; import cfa.vo.sedlib.Sed; import cfa.vo.sedlib.common.SedInconsistentException; import cfa.vo.sedlib.common.SedWritingException; import java.io.IOException; /** Defines management of writing Sed objects to file and streams. */ public interface ISedSerializer { /** * Serializes Sed object to an stream * in the serializer's format. * @param oStream * {@link OutputStream} * @param sed * {@link Sed} * @throws SedInconsistentException, SedWritingException */ public void serialize(OutputStream oStream, Sed sed) throws SedInconsistentException, SedWritingException, IOException; /** * Serializes Sed object tree to a file in the serializer's * format. * @param filename * {@link String} * @param sed * {@link Sed} * @throws SedInconsistentException, SedWritingException */ public void serialize(String filename, Sed sed) throws SedInconsistentException, SedWritingException, IOException; }
30.892857
86
0.697688
4db29adf9b0559547c3539919b0ac7ac81ef523b
465
package com.maaxap.composite; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Word extends CompositeUnit { private static final Logger LOGGER = LoggerFactory.getLogger(Word.class); private String wordText; public Word(String wordText) { this.wordText = wordText; } public String getWordText() { return wordText; } @Override public void printUnit() { LOGGER.info(wordText); } }
19.375
77
0.677419
4eb093185e7fcfccc32744d1ae4d44e3264b2c94
1,065
package com.github.glomadrian.sample; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.github.glomadrian.sample.fragment.DragonBall; import com.github.glomadrian.sample.fragment.Pager; import com.github.glomadrian.sample.fragment.Simple; import com.github.glomadrian.sample.fragment.Size; /** * @author Adrián García Lomas */ public class Adapter extends FragmentPagerAdapter { private static final int COUNT = 4; public Adapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case 0: return Simple.getInstance(); case 1: return Pager.getInstance(); case 2: return Size.getInstance(); case 3: return DragonBall.getInstance(); } return Simple.getInstance(); } @Override public int getCount() { return COUNT; } }
25.357143
56
0.646948
61bf647fb164777d77986063a2704510f6afa9c7
2,981
package net.glowstone.entity; import com.google.common.collect.Sets; import java.util.EnumSet; import java.util.Set; import net.glowstone.entity.ai.EntityDirector; import net.glowstone.entity.ai.MobState; import net.glowstone.net.message.play.player.InteractEntityMessage; import net.glowstone.util.InventoryUtil; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Statistic; import org.bukkit.entity.Animals; import org.bukkit.entity.EntityType; import org.bukkit.inventory.ItemStack; /** * Represents an Animal, such as a Cow. */ public class GlowAnimal extends GlowAgeable implements Animals { private static final Set<Material> DEFAULT_BREEDING_FOODS = Sets.immutableEnumSet(EnumSet.noneOf(Material.class)); /** * Creates a new ageable animal. * * @param location The location of the animal. * @param type The type of animal. * @param maxHealth The max health of this animal. */ public GlowAnimal(Location location, EntityType type, double maxHealth) { super(location, type, maxHealth); if (type != null) { EntityDirector.registerEntityMobState(type, MobState.IDLE, "look_around"); EntityDirector.registerEntityMobState(type, MobState.IDLE, "look_player"); } setState(MobState.IDLE); } @Override protected int getAmbientDelay() { return 120; } @Override public boolean entityInteract(GlowPlayer player, InteractEntityMessage message) { if (!super.entityInteract(player, message) && message.getAction() == InteractEntityMessage.Action.INTERACT.ordinal()) { ItemStack item = InventoryUtil .itemOrEmpty(player.getInventory().getItem(message.getHandSlot())); if (player.getGameMode().equals(GameMode.SPECTATOR) || InventoryUtil.isEmpty(item)) { return false; } if (GameMode.CREATIVE != player.getGameMode() && getBreedingFoods().contains(item.getType())) { // TODO set love mode if possible and spawn particles // TODO heal // TODO only consume the item if the animal is healed or something else player.getInventory().consumeItem(message.getHand()); player.incrementStatistic(Statistic.ANIMALS_BRED); return true; } } return false; } /** * Returns an immutable set containing the breeding foods for the current animal. * @return an immutable set containing Material */ public Set<Material> getBreedingFoods() { return DEFAULT_BREEDING_FOODS; } @Override protected int computeGrowthAmount(Material material) { if (canGrow() && getBreedingFoods().contains(material)) { return Math.abs(getAge() / 10); } return 0; } }
33.122222
92
0.650453
1ff3ea6219d7a80e5e5e2e9f6a6ab139e772e56d
5,980
/** * Copyright 2010 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 datameer.awstasks.ssh; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import awstasks.com.jcraft.jsch.Channel; import awstasks.com.jcraft.jsch.Session; import datameer.awstasks.util.IoUtil; import datameer.awstasks.util.SshUtil; public class ScpDownloadCommand extends JschCommand { private static final byte LINE_FEED = 0x0a; private static final String SCP_DOWNLOAD_COMMAND = "scp -f "; private final String _remoteFile; private final File _localFile; private final boolean _recursive; public ScpDownloadCommand(String remoteFile, File localFile, boolean recursive) { _remoteFile = remoteFile; _localFile = localFile; _recursive = recursive; } @Override public void execute(Session session) throws IOException { String command = constructScpInitCommand(_remoteFile, _recursive); Channel channel = SshUtil.openExecChannel(session, command); try { OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream(); SshUtil.sendAckOk(out); download(in, out, _localFile); } finally { if (channel != null) { channel.disconnect(); } } } protected final static String constructScpInitCommand(String remoteFile, boolean recursive) { String command = SCP_DOWNLOAD_COMMAND; if (recursive) { command += "-r "; } command += remoteFile.replace(" ", "\\ "); return command; } private final static void download(InputStream in, OutputStream out, File localFile) throws IOException { File startFile = localFile; while (true) { // C0644 filesize filename - header for a regular file // T time 0 time 0\n - present if perserve time. // D directory - this is the header for a directory. String serverResponse = readServerResponse(in); if (serverResponse == null) { return; } if (serverResponse.charAt(0) == 'C') { parseAndDownloadFile(serverResponse, startFile, out, in); } else if (serverResponse.charAt(0) == 'D') { startFile = parseAndCreateDirectory(serverResponse, startFile); SshUtil.sendAckOk(out); } else if (serverResponse.charAt(0) == 'E') { startFile = startFile.getParentFile(); SshUtil.sendAckOk(out); } else if (serverResponse.charAt(0) == '\01' || serverResponse.charAt(0) == '\02') { // this indicates an error. throw new IOException(serverResponse.substring(1)); } } } protected static String readServerResponse(InputStream in) throws IOException, UnsupportedEncodingException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); while (true) { int read = in.read(); if (read < 0) { return null; } if ((byte) read == LINE_FEED) { break; } stream.write(read); } String serverResponse = stream.toString("UTF-8"); return serverResponse; } private final static File parseAndCreateDirectory(String serverResponse, File localFile) { int start = serverResponse.indexOf(" "); // appears that the next token is not used and it's zero. start = serverResponse.indexOf(" ", start + 1); String directoryName = serverResponse.substring(start + 1); if (localFile.isDirectory()) { File dir = new File(localFile, directoryName); dir.mkdir(); LOG.info("Creating: " + dir); return dir; } return null; } private final static void parseAndDownloadFile(String serverResponse, File localFile, OutputStream out, InputStream in) throws IOException { int start = 0; int end = serverResponse.indexOf(" ", start + 1); start = end + 1; end = serverResponse.indexOf(" ", start + 1); long filesize = Long.parseLong(serverResponse.substring(start, end)); String filename = serverResponse.substring(end + 1); LOG.info("Receiving: " + filename + " : " + filesize); File transferFile = (localFile.isDirectory()) ? new File(localFile, filename) : localFile; downloadFile(transferFile, filesize, out, in); SshUtil.checkAcknowledgement(in); SshUtil.sendAckOk(out); } private final static void downloadFile(File localFile, long filesize, OutputStream out, InputStream in) throws IOException { SshUtil.sendAckOk(out); // read a content of lfile FileOutputStream fos = new FileOutputStream(localFile); long totalLength = 0; long startTime = System.currentTimeMillis(); try { IoUtil.copyBytes(in, fos, filesize); } finally { long endTime = System.currentTimeMillis(); logStats(startTime, endTime, totalLength); fos.flush(); fos.close(); } } }
37.375
144
0.628428
e377460bc8d3cef62a3809f697877d38597758d6
153
package state.blurayplayer; public interface BluRayPlayerState { void insertBluRay(); void pressPlay(); void pressStop(); void ejectBluRay(); }
11.769231
36
0.738562
b1687c218e8688480f73bb0f4ab81b9fe675db47
2,464
/* * $Id$ * * Copyright 2006-2008 Alex Lin. 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 org.opoo.oqs.spring; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import org.opoo.oqs.TypedValue; import org.opoo.oqs.core.AbstractBatcher; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.JdbcTemplate; import org.opoo.oqs.core.AbstractQueryFactory; /** * * * @author Alex Lin([email protected]) * @version 1.0 */ public class SpringBatcher extends AbstractBatcher { boolean isPrepared = false; private JdbcTemplate jdbcTemplate; public SpringBatcher(AbstractQueryFactory queryFactory, JdbcTemplate jdbcTemplate) { super(queryFactory); isPrepared = false; this.jdbcTemplate = jdbcTemplate; } public SpringBatcher(AbstractQueryFactory queryFactory, JdbcTemplate jdbcTemplate, String sql) { super(queryFactory, sql); isPrepared = true; this.jdbcTemplate = jdbcTemplate; } public int[] executeBatch() { final List list = getTypedValuesList(); if (isPrepared) { return jdbcTemplate.batchUpdate(getSql(), new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int ii) throws SQLException { TypedValue[] typedValues = (TypedValue[]) list.get(ii); for (int i = 0; i < typedValues.length; i++) { TypedValue tv = typedValues[i]; tv.getType().safeSet(ps, tv.getValue(), i + 1); } } public int getBatchSize() { return list.size(); } }); } else { return jdbcTemplate.batchUpdate(getSqls()); } } }
32.853333
100
0.633117
7bc6a7c74c4ad23cd31867b0499f421f0798a7f9
213
/** * Enumeration class Estado - write a description of the enum class here * * @author (your name here) * @version (version number or date here) */ public enum Estado { NOPRESTADO, PRESTADO; }
14.2
72
0.652582
1944866a5879510f0d4778ed57584d7f41784927
1,178
package ${package}.components.content.accordion; import com.citytechinc.cq.component.annotations.Component; import com.citytechinc.cq.component.annotations.editconfig.ActionConfig; import com.citytechinc.cq.component.annotations.editconfig.ActionConfigProperty; import com.icfolson.aem.harbor.core.components.content.accordion.v1.DefaultAccordion; @Component( value = "Accordion Group", actions = { "text: Accordion Group", "-", "edit", "-", "copymove", "delete", "-", "insert" }, isContainer = true, resourceSuperType = DefaultAccordion.RESOURCE_TYPE, actionConfigs = { @ActionConfig( text = "Add Item", handler = "function(){Harbor.Components.Accordion.v1.Accordion.addItem( this, '" + AccordionItem.RESOURCE_TYPE + "' )}", additionalProperties = { @ActionConfigProperty(name = "icon", value = "coral-Icon--experienceAdd") }) } ) public class Accordion extends DefaultAccordion { public static final String RESOURCE_TYPE = "${rootArtifactId}/components/content/accordion"; }
42.071429
144
0.642615
9f5f514eb3b252d30dd7dea1f3707be11f6e41d7
1,574
package com.elastisys.scale.commons.net.host; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.InetAddress; import java.net.SocketException; import java.util.Collection; import org.junit.Test; /** * Verifies the behavior of the {@link HostUtils} class. * * */ public class TestHostUtils { @Test public void getHostIpv4AddressesExcludingLoopback() throws IOException { Collection<InetAddress> ipv4Addresses = HostUtils.hostIpv4Addresses(); assertThat(ipv4Addresses.isEmpty(), is(false)); for (InetAddress ipv4Address : ipv4Addresses) { assertFalse(ipv4Address.isLoopbackAddress()); } // calls should be semantically equivalent assertThat(HostUtils.hostIpv4Addresses(), is(HostUtils.hostIpv4Addresses(false))); } @Test public void getHostIpv4AddressesIncludingLoopback() throws SocketException { Collection<InetAddress> ipv4Addresses = HostUtils.hostIpv4Addresses(true); assertThat(ipv4Addresses.isEmpty(), is(false)); boolean loopbackEncountered = false; for (InetAddress ipv4Address : ipv4Addresses) { if (ipv4Address.isLoopbackAddress()) { loopbackEncountered = true; } } assertTrue(loopbackEncountered); assertTrue(HostUtils.hostIpv4Addresses(true).size() > HostUtils.hostIpv4Addresses(false).size()); } }
30.269231
105
0.709022
fc68b64443001e98c4a25de8fff15c56da841530
4,834
package com.superrtc.b; import android.content.Context; import android.os.Build; import android.os.Build.VERSION; import android.os.Process; import com.superrtc.call.Logging; import java.util.Arrays; import java.util.List; public final class b { private static final String[] a = new String[0]; private static final String[] b = { "D6503", "ONE A2005" }; private static final String[] c = { "Nexus 10", "Nexus 9" }; private static final String[] d = { "Nexus 10", "Nexus 9", "ONE A2005" }; private static int e = 16000; private static boolean f = false; private static boolean g = false; private static boolean h = false; private static boolean i = false; public static boolean deviceIsBlacklistedForOpenSLESUsage() { return Arrays.asList(a).contains(Build.MODEL); } public static List<String> getBlackListedModelsForAecUsage() { return Arrays.asList(b); } public static List<String> getBlackListedModelsForAgcUsage() { return Arrays.asList(c); } public static List<String> getBlackListedModelsForNsUsage() { return Arrays.asList(d); } public static int getDefaultSampleRateHz() { try { int j = e; return j; } finally { localObject = finally; throw ((Throwable)localObject); } } public static String getThreadInfo() { return "@[name=" + Thread.currentThread().getName() + ", id=" + Thread.currentThread().getId() + "]"; } public static boolean hasPermission(Context paramContext, String paramString) { return paramContext.checkPermission(paramString, Process.myPid(), Process.myUid()) == 0; } public static boolean isDefaultSampleRateOverridden() { try { boolean bool = f; return bool; } finally { localObject = finally; throw ((Throwable)localObject); } } public static void logDeviceInfo(String paramString) { Logging.d(paramString, "Android SDK: " + Build.VERSION.SDK_INT + ", Release: " + Build.VERSION.RELEASE + ", Brand: " + Build.BRAND + ", Device: " + Build.DEVICE + ", Id: " + Build.ID + ", Hardware: " + Build.HARDWARE + ", Manufacturer: " + Build.MANUFACTURER + ", Model: " + Build.MODEL + ", Product: " + Build.PRODUCT); } public static boolean runningOnEmulator() { return (Build.HARDWARE.equals("goldfish")) && (Build.BRAND.startsWith("generic_")); } public static boolean runningOnGingerBreadOrHigher() { return Build.VERSION.SDK_INT >= 9; } public static boolean runningOnJellyBeanMR1OrHigher() { return Build.VERSION.SDK_INT >= 17; } public static boolean runningOnJellyBeanMR2OrHigher() { return Build.VERSION.SDK_INT >= 18; } public static boolean runningOnJellyBeanOrHigher() { return Build.VERSION.SDK_INT >= 16; } public static boolean runningOnLollipopOrHigher() { return Build.VERSION.SDK_INT >= 21; } public static void setDefaultSampleRateHz(int paramInt) { try { f = true; e = paramInt; return; } finally { localObject = finally; throw ((Throwable)localObject); } } public static void setWebRtcBasedAcousticEchoCanceler(boolean paramBoolean) { try { g = paramBoolean; return; } finally { localObject = finally; throw ((Throwable)localObject); } } public static void setWebRtcBasedAutomaticGainControl(boolean paramBoolean) { try { h = paramBoolean; return; } finally { localObject = finally; throw ((Throwable)localObject); } } public static void setWebRtcBasedNoiseSuppressor(boolean paramBoolean) { try { i = paramBoolean; return; } finally { localObject = finally; throw ((Throwable)localObject); } } public static boolean useWebRtcBasedAcousticEchoCanceler() { try { if (g) { Logging.w("WebRtcAudioUtils", "Overriding default behavior; now using WebRTC AEC!"); } boolean bool = g; return bool; } finally {} } public static boolean useWebRtcBasedAutomaticGainControl() { try { if (h) { Logging.w("WebRtcAudioUtils", "Overriding default behavior; now using WebRTC AGC!"); } boolean bool = h; return bool; } finally {} } public static boolean useWebRtcBasedNoiseSuppressor() { try { if (i) { Logging.w("WebRtcAudioUtils", "Overriding default behavior; now using WebRTC NS!"); } boolean bool = i; return bool; } finally {} } } /* Location: /Users/gaoht/Downloads/zirom/classes2-dex2jar.jar!/com/superrtc/b/b.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
22.276498
324
0.631568
a24ab01085685c31808a0ec64f69be07c6b49e95
1,953
package com.ronja.crm.ronjaclient.desktop.controller; import com.ronja.crm.ronjaclient.desktop.component.customer.CustomerTableView; import com.ronja.crm.ronjaclient.desktop.component.dialog.Dialogs; import com.ronja.crm.ronjaclient.desktop.component.representative.RepresentativeTableView; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.Tab; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Objects; @Component public class MainWindowController { @FXML private Tab customersTab; @FXML private Tab representativesTab; private final CustomerTableView customerTableView; private final RepresentativeTableView representativeTableView; public MainWindowController(@Autowired CustomerTableView customerTableView, @Autowired RepresentativeTableView representativeTableView) { Thread.setDefaultUncaughtExceptionHandler(this::handleUncaughtException); this.customerTableView = Objects.requireNonNull(customerTableView); this.representativeTableView = Objects.requireNonNull(representativeTableView); } @FXML public void initialize() { customersTab.setContent(customerTableView); customersTab.selectedProperty().addListener((observable, oldValue, newValue) -> onChange(newValue, customerTableView::refreshItems)); representativesTab.setContent(representativeTableView); representativesTab.selectedProperty().addListener((observable, oldValue, newValue) -> onChange(newValue, representativeTableView::refreshItems)); } private void onChange(Boolean newValue, Runnable runnable) { if (Boolean.TRUE.equals(newValue)) { runnable.run(); } } private void handleUncaughtException(Thread thread, Throwable throwable) { Platform.runLater( () -> Dialogs.showErrorMessage("Chyba", throwable.getMessage())); } }
36.166667
91
0.785458
15b626d10200cf2ceef353056b80e00b4664f1c2
1,166
package com.dynatrace.profilediff.ui; import java.util.List; import com.dynatrace.profilediff.XmlElement; import com.dynatrace.profilediff.XmlStruct; import com.dynatrace.profilediff.XmlUtil; class CommonModel { static interface ChangeItemInterface { boolean containsAttributeChanges(); boolean containsInsertions(); boolean containsDeletions(); boolean isChangesOnly(); boolean isTwoWayModel(); } static void collectChangedElements(XmlStruct xml, ChangeItemInterface item, List<XmlElement> deletions, List<XmlElement> insertions, List<XmlElement> attrChanges) { for (XmlElement element : xml.elements) { if (!XmlUtil.isFilteredVisible(element)) { continue; } if (element.hasDirectStructureChange() && element.isDeletion() && item.containsDeletions()) { deletions.add(element); } else if (element.hasDirectStructureChange() && element.isInsertion() && item.containsInsertions()) { insertions.add(element); } else if (element.hasDirectAttributeChange() && (element.isInsertion() || item.isTwoWayModel()) && item.containsAttributeChanges()) { attrChanges.add(element); } } } }
34.294118
166
0.730703
9b5c4bd363674957f42e31a6b8778a116ddaf13b
1,656
/** * * Class ParameterDirectionKind$Class.java * * Generated by KMFStudio at 14 April 2004 22:36:44 * Visit http://www.cs.ukc.ac.uk/kmf * */ package uk.ac.ukc.cs.kmf.kmfstudio.uml.Foundation.Data_Types; public class ParameterDirectionKind$Class implements ParameterDirectionKind, uk.ac.ukc.cs.kmf.kmfstudio.uml.UmlVisitable { /** The 'IN' enumerator */ public static final ParameterDirectionKind IN = new ParameterDirectionKind$Class(); /** The 'OUT' enumerator */ public static final ParameterDirectionKind OUT = new ParameterDirectionKind$Class(); /** The 'INOUT' enumerator */ public static final ParameterDirectionKind INOUT = new ParameterDirectionKind$Class(); /** The 'RETURN' enumerator */ public static final ParameterDirectionKind RETURN = new ParameterDirectionKind$Class(); /** Default constructors */ public ParameterDirectionKind$Class() { } /** The id */ protected String id; /** Get the id */ public String getId() { return id; } /** Set the id */ public void setId(String id) { this.id = "1"; } /** Overrride toString */ public String toString() { String res = "ParameterDirectionKind"; if (this == IN) res += "::IN"; if (this == OUT) res += "::OUT"; if (this == INOUT) res += "::INOUT"; if (this == RETURN) res += "::RETURN"; return res; } /** Clone the object */ public Object clone() { ParameterDirectionKind$Class obj = new ParameterDirectionKind$Class(); return obj; } /** Delete the object */ public void delete() { } /** Accept the visitor */ public Object accept(uk.ac.ukc.cs.kmf.kmfstudio.uml.UmlVisitor v, Object obj) { return v.visit(this, obj); } }
25.875
88
0.684783
aea78c9e25bbae7d5b6c688ab68975be9de6beca
228
package mx.sam.apiEjemplo.service; import mx.sam.apiEjemplo.dto.UsuarioDTO; import mx.sam.apiEjemplo.service.utils.Crud; /* * @author Samuel * @version 1.0 * */ public interface IUsuarioService extends Crud<UsuarioDTO>{ }
17.538462
58
0.754386