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
213755a4bcf044feef8fd1fea85dd864f29b1f33
3,538
package cn.liulin.algorithm.leetcode.array.simple; import java.util.HashMap; import java.util.Map; /** * cn.liulin.algorithm.leetcode.array.simple$ * 594. 最长和谐子序列 * 和谐数组是指一个数组里元素的最大值和最小值之间的差别 正好是 1 。 * 现在,给你一个整数数组 nums ,请你在所有可能的子序列中找到最长的和谐子序列的长度。 * 数组的子序列是一个由数组派生出来的序列,它可以通过删除一些元素或不删除元素、且不改变其余元素的顺序而得到。 * @author ll * @date 2021-10-14 09:23:47 **/ public class LongestHarmonicSubsequence594 { public static void main(String[] args) { int[] nums = new int[] {1,3,2,3}; int lhs2 = new LongestHarmonicSubsequence594().findLHS2(nums); System.out.println(lhs2); } /** * 自定义,完全暴力法 * @author ll * @date 2021-10-14 10:06:20 * @param nums * @return int **/ public int findLHS(int[] nums) { int max = 0; int leftFlag = -1; int rightFlag = 1; for (int i = 0; i < nums.length - 1; i++) { int leftSize = 0; int rightSize = 0; boolean left = false; boolean right = false; for (int j = i + 1; j < nums.length; j++) { if (nums[i] - nums[j] == leftFlag) { left = true; leftSize++; } else if (nums[i] - nums[j] == 0) { leftSize++; rightSize++; } else if (nums[i] - nums[j] == rightFlag) { right = true; rightSize++; } } if (left && leftSize != 0) { max = Math.max(max, leftSize + 1); } if (right && rightSize != 0) { max = Math.max(max, rightSize + 1); } } return max; } /** * 将每个数当作最小的数,找出比它大一或者相等的数即可 * @author ll * @date 2021-10-14 10:24:12 * @param nums * @return int **/ public int findLHS2(int[] nums) { int res = 0; for (int i = 0; i < nums.length; i++) { int count = 0; boolean flag = false; for (int j = 0; j < nums.length; j++) { if (nums[j] == nums[i]) count++; else if (nums[j] + 1 == nums[i]) { count++; flag = true; } } if (flag) res = Math.max(count, res); } return res; } /** * 方法二:哈希映射 * @author ll * @date 2021-10-14 10:24:57 * @param nums * @return int **/ public int findLHS3(int[] nums) { HashMap< Integer, Integer > map = new HashMap < > (); int res = 0; for (int num: nums) { map.put(num, map.getOrDefault(num, 0) + 1); } for (int key: map.keySet()) { if (map.containsKey(key + 1)) res = Math.max(res, map.get(key) + map.get(key + 1)); } return res; } /** * 哈希+一次扫描 * @author ll * @date 2021-10-14 10:31:39 * @param nums * @return int **/ public int findLHS4(int[] nums) { Map<Integer, Integer> map = new HashMap<>(); int res = 0; for (int num: nums) { map.put(num, map.getOrDefault(num, 0) + 1); if (map.containsKey(num + 1)) { res = Math.max(res, map.get(num) + map.get(num + 1)); } if (map.containsKey(num - 1)) { res = Math.max(res, map.get(num) + map.get(num - 1)); } } return res; } }
27.640625
70
0.447428
bbcb4d2d1c9262e9802731f32a955c9435059407
2,047
package dk.sebsa.amber_engine.rendering.overlays; import java.util.function.Consumer; import dk.sebsa.amber.graph.GUI; import dk.sebsa.amber.graph.Sprite; import dk.sebsa.amber.math.Rect; import dk.sebsa.amber_engine.Main; import dk.sebsa.amber_engine.editor.Editor; import dk.sebsa.amber_engine.rendering.Overlay; public class SaveWorld extends Overlay { public boolean close = false; private Consumer<answer> consumer; private Sprite box = Sprite.getSprite(GUI.sheet+".Box"); private Rect yesRect, noRect, cancelRect; private Rect layer; public SaveWorld(Consumer<answer> consumer) { close = false; this.consumer = consumer; yesRect = new Rect(5, 135, GUI.defaultFont.getStringWidth("Yes")+10, 24); noRect = new Rect(yesRect.x+yesRect.width+5, yesRect.y, GUI.defaultFont.getStringWidth("No")+6, 24); cancelRect = new Rect(noRect.x+noRect.width+5, yesRect.y, GUI.defaultFont.getStringWidth("Cancel")+5, 24); } @Override public boolean render() { GUI.window(layer, "Save World?", this::renderWindow, Editor.window); // CLose if(GUI.toggle(false, Main.window.getWidth()/2+282, Main.window.getHeight()/2-100+Editor.window.padding.height, null, Editor.x, 1)) { close = true; return true; } return false; } public void renderWindow(Rect r) { GUI.label("You are about to close and UNSAVED world?", 0, 0); GUI.label("Do you want to save first?", 0, 16); if(GUI.button("Yes", yesRect, Editor.button, Editor.buttonHover, GUI.Press.realesed, false, 1)) { close = true; consumer.accept(answer.yes); } else if(GUI.button("No", noRect, box, Editor.button, GUI.Press.realesed, false, 1)) { close = true; consumer.accept(answer.no); } else if(GUI.button("Cancel", cancelRect, box, Editor.button, GUI.Press.realesed, false, 1)) { close = true; consumer.accept(answer.cancel); } } @Override public boolean close() { if(close) return true; return false; } @Override public Rect layer() { layer = new Rect(Main.window.getWidth()/2-300, Main.window.getHeight()/2-100, 600, 200); return layer; } }
35.912281
163
0.721055
8491f62f9febf3e78acebcb8632e0f6e85860c0f
3,296
package com.ziroom.ziroomcustomer.ziroomstation.projectdetail.a; import android.content.Context; import android.support.v7.widget.RecyclerView.a; import android.support.v7.widget.RecyclerView.u; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import com.growingio.android.sdk.agent.VdsAgent; import com.growingio.android.sdk.instrumentation.Instrumented; import com.ziroom.ziroomcustomer.minsu.searchlist.model.StrategySearchListBean.DataBean.ListBean; import com.ziroom.ziroomcustomer.webview.JsBridgeWebActivity; import java.util.List; public class c extends RecyclerView.a<a> { private List<StrategySearchListBean.DataBean.ListBean> a; private Context b; public c(Context paramContext) { this.b = paramContext; } public int getItemCount() { int i = 3; if (this.a == null) { i = 0; } while (this.a.size() > 3) { return i; } return this.a.size(); } public void onBindViewHolder(a parama, int paramInt) { StrategySearchListBean.DataBean.ListBean localListBean = (StrategySearchListBean.DataBean.ListBean)this.a.get(paramInt); com.freelxl.baselibrary.f.c.loadHolderImage(parama.c, localListBean.getBannerImg()); parama.d.setText(localListBean.getCityName() + " · " + localListBean.getBusinessArea()); parama.e.setText(localListBean.getTitle()); parama.f.setText(localListBean.getSubCategory() + " | " + localListBean.getSubTitle()); parama.a.setTag(localListBean); parama.a.setOnClickListener(new View.OnClickListener() { @Instrumented public void onClick(View paramAnonymousView) { VdsAgent.onClick(this, paramAnonymousView); paramAnonymousView = (StrategySearchListBean.DataBean.ListBean)paramAnonymousView.getTag(); JsBridgeWebActivity.start(c.a(c.this), "城市攻略", paramAnonymousView.getTargetUrl(), paramAnonymousView.getSubTitle(), paramAnonymousView.getBannerImg(), true); } }); if (paramInt == 2) { parama.b.setVisibility(8); return; } parama.b.setVisibility(0); } public a onCreateViewHolder(ViewGroup paramViewGroup, int paramInt) { return new a(LayoutInflater.from(this.b).inflate(2130904559, paramViewGroup, false)); } public void setData(List<StrategySearchListBean.DataBean.ListBean> paramList) { this.a = paramList; notifyDataSetChanged(); } class a extends RecyclerView.u { View a; View b; SimpleDraweeView c; TextView d; TextView e; TextView f; public a(View paramView) { super(); this.a = paramView; this.c = ((SimpleDraweeView)paramView.findViewById(2131695349)); this.d = ((TextView)paramView.findViewById(2131690053)); this.e = ((TextView)paramView.findViewById(2131689541)); this.f = ((TextView)paramView.findViewById(2131690071)); this.b = paramView.findViewById(2131691738); } } } /* Location: /Users/gaoht/Downloads/zirom/classes4-dex2jar.jar!/com/ziroom/ziroomcustomer/ziroomstation/projectdetail/a/c.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
31.390476
165
0.712985
77091f3e4dd0450cca51e59e7ca6f5cdb1cebc7e
349
package com.touwolf.mailchimp.model.campaign; import com.google.gson.annotations.SerializedName; public enum CampaignTypeEnum { @SerializedName("regular") REGULAR, @SerializedName("plaintext") PLAIN_TEXT, @SerializedName("absplit") AB_SPLIT, @SerializedName("rss") RSS, @SerializedName("variate") VARIATE }
20.529412
50
0.707736
a3805b8732134cce1c5e87c9c61edc6face6789f
2,674
/* * Copyright 2012-2014 Sergey Ignatov * * 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.intellij.erlang.application; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.filters.TextConsoleBuilder; import com.intellij.execution.filters.TextConsoleBuilderFactory; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.ui.ConsoleView; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.text.StringUtil; import org.intellij.erlang.runconfig.ErlangRunningState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class ErlangApplicationRunningState extends ErlangRunningState { private final ErlangApplicationConfiguration myConfiguration; public ErlangApplicationRunningState(ExecutionEnvironment env, Module module, ErlangApplicationConfiguration configuration) { super(env, module); myConfiguration = configuration; } @Override protected boolean useTestCodePath() { return myConfiguration.isUseTestCodePath(); } @Override protected boolean isNoShellMode() { return true; } @Override protected boolean isStopErlang() { return myConfiguration.stopErlang(); } @Override protected List<String> getErlFlags() { return StringUtil.split(myConfiguration.getErlFlags(), " "); } @Nullable @Override public ErlangEntryPoint getEntryPoint() throws ExecutionException { ErlangEntryPoint entryPoint = ErlangEntryPoint.fromModuleAndFunction(myConfiguration.getModuleAndFunction(), myConfiguration.getParams()); if (entryPoint == null) { throw new ExecutionException("Invalid entry point"); } return entryPoint; } @Nullable @Override public String getWorkDirectory() { return myConfiguration.getWorkDirectory(); } @NotNull @Override public ConsoleView createConsoleView(Executor executor) { TextConsoleBuilder consoleBuilder = TextConsoleBuilderFactory.getInstance().createBuilder(myConfiguration.getProject()); return consoleBuilder.getConsole(); } }
31.833333
142
0.780105
2bcc65a1934868f376b5cd5930e2cb584d6c871a
2,365
package com.njh.socket.TCPSocketHalfDuplexContact; import java.io.*; import java.net.Socket; import java.util.Scanner; /** *ClassName: SocketClient *Description: 半双工通信客户端 *Author: njh *Time: ,14:47 *Version: V1.0 * **/ public class SocketClient{ private Socket socket;//使用TCP协议 //private DatagramSocket datagramSocket; //可以用UDP协议 public SocketClient(String ip, int port){ try{ socket = new Socket(ip,port); start(); } catch(Exception e){ e.printStackTrace(); } } public void start() throws Exception{ //获取socket传过来的字节流转成缓冲流,以提高性能 BufferedInputStream bis = new BufferedInputStream(socket.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream()); //将字节流转成字符流 InputStreamReader isr = new InputStreamReader(bis); //OutputStreamWriter osw = new OutputStreamWriter(bos); PrintWriter pw = new PrintWriter(bos); //获取服务器传来的信息 BufferedReader br = new BufferedReader(isr); //结束语为over String info = ""; while(!info.equals("over")){//规定:服务器先发送信息,读写顺序不能乱不然会阻塞 //先读取信息 info = br.readLine();//查看源码发现BufferReader的readLine()加锁后对\n跳过,所以之前加\n或者\r已经不再适用。除非提前在append \n或\r时加锁 //I/O阻塞也可以通过多线程来规避 if(!info.equals("")&&info.length()!=0) System.out.println("Server send message : " + info); //再写信息 Scanner sc = new Scanner(System.in); info = sc.nextLine(); System.out.println("Send to Server : " + info); //osw.write(info); //osw.flush(); pw.println(info);//为什么选择PrintWriter而不是OutputStreamWriter? pw.flush(); //是因为BufferReader.readLine()是阻塞的,除非遇到换行或者回车符号,不然不会继续执行 //查看PrintWriter.println()源码后发现在print(info)后又调用了println()。正好构成了换行 } //关闭读取流 br.close(); //关闭字符流 //osw.close(); isr.close(); pw.close(); //关闭缓冲流 bos.close(); bis.close(); //关闭socket连接 socket.close(); } public static void main(String[] args){ new SocketClient("127.0.0.1",6666); } }
30.714286
112
0.557717
97734ae0c1805af6e32986b65d48110a7758ec0e
250
package lambda.rodeo.lang.values; import lombok.Builder; import lombok.EqualsAndHashCode; @Builder @EqualsAndHashCode public class Constant<T> { private final T value; @Override public String toString() { return value.toString(); } }
14.705882
33
0.74
bf2e1ca862572e9fa6d66339da6b3bdafc58213b
1,919
/** * Copyright (c) Dell Inc., or its subsidiaries. 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 */ package io.pravega.authplugin.basic; import io.pravega.auth.AuthHandler; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class AccessControlEntryTest { @Test public void fromStringWithNoSpaces() { AccessControlEntry ace = AccessControlEntry.fromString("prn::*,READ"); assertNotNull(ace); assertEquals("prn::.*", ace.getResourcePattern()); assertEquals(AuthHandler.Permissions.READ, ace.getPermissions()); } @Test public void fromStringWithEmptySpaces() { AccessControlEntry ace = AccessControlEntry.fromString(" prn::* , READ "); // with spaces assertNotNull(ace); assertEquals("prn::.*", ace.getResourcePattern()); assertEquals(AuthHandler.Permissions.READ, ace.getPermissions()); } @Test public void fromStringInstantiatesNullObjectIfInputIsBlank() { assertNull(AccessControlEntry.fromString(null)); assertNull(AccessControlEntry.fromString("")); assertNull(AccessControlEntry.fromString(" ")); } @Test public void fromStringInstantiatesNullObjectIfInputIsInvalid() { assertNull(AccessControlEntry.fromString("ABC")); // permission missing assertNull(AccessControlEntry.fromString(",READ")); // resource string/pattern missing assertNull(AccessControlEntry.fromString("prn::/,INVALID_PERMISSION")); // invalid permission assertNull(AccessControlEntry.fromString(",,READ")); // resource string/pattern missing } }
36.903846
101
0.711308
6d2843dda4185bb61d3cffd99f37003b569c093d
632
package page21.q2097; import java.util.Arrays; import java.util.Scanner; public class Main { private static boolean b[] = new boolean[10]; public static void main(String[] args) { Scanner in = new Scanner(System.in); boolean f = true; for(int i=in.nextInt(), m=in.nextInt(); i<=m; i++) if(isDistinct(i)) { f = false; System.out.println(i); } if(f) System.out.println(); } private static boolean isDistinct(int n) { Arrays.fill(b, false); for(char c : String.valueOf(n).toCharArray()) if(b[c-'0']) return false; else b[c-'0'] = true; return true; } }
22.571429
54
0.601266
06ee017c4cce39863cdf6fe30ca81db8ab572a6f
882
package thundr.redstonerepository.item.tool; import cofh.redstonearsenal.item.tool.ItemSickleFlux; import net.minecraft.item.EnumRarity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import thundr.redstonerepository.item.GelidEnderiumEnergy; public class ItemSickleGelid extends ItemSickleFlux { public ItemSickleGelid(Item.ToolMaterial toolMaterial) { super(toolMaterial); this.maxEnergy = GelidEnderiumEnergy.maxEnergy; this.energyPerUse = GelidEnderiumEnergy.energyPerUse; this.energyPerUseCharged = GelidEnderiumEnergy.energyPerUseCharged; this.maxTransfer = GelidEnderiumEnergy.maxTransfer; this.radius = 5; } public EnumRarity getRarity(ItemStack stack) { return EnumRarity.RARE; } public int getRGBDurabilityForDisplay(ItemStack stack) { return 1333581; } }
30.413793
75
0.756236
0fa9d7935919016418d63f41c029a50c1f80d99a
1,686
package com.shsrobotics.library.joysticks; /** * Logitech Extreme 3-D Controller button mappings. * @author Team 2412 <first.robototes.com, github.com/robototes> */ public class Extreme3DController { /** Trigger. */ public static final int trigger = 1; /** Button 2. Side-key at the joystick top */ public static final int side = 2; /** Button 3. The top four buttons form a square. This one is the bottom left one. */ public static final int topBottomLeft = 3; /** Button 4. The top four buttons form a square. This one is the bottom right one. */ public static final int topBottomRight = 4; /** Button 5. The top four buttons form a square. This one is the top left one. */ public static final int topTopLeft = 5; /** Button 6. The top four buttons form a square. This one is the top right one. */ public static final int topTopRight = 6; /** Button 7. There are six base buttons. This one is the farthest away on the left. */ public static final int baseFrontLeft = 7; /** Button 8. There are six base buttons. This one is the farthest away on the right. */ public static final int baseFrontRight = 8; /** Button 9. There are six base buttons. This one is in the middle on the left. */ public static final int baseCenterLeft = 9; /** Button 10. There are six base buttons. This one is in the middle on the right. */ public static final int baseCenterRight = 10; /** Button 11. There are six base buttons. This one is the nearest on the left. */ public static final int baseRearLeft = 11; /** Button 12. There are six base buttons. This one is the nearest on the right. */ public static final int baseRearRight = 12; }
36.652174
89
0.702847
afa312dfbbb7142b5d4c603f9637ac030dcecc20
1,951
package com.archos.filemanager.dialog; import android.content.Intent; import android.os.Bundle; import com.archos.filemanager.ShortcutDb; import com.archos.filemanager.network.shortcuts.ShortcutsFragment; import com.archos.environment.ArchosUtils; /** * Created by vapillon on 13/04/16. */ public class ShortcutRenameDialog extends RenameDialog { public static final String ARG_SHORTCUT_ID = "shortcut_id"; long mShortcutId; String mOriginalName; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle arg = getArguments(); mShortcutId = arg.getLong(ARG_SHORTCUT_ID, -1); if (mShortcutId < 0) { throw new IllegalArgumentException("Rename dialog needs a ARG_SHORTCUT_ID as argument"); } mOriginalName = ShortcutDb.STATIC.getShortcutName(mShortcutId); } @Override public String getOriginalName() { return mOriginalName; } @Override public void performRenaming(String newName) { final boolean success = ShortcutDb.STATIC.renameShortcut(mShortcutId, newName); mHandler.sendEmptyMessage(success ? RENAME_SUCCESS : RENAME_FAILED); mHandler.post(new Runnable() { public void run() { if (success) { Intent intent1 = new Intent(ShortcutsFragment.ACTION_REFRESH_SHORTCUTS_FRAGMENT); intent1.setPackage(ArchosUtils.getGlobalContext().getPackageName()); getActivity().sendBroadcast(intent1); Intent intent2 = new Intent(ShortcutsFragment.ACTION_STOP_ACTION_MODE); intent2.setPackage(ArchosUtils.getGlobalContext().getPackageName()); getActivity().sendBroadcast(intent2); renameSuccess(); } else { renameFail(); } } }); } }
33.067797
101
0.646848
afcc1687293c7baf95fb65382b0d10f07e4dcade
223
package com.xp.basics.inter_face; /** * Test1.java 测试1 * * @author: zhaoxiaoping * @date: 2019/08/06 **/ public class Test1 implements TestInterface { @Override public String getName() { return "test1"; } }
14.866667
45
0.659193
2d1905f719dd92db709e6860bada9996c81a33b4
2,317
/* * This Java source file was generated by the Gradle 'init' task. */ package dev.random.discord.bot; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.entities.Activity; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageChannel; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.utils.Compression; import net.dv8tion.jda.api.utils.cache.CacheFlag; import javax.security.auth.login.LoginException; import java.util.Random; public class App { public static void main(String[] args) throws LoginException, InterruptedException { //Start JDABuilder builder = JDABuilder.createDefault(args[0]); // Disable parts of the cache builder.disableCache(CacheFlag.MEMBER_OVERRIDES, CacheFlag.VOICE_STATE); // Enable the bulk delete event builder.setBulkDeleteSplittingEnabled(true); // Disable compression (not recommended) builder.setCompression(Compression.NONE); // Set activity (like "playing Something") JDA jda = builder.build(); jda.setAutoReconnect(true); jda.awaitReady(); (new Thread(() -> { final String[] activities = {"rm -rf /", "Coding in HTML", "Debugging my debugger"}; final Random rand = new Random(); while (true) { jda.getPresence().setActivity(Activity.playing(activities[rand.nextInt(activities.length)])); // Wait long start = System.currentTimeMillis(); while (System.currentTimeMillis() - start < 60000) { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } }, "Periodic activity changer thread")).start(); jda.addEventListener(new ListenerAdapter() { @Override public void onMessageReceived(MessageReceivedEvent event) { if (!event.getAuthor().isBot()) { String msg = event.getMessage().getContentRaw(); } } }); } }
35.646154
109
0.615019
6ca40aa39a61980125e33362b377696c1509ce4c
488
package telnetthespire.commands.parsers; import telnetthespire.commands.Command; import telnetthespire.commands.annotations.Name; import telnetthespire.commands.handlers.State; import java.util.Vector; @Name("state") public class StateParser extends CommandParser { public StateParser() { } @Override public boolean isAvailable() { return true; } @Override public Command parse(Vector<Object> arguments) { return new State(this); } }
19.52
52
0.717213
70698e436bf9289d57a989765b626ba2f71541ba
756
package h6getallen; import java.applet.Applet; import java.awt.*; /** * Created by Mike on 9/18/2016. * */ public class PraktijkOpdrH6Getallen extends Applet { private double combineerd; private double verdeeld; public void init() { double cijfer1 = 5.9; double cijfer2 = 6.3; double cijfer3 = 6.9; combineerd = cijfer1 + cijfer2 + cijfer3; double gemiddelde = combineerd / 3; double vermenig = gemiddelde * 10; int afkap = (int) vermenig; verdeeld = (double) afkap / 10; } public void paint(Graphics g) { g.drawString("De Drie cijfers samen zijn: " + combineerd, 100, 50); g.drawString("Het gemiddelde is: " + verdeeld, 100, 100); } }
19.384615
75
0.607143
00fa073f838ba07f7df721689f8b5efbdd6a2229
2,689
/* * 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.action.index; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.test.ESSingleNodeTestCase; import org.junit.Test; import static org.hamcrest.Matchers.is; public class TransportIndexActionIT extends ESSingleNodeTestCase { /** * Validates that the autoGeneratedId index request attribute is correctly passed to the * {@link org.elasticsearch.index.engine.Engine.Create} class. */ @Test public void testPrepareIndexOperationOnPrimaryCreateWithoutAutoGeneratedId() throws Exception { createIndex("test"); IndicesService indicesService = getInstanceFromNode(IndicesService.class); IndexService indexService = indicesService.indexService("test"); IndexShard indexShard = indexService.shard(0); TestIndexRequest indexRequest = new TestIndexRequest("test", "type", "1"); indexRequest.timestamp("0"); indexRequest.source("{}"); indexRequest.opType(IndexRequest.OpType.CREATE); indexRequest.setCanHaveDuplicates(); Engine.Create create = (Engine.Create) TransportIndexAction.prepareIndexOperationOnPrimary(null, indexRequest, indexShard); assertThat(create.canHaveDuplicates(), is(true)); assertThat(create.autoGeneratedId(), is(false)); } static class TestIndexRequest extends IndexRequest { boolean canHaveDuplicates = false; public TestIndexRequest(String index, String type, String id) { super(index, type, id); } public void setCanHaveDuplicates() { canHaveDuplicates = true; } @Override public boolean canHaveDuplicates() { return canHaveDuplicates; } } }
36.835616
104
0.722945
622d77948c8c99ba49d72e2cfe86be229a4d42a6
519
private static int[] insertSort(int[] seq, boolean isASC) { int[] tmp_seq = new int[seq.length]; System.arraycopy(seq, 0, tmp_seq, 0, seq.length); for (int i = 1; i < tmp_seq.length; i++) { int tmp = tmp_seq[i]; int j = i - 1; while (j >= 0 && (isASC? (tmp_seq[j] > tmp) : (tmp_seq[j] < tmp))) { tmp_seq[j + 1] = tmp_seq[j]; j--; } tmp_seq[j + 1] = tmp; } return tmp_seq; }
32.4375
80
0.433526
ad5adcf1082117c7b84dbc3487e77e24e281c3d4
3,651
package com.airbnb.reair.db; import com.airbnb.reair.common.Container; import com.airbnb.reair.utils.RetryableTask; import com.airbnb.reair.utils.RetryingTaskRunner; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Optional; /** * A simple string key/value store using a DB. */ public class DbKeyValueStore { private static final Log LOG = LogFactory.getLog(DbKeyValueStore.class); private DbConnectionFactory dbConnectionFactory; private String dbTableName; private RetryingTaskRunner retryingTaskRunner = new RetryingTaskRunner(); /** * Constructor. * * @param dbConnectionFactory connection factory to use for connecting to the DB * @param dbTableName name of the table containing the keys and values */ public DbKeyValueStore(DbConnectionFactory dbConnectionFactory, String dbTableName) { this.dbTableName = dbTableName; this.dbConnectionFactory = dbConnectionFactory; } /** * Get the create table command for the key/value table. * * @param tableName name of the table * @return SQL that can be executed to create the table */ public static String getCreateTableSql(String tableName) { return String.format("CREATE TABLE `%s` (\n" + " `update_time` timestamp NOT NULL DEFAULT " + "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n" + " `key_string` varchar(256) NOT NULL,\n" + " `value_string` varchar(4000) DEFAULT NULL,\n" + " PRIMARY KEY (`key_string`)\n" + ") ENGINE=InnoDB", tableName); } /** * Get the value of the key. * * @param key name of the key * @return the value associated with they key * * @throws SQLException if there's an error querying the DB */ public Optional<String> get(String key) throws SQLException { Connection connection = dbConnectionFactory.getConnection(); String query = String.format("SELECT value_string FROM %s " + "WHERE key_string = ? LIMIT 1", dbTableName); PreparedStatement ps = connection.prepareStatement(query); try { ps.setString(1, key); ResultSet rs = ps.executeQuery(); if (rs.next()) { return Optional.ofNullable(rs.getString(1)); } else { return Optional.empty(); } } finally { ps.close(); ps = null; } } /** * Sets the value for a key, retrying if necessary. * * @param key the key to set * @param value the value to associate with the key */ public void resilientSet(final String key, final String value) { retryingTaskRunner.runUntilSuccessful(new RetryableTask() { @Override public void run() throws Exception { set(key, value); } }); } /** * Sets the value for a key. * * @param key the key to set * @param value the value to associate with the key * * @throws SQLException if there's an error querying the DB */ public void set(String key, String value) throws SQLException { LOG.debug("Setting " + key + " to " + value); Connection connection = dbConnectionFactory.getConnection(); String query = String.format("INSERT INTO %s (key_string, value_string) " + "VALUE (?, ?) ON DUPLICATE KEY UPDATE value_string = ?", dbTableName); PreparedStatement ps = connection.prepareStatement(query); try { ps.setString(1, key); ps.setString(2, value); ps.setString(3, value); ps.executeUpdate(); } finally { ps.close(); ps = null; } } }
29.92623
100
0.672966
96d5b653a9754b367630f656a688f5d1bad9fbce
914
package org.roaringbitmap.buffer; import java.nio.LongBuffer; import org.junit.Test; import org.roaringbitmap.BitmapContainer; public class TestMappeableBitmapContainer { @Test(expected = IndexOutOfBoundsException.class) public void testPreviousTooSmall() { emptyContainer().prevSetBit(-1); } @Test(expected = IndexOutOfBoundsException.class) public void testPreviousTooLarge() { emptyContainer().prevSetBit(Short.MAX_VALUE + 1); } @Test(expected = IndexOutOfBoundsException.class) public void testNextTooSmall() { emptyContainer().nextSetBit(-1); } @Test(expected = IndexOutOfBoundsException.class) public void testNextTooLarge() { emptyContainer().nextSetBit(Short.MAX_VALUE + 1); } private static MappeableBitmapContainer emptyContainer() { return new MappeableBitmapContainer(0, LongBuffer.allocate(1)); } }
28.5625
71
0.719912
a9ab308fc304881d85bedb8b6711b0052b63dc8f
542
package com.rollbar.reactivestreams.notifier.sender.http; import java.util.Map; import java.util.Set; /** * Data for an asynchronous, non-blocking HTTP request. */ public interface AsyncHttpRequest { String getUrl(); Iterable<Map.Entry<String, String>> getHeaders(); String getBody(); class Builder { public static AsyncHttpRequest build(String url, Set<Map.Entry<String, String>> headers, String reqBody) { return new AsyncHttpRequestImpl(url, headers, reqBody); } } }
23.565217
92
0.671587
58651c943a352258014e578d2d5dbaeb55324c80
8,174
package de.metas.handlingunits.attribute.impl; import java.math.BigDecimal; import java.util.Collection; /* * #%L * de.metas.handlingunits.base * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.stream.Stream; import org.adempiere.ad.dao.ICompositeQueryFilter; import org.adempiere.ad.dao.IQueryBL; import org.adempiere.ad.dao.IQueryBuilder; import org.adempiere.ad.trx.api.ITrx; import org.adempiere.mm.attributes.api.IAttributeDAO; import org.adempiere.model.InterfaceWrapperHelper; import org.compiere.model.I_M_Attribute; import org.compiere.model.X_M_Attribute; import org.compiere.util.Env; import org.compiere.util.Util.ArrayKey; import org.eevolution.model.I_PP_Cost_Collector; import org.eevolution.model.I_PP_Order; import org.slf4j.Logger; import de.metas.handlingunits.attribute.IPPOrderProductAttributeDAO; import de.metas.handlingunits.model.I_M_HU_Attribute; import de.metas.handlingunits.model.I_PP_Order_ProductAttribute; import de.metas.handlingunits.model.I_PP_Order_Qty; import de.metas.logging.LogManager; import de.metas.util.GuavaCollectors; import de.metas.util.Services; public class PPOrderProductAttributeDAO implements IPPOrderProductAttributeDAO { private static final transient Logger logger = LogManager.getLogger(PPOrderProductAttributeDAO.class); @Override public List<I_PP_Order_ProductAttribute> retrieveProductAttributesForPPOrder(final int ppOrderId) { final IQueryBL queryBL = Services.get(IQueryBL.class); return queryBL.createQueryBuilder(I_PP_Order_ProductAttribute.class, Env.getCtx(), ITrx.TRXNAME_ThreadInherited) .addEqualsFilter(I_PP_Order_ProductAttribute.COLUMNNAME_PP_Order_ID, ppOrderId) .addOnlyActiveRecordsFilter() .create() .list(I_PP_Order_ProductAttribute.class); } private Stream<I_PP_Order_ProductAttribute> streamProductAttributesForHUAttributes(final int ppOrderId, final Collection<I_M_HU_Attribute> huAttributes) { if (huAttributes.isEmpty()) { return Stream.empty(); } final IQueryBL queryBL = Services.get(IQueryBL.class); final IQueryBuilder<I_PP_Order_ProductAttribute> queryBuilder = queryBL.createQueryBuilder(I_PP_Order_ProductAttribute.class, Env.getCtx(), ITrx.TRXNAME_ThreadInherited) .addEqualsFilter(I_PP_Order_ProductAttribute.COLUMNNAME_PP_Order_ID, ppOrderId) .addOnlyActiveRecordsFilter(); final ICompositeQueryFilter<I_PP_Order_ProductAttribute> huFilters = queryBuilder.addCompositeQueryFilter().setJoinOr(); huAttributes.forEach(huAttribute -> { huFilters.addCompositeQueryFilter().setJoinAnd() .addEqualsFilter(I_PP_Order_ProductAttribute.COLUMNNAME_M_HU_ID, huAttribute.getM_HU_ID()) .addEqualsFilter(I_PP_Order_ProductAttribute.COLUMNNAME_M_Attribute_ID, huAttribute.getM_Attribute_ID()); }); return queryBuilder .create() .stream(I_PP_Order_ProductAttribute.class); } @Override public void addPPOrderProductAttributes(final I_PP_Cost_Collector costCollector, final List<I_M_HU_Attribute> huAttributes) { if (huAttributes.isEmpty()) { return; } final I_PP_Order ppOrder = costCollector.getPP_Order(); addPPOrderProductAttributes(ppOrder, huAttributes, ppOrderAttribute -> ppOrderAttribute.setPP_Cost_Collector(costCollector)); } @Override public void addPPOrderProductAttributesFromIssueCandidate(final I_PP_Order_Qty issueCandidate, final List<I_M_HU_Attribute> huAttributes) { if (huAttributes.isEmpty()) { return; } final I_PP_Order ppOrder = issueCandidate.getPP_Order(); addPPOrderProductAttributes(ppOrder, huAttributes, ppOrderAttribute -> { // ppOrderAttribute.setPP_Order_Qty(issueCandidate); // TODO: shall we add it? }); } private void addPPOrderProductAttributes(final I_PP_Order ppOrder, final List<I_M_HU_Attribute> huAttributes, final Consumer<I_PP_Order_ProductAttribute> beforeSave) { final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class); // // Fetch the existing PP_Order_ProductAttribute records matching given huAttributes (matched by M_HU_ID/M_Attribute_ID) final Map<ArrayKey, I_PP_Order_ProductAttribute> existingPPOrderAttributes = streamProductAttributesForHUAttributes(ppOrder.getPP_Order_ID(), huAttributes) .collect(GuavaCollectors.toHashMapByKey(ppOrderAttribute -> ArrayKey.of(ppOrderAttribute.getM_HU_ID(), ppOrderAttribute.getM_Attribute_ID()))); // // Iterate and create/update one PP_Order_ProductAttribute for each HU_Attribute for (final I_M_HU_Attribute huAttribute : huAttributes) { final I_M_Attribute attribute = attributesRepo.getAttributeById(huAttribute.getM_Attribute_ID()); // // Find existing PP_Order_ProductAttribute or create a new one final ArrayKey key = ArrayKey.of(huAttribute.getM_HU_ID(), huAttribute.getM_Attribute_ID()); final I_PP_Order_ProductAttribute ppOrderAttribute = existingPPOrderAttributes.computeIfAbsent(key, k -> { final I_PP_Order_ProductAttribute ppOrderAttributeNew = InterfaceWrapperHelper.newInstance(I_PP_Order_ProductAttribute.class); ppOrderAttributeNew.setAD_Org_ID(ppOrder.getAD_Org_ID()); ppOrderAttributeNew.setPP_Order(ppOrder); ppOrderAttributeNew.setM_Attribute_ID(attribute.getM_Attribute_ID()); ppOrderAttributeNew.setM_HU_ID(huAttribute.getM_HU_ID()); // provenance HU return ppOrderAttributeNew; }); // // Set Value/ValueNumber final String attributeValueType = attribute.getAttributeValueType(); if (X_M_Attribute.ATTRIBUTEVALUETYPE_Number.equals(attributeValueType)) { ppOrderAttribute.setValue(null); final BigDecimal valueNumber = InterfaceWrapperHelper.getValueOrNull(huAttribute, I_M_HU_Attribute.COLUMNNAME_ValueNumber); ppOrderAttribute.setValueNumber(valueNumber); } else if (X_M_Attribute.ATTRIBUTEVALUETYPE_Date.equals(attributeValueType)) { // TODO: introduce PP_Order_ProductAttribute.ValueDate continue; } else if (X_M_Attribute.ATTRIBUTEVALUETYPE_StringMax40.equals(attributeValueType) || X_M_Attribute.ATTRIBUTEVALUETYPE_List.equals(attributeValueType)) { ppOrderAttribute.setValue(huAttribute.getValue()); ppOrderAttribute.setValueNumber(null); } else { logger.warn("AttributeValueType {} not supported for {} / {}", attributeValueType, attribute, huAttribute); continue; } // Execute beforeSave custom code beforeSave.accept(ppOrderAttribute); // save it InterfaceWrapperHelper.save(ppOrderAttribute); } } @Override public void deactivateForCostCollector(final int costCollectorId) { final IQueryBL queryBL = Services.get(IQueryBL.class); queryBL.createQueryBuilder(I_PP_Order_ProductAttribute.class) .addEqualsFilter(org.eevolution.model.I_PP_Order_ProductAttribute.COLUMNNAME_PP_Cost_Collector_ID, costCollectorId) .addOnlyActiveRecordsFilter() .create() .updateDirectly() .addSetColumnValue(org.eevolution.model.I_PP_Order_ProductAttribute.COLUMNNAME_IsActive, false) // deactivate all for cost collector .execute(); } @Override public void deleteForHU(final int ppOrderId, final int huId) { final IQueryBL queryBL = Services.get(IQueryBL.class); queryBL.createQueryBuilder(I_PP_Order_ProductAttribute.class) .addEqualsFilter(I_PP_Order_ProductAttribute.COLUMNNAME_PP_Order_ID, ppOrderId) .addEqualsFilter(I_PP_Order_ProductAttribute.COLUMNNAME_M_HU_ID, huId) .addOnlyActiveRecordsFilter() .create() .deleteDirectly(); } }
38.375587
171
0.797651
6598b4d7c2bbed4bdcf1660fb25bbcb52029aff7
794
package uk.gov.dft.bluebadge.webapp.la.controller.utils; import java.io.Serializable; import java.util.Comparator; import java.util.List; import org.apache.commons.lang3.math.NumberUtils; import uk.gov.dft.bluebadge.common.api.model.ErrorErrors; public class ErrorComparator implements Comparator<ErrorErrors>, Serializable { private List<String> errorListOrder; public ErrorComparator(List<String> errorListOrder) { this.errorListOrder = errorListOrder; } @Override public int compare(ErrorErrors o1, ErrorErrors o2) { String field1 = o1.getField(); String field2 = o2.getField(); int field1Index = this.errorListOrder.indexOf(field1); int field2Index = this.errorListOrder.indexOf(field2); return NumberUtils.compare(field1Index, field2Index); } }
27.37931
79
0.768262
f171d62a0bacc712861ae2721a52b2caf5587982
617
/* * Copyright 2019-2020 VMware, Inc. * SPDX-License-Identifier: BSD-2-Clause * */ package samples.vm.model; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import lombok.Getter; import lombok.Setter; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "deviceType") @JsonSubTypes({ @JsonSubTypes.Type(value = VirtualDisk.class), @JsonSubTypes.Type(value = VirtualUSB.class) }) public class VirtualDevice { @Getter @Setter private int key; @Getter @Setter private String deviceName; }
22.851852
102
0.740681
9372ae1c4bc1f3f23fb17f174877a17ba7081c69
94
package js.util.iterable; public interface StringIterableIterable extends StringIterable { }
18.8
64
0.840426
089781ec907e212030cc664861f3741abad8e1f2
10,780
/* * Copyright (c) 2020 DLR Institute of Transport Research * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package de.dlr.ivf.tapas.tools; import de.dlr.ivf.tapas.persistence.db.TPS_DB_IO; import de.dlr.ivf.tapas.tools.persitence.db.TPS_BasicConnectionClass; import de.dlr.ivf.tapas.util.Matrix; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class TPS_ParkingSpaceAproximator extends TPS_BasicConnectionClass { Map<Integer, Integer> personsPerTaz = new HashMap<>(); Map<Integer, Integer> carsPerTaz = new HashMap<>(); Map<Integer, Integer> areaPerTaz = new HashMap<>(); int maxTAZ = Integer.MIN_VALUE, minTAZ = Integer.MAX_VALUE, numberOfTaz = 0; double[] access = new double[0]; double[] egress = new double[0]; double maxEgress = 0; double minEgress = Integer.MAX_VALUE; double maxAccess = 0; double minAccess = Integer.MAX_VALUE; public static void main(String[] args) { String key = "VEU2_MID2008_Y2010_REF"; String accessName = "MIT_ACCESS_1223_" + key; String egressName = "MIT_EGRESS_1223_" + key; String region = "berlin"; //lets boogie! TPS_ParkingSpaceAproximator worker = new TPS_ParkingSpaceAproximator(); System.out.println("Loading tazes and areas for region " + region); worker.loadTazArea("core." + region + "_taz_1223_multiline"); System.out.println("Found " + worker.numberOfTaz + " tazes!"); System.out.println("Loading households and cars for key " + key); worker.loadPersonsAndCars("core." + region + "_households_1223", key); System.out.println("Calc parking times"); worker.calcParkingTimes(10, 1000, 2.8, 100, 1, 0.9); System.out.println("Access min/max: " + worker.minAccess + "/" + worker.maxAccess); System.out.println("Egress min/max: " + worker.minEgress + "/" + worker.maxEgress); System.out.println("Save access/egress " + accessName + "-" + egressName); worker.storeSQLMatrix("core." + region + "_matrices", egressName, accessName); System.out.println("Finished"); } /** * Theory behind it: * <p> * 1. Searching for a parking lot: * The probability to find a parking lot in a area with a fixed * availability of parking spaces increases linearly with the * street length covered. * The availability of parking lots decreases linearly with the density * of cars is a specific region. * ->Extension: We found this true for the first 90%! So interpolate between 0 and the 80%-Median * So we interpolate between a given minimum (e. g. 10 m) and * maximum search distance (e.g. 1500m). * Additionally a search speed is needed to calculate the search time. * <p> * 2. Going back to your original destination * If you found a parking lot, you have to walk back to your * original destination. But the search-strategy is most probable a spiral * around the original destination. We assume grid-blocks (Manhattan style). * The search strategy is as follows: * First round you drive around the block, called center block (4 Streets) * Second round you drive around the cross around the center block (12 streets -draw it!) * Third round you drive around the diamond arount the cros (20 streets) * Forth round 28 Streets... * <p> * When you draw it you see that the length of the search line increases * by eight segments every round (plus + street to the next circle, * but we ommit that ;) ) * <p> * The length of going back to the origin is the number of rounds but the * length of the search distance is the sum of street segments for all rounds * <p> * So if you know the block distance, a walking speed and have a search * length for finding a lot, you can calculate the walking distance * between lot and destination. * * @param minSearch the minimum search distance in meters eg 10m * @param maxSearch the maximum search distance in meters e.g. 1500m * @param searchSpeedCar the speed during the search in m/s (e.g. 14.4km/h = 4m/s) * @param blockDistance the average block length in meters (e.g. 1000) * @param walkSpeed the speed going back in m/s (e.g. 3.6km/h = 1m/s) * @param saturationFactor is the factor between 0 and 1, how many regions are affected by less than the maximum search radius. */ public void calcParkingTimes(double minSearch, double maxSearch, double searchSpeedCar, double blockDistance, double walkSpeed, double saturationFactor) { this.access = new double[this.numberOfTaz]; this.egress = new double[this.numberOfTaz]; double[] egressSort = new double[this.numberOfTaz]; double highestDensity = 0, lowestDensity = 1e99, density; int carsPerTaz, areaPerTaz; //first calc the density and find the normalization factors for (Integer taz : this.carsPerTaz.keySet()) { carsPerTaz = this.carsPerTaz.get(taz); areaPerTaz = this.areaPerTaz.get(taz); density = ((double) carsPerTaz) * 1000000.0 / (double) areaPerTaz; this.egress[taz - minTAZ] = density; egressSort[taz - minTAZ] = density; highestDensity = Math.max(highestDensity, density); lowestDensity = Math.min(lowestDensity, density); } saturationFactor = Math.max(0., Math.min(1.0, saturationFactor)); Arrays.sort(egressSort); lowestDensity = egressSort[0]; int indexSaturation = (int) ((egressSort.length - 1) * saturationFactor); //chop to reasonabele values indexSaturation = Math.max(1, Math.min(egressSort.length - 1, indexSaturation)); highestDensity = egressSort[indexSaturation]; //now normalize the density to the min/max searchradius for (int i = 0; i < egress.length; ++i) { //normalize from 0 to 1 this.egress[i] = (egress[i] - lowestDensity) / (highestDensity - lowestDensity); //extract from min to max this.egress[i] = egress[i] * (maxSearch - minSearch) + minSearch; //in egress is now the search distance to find a parking lot //now calculate the walking time back and put it in access int round = 1; double distanceCovered = 4 * blockDistance; while (distanceCovered < egress[i]) { round++; distanceCovered += 8 * blockDistance + distanceCovered; } //ok we have now the number of rounds to circle around the destination //now calculate the time to get there: this.access[i] = round * blockDistance / walkSpeed; this.maxAccess = Math.max(this.maxAccess, this.access[i]); this.minAccess = Math.min(this.minAccess, this.access[i]); //ok now we calculate the egress time: //search distance/search speed + walking time back this.egress[i] = this.egress[i] / searchSpeedCar + this.access[i]; this.maxEgress = Math.max(this.maxEgress, this.egress[i]); this.minEgress = Math.min(this.minEgress, this.egress[i]); } } public void loadPersonsAndCars(String db, String key) { String query = ""; try { query = "SELECT hh_taz_id, sum(hh_persons)::integer as persons, sum(hh_cars)::integer as cars FROM " + db + " WHERE hh_key= '" + key + "' group by hh_taz_id"; ResultSet rs = this.dbCon.executeQuery(query, this); int taz; int persons; int cars; while (rs.next()) { taz = rs.getInt("hh_taz_id"); persons = rs.getInt("persons"); cars = rs.getInt("cars"); this.personsPerTaz.put(taz, persons); this.carsPerTaz.put(taz, cars); } } catch (SQLException e) { System.err.println( this.getClass().getCanonicalName() + " readParameters: SQL-Error during statement: " + query); e.printStackTrace(); } } public void loadTazArea(String db) { String query = ""; try { query = "SELECT gid, st_area(geography(the_geom))::integer as sqrmeter FROM " + db; ResultSet rs = this.dbCon.executeQuery(query, this); int taz; int area; while (rs.next()) { taz = rs.getInt("gid"); area = rs.getInt("sqrmeter"); this.areaPerTaz.put(taz, area); maxTAZ = Math.max(maxTAZ, taz); minTAZ = Math.min(minTAZ, taz); } numberOfTaz = 1 + maxTAZ - minTAZ; } catch (SQLException e) { System.err.println( this.getClass().getCanonicalName() + " readParameters: SQL-Error during statement: " + query); e.printStackTrace(); } } public void storeSQLMatrix(String db, String nameEgress, String nameAccess) { //delete old values String query = "DELETE FROM " + db + " WHERE matrix_name= '" + nameEgress + "'"; this.dbCon.execute(query, this); query = "DELETE FROM " + db + " WHERE matrix_name= '" + nameAccess + "'"; this.dbCon.execute(query, this); //create the access/egress matrix: //Egress: all values TO this cell have the same egress //Access: all values FROM this cell have the same access Matrix egressM = new Matrix(this.egress.length); Matrix accessM = new Matrix(this.access.length); for (int i = 0; i < this.egress.length; ++i) { for (int j = 0; j < this.egress.length; ++j) { egressM.setValue(i, j, this.egress[i]); //same destination (i) accessM.setValue(i, j, this.access[j]); //same origin (j) } } //save to db! query = "INSERT INTO " + db + " (\"matrix_name\",\"matrix_values\")" + " VALUES('" + nameEgress + "',"; // build array of matrix-ints query += TPS_DB_IO.matrixToSQLArray(egressM, 0); query += ")"; this.dbCon.execute(query, this); query = "INSERT INTO " + db + " (\"matrix_name\",\"matrix_values\")" + " VALUES('" + nameAccess + "',"; // build array of matrix-ints query += TPS_DB_IO.matrixToSQLArray(accessM, 0); query += ")"; this.dbCon.execute(query, this); } }
45.677966
158
0.616976
2e1a9bd8436c03042b7f292be5509ff2be73fd25
1,858
/* * Copyright (c) 2014-2018 North Concepts 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.northconcepts.templatemaster.template; import com.northconcepts.templatemaster.content.Content; import com.northconcepts.templatemaster.content.ContentList; import freemarker.template.TemplateHashModel; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; public class ContentTemplateModel implements TemplateHashModel { private final Content block; public ContentTemplateModel(Content block) { this.block = block; } @Override public TemplateModel get(String key) throws TemplateModelException { Content b = block; ContentList blocks = null; while (b != null && (blocks = b.get(key, false)) == null) { b = b.getParent(); } if (blocks == null) { // throw new ContentException(ContentErrorCode.VALUE_NOT_FOUND).set("key", key); return null; } Object object = blocks.render(); // Object object = (blocks == null)?null:blocks.render(); return Templates.get().getConfiguration().getObjectWrapper().wrap(object); } @Override public boolean isEmpty() throws TemplateModelException { return block == null || block.isEmpty(); } }
33.178571
91
0.695371
a0640b7c978badad616b4a90d740145916a4577f
4,266
package com.zhiyi.ukafu.activitys; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.WindowManager; import android.webkit.CookieManager; import android.webkit.WebView; import android.widget.Toast; import com.zhiyi.ukafu.AppConst; import com.zhiyi.ukafu.JsInterface; import com.zhiyi.ukafu.QrcodeUploadActivity; import com.zhiyi.ukafu.R; import com.zhiyi.ukafu.components.ZyWebViewClient; import com.zhiyi.ukafu.util.DBHelper; import com.zhiyi.ukafu.util.DBManager; import com.zhiyi.ukafu.util.LogUtil; import com.zhiyi.ukafu.util.SystemProgramUtils; public class WebViewActivity extends AppCompatActivity { private WebView webView; private static String LOG_TAG = "ZYKJ"; private JsInterface jsInterface; private DBManager dbm; private String Url; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); setContentView(R.layout.activity_web_view); webView = findViewById(R.id.web_view); // webView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE // | View.SYSTEM_UI_FLAG_FULLSCREEN // | View.SYSTEM_UI_FLAG_LAYOUT_STABLE // | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY // | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // webView.setWebViewClient(new ZyWebViewClient()); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setDomStorageEnabled(true); //webView.setWebContentsDebuggingEnabled(true); Intent intent = getIntent(); Url = intent.getStringExtra(AppConst.ACTION_URL); if (Url == null) { Url = "https://www.ukafu.com/default_app_h5.html"; } jsInterface = new JsInterface(webView,this); webView.addJavascriptInterface(jsInterface,"client"); webView.loadUrl(Url); CookieManager ck = CookieManager.getInstance(); ck.setAcceptCookie(true); ck.setAcceptThirdPartyCookies(webView,true); ck.getCookie(Url); dbm = new DBManager(this); String sck = dbm.getCookie(Url); ck.setCookie(Url,sck); } // @Override // protected void onResume() { // super.onResume(); // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (intent == null) { return; } if (requestCode == SystemProgramUtils.REQUEST_CODE_ZHAOPIAN) { Uri uri = intent.getData(); if (uri == null) { Toast.makeText(this, "目标数据为空", Toast.LENGTH_LONG); return; } Cursor cursor = getContentResolver().query(uri, null, null, null, null); if (cursor == null) { Toast.makeText(this, "找不到数据", Toast.LENGTH_LONG); return; } cursor.moveToFirst(); int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); if (idx < 0) { Toast.makeText(this, "无法访问相册", Toast.LENGTH_LONG); return; } String currentPhotoString = cursor.getString(idx); cursor.close(); Intent qIntent = new Intent(WebViewActivity.this, QrcodeUploadActivity.class); qIntent.putExtra("file", currentPhotoString); qIntent.putExtra("forupload",false); startActivityForResult(qIntent, 101); }else if(requestCode == SystemProgramUtils.REQUEST_CODE_PERMISSION){ LogUtil.i("请求权限结果:"+resultCode); }else if(requestCode == 101){ jsInterface.onQrcodeload(intent); } } }
38.432432
120
0.661978
64fd3b31bb69e2b0a5685aa69696537efaaf7503
1,767
package com.interphone.bean; import android.text.TextUtils; import java.text.NumberFormat; import lombok.Data; /** * Created by Administrator on 2016/5/13. */ @Data public class ProtertyData { /** * 30s-180s */ private int totTime; /** * 0-5 * 0:OFF , 1 2 3 4 5 */ private int vox; /** * 活动信道 1-16 */ private int activityChannelId; /** * 机器型号 */ public String deviceMode =""; /** * 设备id */ public String userId =""; /** * 1 2 3(默认) */ public int status = 0x0C; /** * 0:VHF 显示136-174MHz 1:UHF 显示400-470MHz */ private int HFvalue; /** * 序列号 */ private String serialNumber=""; /** * 扫描频率 BCD码,16进制的10位数 比如数字12 0x12 而不是0x0b * "VHF:136-174MHz * 最多到小数点后4位, 也就是固定的 xxx.xxxx , * 必须能被5整除 或 6.25整除 */ private String scanRate; /** * 写频密码 * 353605超级密码 , 全FFFFFF为空密码 */ public String password=""; public String getScanRate() { if (TextUtils.isEmpty(scanRate)) return ""; if (scanRate.equals("00000000")) return ""; double d = Integer.parseInt(scanRate) / 100000.0d; NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(4); return nf.format(d); } public int getActivityChannelId() { if (activityChannelId <1 || activityChannelId > 16) return 1; return activityChannelId; } public void setActivityChannelId(int activityChannelId) { this.activityChannelId = activityChannelId; } public String getHFValueString() { return isVHF() ?"136-174MHZ":"400-470MHZ"; } public boolean isVHF() { return HFvalue==0; } }
18.6
69
0.567629
46c455212ce9706be73133aa3e6dd72b00cfb374
3,449
package ru.yoomoney.tech.dbqueue.settings; import org.junit.Test; import javax.annotation.Nonnull; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiFunction; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; public class DynamicSettingTest { @Test public void should_not_invoke_observer_when_no_changes() { AtomicBoolean observerInvoked = new AtomicBoolean(false); SimpleDynamicSetting oldSetting = new SimpleDynamicSetting("old"); oldSetting.registerObserver((oldVal, newVal) -> { observerInvoked.set(true); }); SimpleDynamicSetting newSetting = new SimpleDynamicSetting("old"); Optional<String> diff = oldSetting.setValue(newSetting); assertThat(diff, equalTo(Optional.empty())); assertThat(observerInvoked.get(), equalTo(false)); assertThat(oldSetting, equalTo(newSetting)); } @Test public void should_invoke_observer_when_setting_changed() { AtomicBoolean observerInvoked = new AtomicBoolean(false); SimpleDynamicSetting oldSetting = new SimpleDynamicSetting("old"); oldSetting.registerObserver((oldVal, newVal) -> { observerInvoked.set(true); }); SimpleDynamicSetting newSetting = new SimpleDynamicSetting("new"); Optional<String> diff = oldSetting.setValue(newSetting); assertThat(diff, equalTo(Optional.of("new<old"))); assertThat(observerInvoked.get(), equalTo(true)); assertThat(oldSetting, equalTo(newSetting)); } @Test public void should_not_update_setting_when_observer_fails() { SimpleDynamicSetting oldSetting = new SimpleDynamicSetting("old"); oldSetting.registerObserver((oldVal, newVal) -> { throw new RuntimeException("exc"); }); SimpleDynamicSetting newSetting = new SimpleDynamicSetting("new"); Optional<String> diff = oldSetting.setValue(newSetting); assertThat(diff, equalTo(Optional.empty())); assertThat(oldSetting, not(equalTo(newSetting))); } private static class SimpleDynamicSetting extends DynamicSetting<SimpleDynamicSetting> { private String text; private SimpleDynamicSetting(String text) { this.text = text; } @Nonnull @Override protected String getName() { return "simple"; } @Nonnull @Override protected BiFunction<SimpleDynamicSetting, SimpleDynamicSetting, String> getDiffEvaluator() { return (oldVal, newVal) -> newVal.text + '<' + oldVal.text; } @Nonnull @Override protected SimpleDynamicSetting getThis() { return this; } @Override protected void copyFields(@Nonnull SimpleDynamicSetting newValue) { this.text = newValue.text; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SimpleDynamicSetting that = (SimpleDynamicSetting) o; return Objects.equals(text, that.text); } @Override public int hashCode() { return Objects.hash(text); } } }
34.148515
101
0.656712
e035029c4b254c6589ea3cb59abdcdec38d9fc06
6,360
package ca.carleton.gcrc.json; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import nunaliit.org.json.JSONArray; import nunaliit.org.json.JSONException; import nunaliit.org.json.JSONObject; import nunaliit.org.json.JSONString; public class JSONSupport { static public boolean containsKey(JSONObject obj, String key){ Iterator<?> it = obj.keys(); while( it.hasNext() ){ Object keyObj = it.next(); if( keyObj instanceof String ) { String k = (String)keyObj; if( k.equals(key) ) return true; } } return false; } static public List<String> keysFromObject(JSONObject obj){ List<String> keys = new Vector<String>(); Iterator<?> it = obj.keys(); while( it.hasNext() ){ Object keyObj = it.next(); if( keyObj instanceof String ) { String k = (String)keyObj; keys.add(k); } } return keys; } static public String valueToString(Object value) throws Exception { if (value == null || value.equals(null)) { return "null"; } if (value instanceof JSONString) { Object object; try { object = ((JSONString)value).toJSONString(); } catch (Exception e) { throw new JSONException(e); } if (object instanceof String) { return (String)object; } throw new JSONException("Bad value from toJSONString: " + object); } if (value instanceof Number) { return numberToString((Number) value); } if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { return value.toString(); } if (value instanceof Map) { return new JSONObject((Map<?,?>)value).toString(); } if (value instanceof Collection) { return new JSONArray((Collection<?>)value).toString(); } if (value.getClass().isArray()) { return new JSONArray(value).toString(); } return JSONObject.quote(value.toString()); } static public String numberToString(Number number) throws Exception { if (number == null) { throw new JSONException("Null pointer"); } testValidity(number); // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; } static public void testValidity(Object o) throws Exception { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } } static public int compare(Object obj1, Object obj2){ if( obj1 == obj2 ) { return 0; } if( obj1 == null ) { return -1; } if( obj2 == null ) { return 1; } if( obj1.getClass() != obj2.getClass() ) { // Not same class, sort by class name return obj1.getClass().getName().compareTo( obj2.getClass().getName() ); } if( obj1 instanceof JSONObject ) { return JSONObjectComparator.singleton.compare((JSONObject)obj1, (JSONObject)obj2); } if( obj1 instanceof JSONArray ) { return JSONArrayComparator.singleton.compare((JSONArray)obj1, (JSONArray)obj2); } if( obj1 instanceof String ) { return ((String)obj1).compareTo((String)obj2); } if( obj1 instanceof Number ) { double d1 = ((Number)obj1).doubleValue(); double d2 = ((Number)obj2).doubleValue(); if( d1 < d2 ) return -1; if( d1 > d2 ) return 1; return 0; } if( obj1 instanceof Boolean ) { return ((Boolean)obj1).compareTo((Boolean)obj2); } return 0; } static public JSONObject copyObject(JSONObject obj){ if( null == obj ) { return null; } JSONObject c = new JSONObject(); Iterator<?> keyIt = obj.keys(); while( keyIt.hasNext() ){ Object keyObj = keyIt.next(); if( keyObj instanceof String ){ String key = (String)keyObj; Object value = obj.get(key); if( null == value ){ c.put(key, value); } else if( value instanceof JSONObject ) { c.put(key, copyObject((JSONObject)value)); } else if( value instanceof JSONArray ) { c.put(key, copyArray((JSONArray)value)); } else { c.put(key, value); } } } return c; } static public JSONArray copyArray(JSONArray arr){ if( null == arr ) { return null; } JSONArray c = new JSONArray(); for(int i=0,e=arr.length(); i<e; ++i){ Object value = arr.get(i); if( null == value ){ c.put(value); } else if( value instanceof JSONObject ) { c.put(copyObject((JSONObject)value)); } else if( value instanceof JSONArray ) { c.put(copyArray((JSONArray)value)); } else { c.put(value); } } return c; } static public JSONObject fromError(Throwable t){ return fromError(t, 8); } static public JSONObject fromError(Throwable t, int limit){ if( limit < 0 ){ return null; } if( null == t ){ return null; } JSONObject errorObj = new JSONObject(); String message = t.getMessage(); if( null == message ){ message = t.getClass().getName(); } errorObj.put("error", message); // Stack trace { StackTraceElement[] stackTrace = t.getStackTrace(); if( null != stackTrace && stackTrace.length > 0 ){ errorObj.put("stack", stackTrace[0].toString()); } } // Cause JSONObject causeObj = fromError(t.getCause(), limit-1); if( null != causeObj ){ errorObj.put("cause", causeObj); } return errorObj; } }
26.065574
85
0.577201
99681482c27aad6e320e59bfb18e145b4affdb15
2,651
package pl.smsapi.test.run; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import pl.smsapi.api.MmsFactory; import pl.smsapi.api.action.mms.MMSDelete; import pl.smsapi.api.action.mms.MMSGet; import pl.smsapi.api.action.mms.MMSSend; import pl.smsapi.api.response.CountableResponse; import pl.smsapi.api.response.MessageResponse; import pl.smsapi.api.response.StatusResponse; import pl.smsapi.exception.SmsapiException; import pl.smsapi.test.TestSmsapi; import java.util.Date; @Ignore public class MmsTest extends TestSmsapi { private String numberTest = "694562829"; private String[] ids; MmsFactory apiFactory; @Before public void setUp() { apiFactory = new MmsFactory(getAuthorizationClient(), getProxy()); } @Test public void mmsSendTest() throws SmsapiException { final long time = (new Date().getTime() / 1000) + 86400; final String smil = "<smil><head><layout><root-layout height='100%' width='100%'/><region id='Image' width='100%' height='100%' left='0' top='0'/></layout></head><body><par><img src='http://www.smsapi.pl/assets/img/pages/errors/404.jpg' region='Image' /></par></body></smil>"; MMSSend action = apiFactory.actionSend() .setSubject("Test") .setSmil(smil) .setTo(numberTest) .setDateSent(time); StatusResponse result = action.execute(); System.out.println("MmsSend:"); if (result.getCount() > 0) { ids = new String[result.getCount()]; } int i = 0; for (MessageResponse item : result.getList()) { if (!item.isError()) { renderMessageItem(item); ids[i] = item.getId(); i++; } } if (ids.length > 0) { writeIds(ids); } } @Test public void mmsGetTest() throws SmsapiException { System.out.println("MmsGet:"); ids = readIds(); if (ids != null) { MMSGet action = apiFactory.actionGet().ids(ids); StatusResponse result = action.execute(); for (MessageResponse item : result.getList()) { renderMessageItem(item); } } } @Test public void mmsDeleteTest() throws SmsapiException { System.out.println("MmsDelete:"); ids = readIds(); if (ids != null) { MMSDelete action = apiFactory.actionDelete().ids(ids); CountableResponse item = action.execute(); System.out.println("Delete: " + item.getCount()); } } }
27.614583
284
0.592607
d1c473b974b4df7e895c6042c7cd07c7ad48b482
163
package emailvalidator4j.parser.exception; public class InvalidEmail extends Exception{ public InvalidEmail(String message) { super(message); } }
20.375
44
0.736196
55c3f9560623777f7cd01222be3b695bd1146338
1,081
package com.repomgr.repomanager.rest.model.common; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; /** * Response Object for common messages and a status, if action was successful (valid = true) or if action failed (valid = false) */ @JsonInclude(JsonInclude.Include.NON_NULL) public class ResponseDto { @JsonProperty(value = "_status") private boolean status; @JsonProperty(value = "_message") private MessageDto message; public ResponseDto() { } public ResponseDto(final boolean status) { this.status = status; } public ResponseDto(final boolean status, final MessageDto messageDto) { this.status = status; this.message = messageDto; } public boolean isStatus() { return status; } public void setStatus(final boolean status) { this.status = status; } public MessageDto getMessage() { return message; } public void setMessage(final MessageDto message) { this.message = message; } }
24.568182
128
0.679926
67758316001219bb1a701ae3a46269c97b8a6828
3,466
/* * 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.flink.runtime.state.ttl; import org.apache.flink.api.common.functions.AggregateFunction; import org.apache.flink.api.common.state.StateTtlConfig; import org.apache.flink.util.FlinkRuntimeException; import org.apache.flink.util.Preconditions; import org.apache.flink.util.function.ThrowingConsumer; import org.apache.flink.util.function.ThrowingRunnable; /** * This class wraps aggregating function with TTL logic. * * @param <IN> The type of the values that are aggregated (input values) * @param <ACC> The type of the accumulator (intermediate aggregate state). * @param <OUT> The type of the aggregated result */ class TtlAggregateFunction<IN, ACC, OUT> extends AbstractTtlDecorator<AggregateFunction<IN, ACC, OUT>> implements AggregateFunction<IN, TtlValue<ACC>, OUT> { ThrowingRunnable<Exception> stateClear; ThrowingConsumer<TtlValue<ACC>, Exception> updater; TtlAggregateFunction( AggregateFunction<IN, ACC, OUT> aggFunction, StateTtlConfig config, TtlTimeProvider timeProvider) { super(aggFunction, config, timeProvider); } @Override public TtlValue<ACC> createAccumulator() { return wrapWithTs(original.createAccumulator()); } @Override public TtlValue<ACC> add(IN value, TtlValue<ACC> accumulator) { ACC userAcc = getUnexpired(accumulator); userAcc = userAcc == null ? original.createAccumulator() : userAcc; return wrapWithTs(original.add(value, userAcc)); } @Override public OUT getResult(TtlValue<ACC> accumulator) { Preconditions.checkNotNull(updater, "State updater should be set in TtlAggregatingState"); Preconditions.checkNotNull( stateClear, "State clearing should be set in TtlAggregatingState"); ACC userAcc; try { userAcc = getWithTtlCheckAndUpdate(() -> accumulator, updater, stateClear); } catch (Exception e) { throw new FlinkRuntimeException( "Failed to retrieve original internal aggregating state", e); } return userAcc == null ? null : original.getResult(userAcc); } @Override public TtlValue<ACC> merge(TtlValue<ACC> a, TtlValue<ACC> b) { ACC userA = getUnexpired(a); ACC userB = getUnexpired(b); if (userA != null && userB != null) { return wrapWithTs(original.merge(userA, userB)); } else if (userA != null) { return rewrapWithNewTs(a); } else if (userB != null) { return rewrapWithNewTs(b); } else { return null; } } }
38.511111
98
0.685805
3995e5ded2916b3ffe82a53f7005779830743cbc
1,130
package fr.firmy.lab.eternity2server.controller.dal; import fr.firmy.lab.eternity2server.controller.exception.RegisteringFailedException; import fr.firmy.lab.eternity2server.controller.exception.UnregisteringFailedException; import fr.firmy.lab.eternity2server.model.Node; import java.util.List; public interface WorkersRegistry { void addPendingJob(Node pending_job, String solver_name, String solver_ip, String solver_version, String solver_machine_type, String solver_cluster_name, Double solver_score) throws RegisteringFailedException; void removePendingJob(Node pending_job, String solver_name) throws UnregisteringFailedException; List<Node> getPendingJobs(String solver_name, String solver_ip, String solver_version, String solver_machine_type, String cluster_name, Double solver_score); }
38.965517
86
0.612389
c672a3142cb78e632b2d3ad226e45bd164c4e117
1,198
package com.devops.thatguy.dao; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.devops.thatguy.model.BillingAddress; @Repository("BillingAddressDAO") public class BillingAddressDAOImpl implements BillingAddressDAO { @Autowired SessionFactory sessionFactory; public BillingAddressDAOImpl(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Transactional public void saveOrUpdate(BillingAddress billingAddress) { sessionFactory.getCurrentSession().saveOrUpdate(billingAddress); } @Transactional public void deleteBillingAddress(String billingAddressId) { BillingAddress billingAddressToDelete = new BillingAddress(); //billingAddressToDelete.setBillingAddressId(billingAddressId); sessionFactory.getCurrentSession().delete(billingAddressToDelete); } @Transactional public BillingAddress getBillingAddress(String billingAddressId) { return sessionFactory.getCurrentSession().get(BillingAddress.class, billingAddressId); } }
29.219512
89
0.807179
b53301341b30a1e0596d3acc4394bd609a4ab548
196
package com.cardillsports.fantasystats.fantasyv.model; /** * Created by vithushan on 1/23/17. */ public interface RequestTokenHandler { void handleRequestToken(String authorizationUrl); }
19.6
54
0.770408
42a7dc9c4e74431d10af535d726d3da2bc885a2b
13,471
/* * Copyright (c) 2014, AXIA Studio (Tiziano Lattisi) - http://www.axiastudio.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the AXIA Studio nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY AXIA STUDIO ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AXIA STUDIO BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.axiastudio.zoefx.persistence; import com.axiastudio.zoefx.core.IOC; import com.axiastudio.zoefx.core.db.AbstractManager; import com.axiastudio.zoefx.core.beans.BeanAccess; import com.axiastudio.zoefx.core.beans.BeanClassAccess; import com.axiastudio.zoefx.core.db.Database; import com.axiastudio.zoefx.core.db.Manager; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.TypedQuery; import javax.persistence.criteria.*; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /** * User: tiziano * Date: 18/03/14 * Time: 20:50 */ public class JPAManagerImpl<E> extends AbstractManager<E> implements Manager<E> { private Class<E> entityClass; private EntityManager entityManager=null; private EntityManagerFactory entityManagerFactory=null; public JPAManagerImpl(EntityManagerFactory emf, Class<E> klass) { this(emf, klass, null); } public JPAManagerImpl(EntityManagerFactory emf, Class<E> klass, EntityManager em) { entityClass = klass; entityManagerFactory = emf; entityManager = em; } @Override public Object getId(E entity) { return entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity); } @Override public E create() { try { return entityClass.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } @Override public Object createRow(String collectionName) { Database db = IOC.queryUtility(Database.class); BeanClassAccess beanClassAccess = new BeanClassAccess(entityClass, collectionName); Class<?> genericReturnType = beanClassAccess.getGenericReturnType(); Manager<?> manager = db.createManager(genericReturnType); return manager.create(); } @Override public E save(E entity) { parentize(entity); EntityManager em = createEntityManager(); em.getTransaction().begin(); E merged = em.merge(entity); em.getTransaction().commit(); em.refresh(merged); finalizeEntityManager(em); return merged; } @Override public void save(List<E> entities) { EntityManager em = createEntityManager(); em.getTransaction().begin(); for( E entity: entities ){ em.merge(entity); } em.getTransaction().commit(); finalizeEntityManager(em); } @Override public void delete(E entity) { EntityManager em = createEntityManager(); em.getTransaction().begin(); E merged = em.merge(entity); em.remove(merged); em.getTransaction().commit(); finalizeEntityManager(em); } @Override public void deleteRow(Object row) { EntityManager em = createEntityManager(); Object merged = em.merge(row); em.remove(merged); finalizeEntityManager(em); } @Override public void truncate(){ EntityManager em = createEntityManager(); em.getTransaction().begin(); em.createQuery("DELETE FROM " + entityClass.getCanonicalName() + " e").executeUpdate(); em.getTransaction().commit(); } @Override public E get(Long id) { EntityManager em = createEntityManager(); E entity = em.find(entityClass, id); finalizeEntityManager(em); return entity; } @Override public List<E> query() { EntityManager em = createEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<E> cq = cb.createQuery(entityClass); Root<E> root = cq.from(entityClass); cq.select(root); TypedQuery<E> query = em.createQuery(cq); List<E> store = query.getResultList(); finalizeEntityManager(em); return store; } @Override public List<E> query(Map<String, Object> map, List<String> orderbys, List<Boolean> reverses, Integer size, Integer startindex) { EntityManager em = createEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<E> cq = cb.createQuery(entityClass); Root<E> root = cq.from(entityClass); List<Predicate> predicates = new ArrayList<>(); for( String name: map.keySet() ){ Predicate predicate=null; Path path = null; path = root.get(name.split("#")[0]); Object objectValue = map.get(name); if( objectValue instanceof String ){ String value = (String) objectValue; value = value.replace("*", "%"); if( !value.endsWith("%") ){ value += "%"; } predicate = cb.like(cb.upper(path), value.toUpperCase()); } else if( objectValue instanceof Boolean ){ predicate = cb.equal(path, objectValue); } else if( objectValue instanceof List ){ /* List<Date> range = (List<Date>) objectValue; Date from = zeroMilliseconds(range.get(0)); Date to = lastMillisecond(range.get(1)); predicate = cb.and(cb.greaterThanOrEqualTo(path, from), cb.lessThanOrEqualTo(path, to)); */ List<Object> range = (List<Object>) objectValue; if( range.get(0) instanceof Operator){ Operator op = (Operator) range.get(0); Object value = range.get(1); if( Operator.eq.equals(op) ){ predicate = cb.equal(path, value); } else if( value instanceof Comparable ) { if( value instanceof Date ){ if( Operator.lt.equals(op) || Operator.le.equals(op) ){ value = lastMillisecond((Date) range.get(1)); } else if ( Operator.gt.equals(op) || Operator.ge.equals(op) ){ value = zeroMilliseconds((Date) range.get(1)); } } if (Operator.lt.equals(op)) { predicate = cb.lessThan(path, (Comparable) value); } else if (Operator.le.equals(op)) { predicate = cb.lessThanOrEqualTo(path, (Comparable) value); } else if (Operator.gt.equals(op)) { predicate = cb.greaterThan(path, (Comparable) value); } else if (Operator.ge.equals(op)) { predicate = cb.greaterThanOrEqualTo(path, (Comparable) value); } } } } else if( objectValue instanceof Object ){ if( objectValue.getClass().isEnum() ) { int value = ((Enum) objectValue).ordinal(); // XXX: and if EnumType.STRING?? predicate = cb.equal(path, value); } else { predicate = cb.equal(path, objectValue); } } if( predicate != null ){ predicates.add(predicate); } } cq.select(root); if( predicates.size()>0 ){ cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()]))); } // order by if( orderbys.size()>0 ) { List<Order> orders = new ArrayList<>(); for (int i = 0; i < orderbys.size(); i++) { String orderby = orderbys.get(i); Boolean reverse = reverses.get(i); if (reverse) { orders.add(cb.desc(root.get(orderby))); } else { orders.add(cb.asc(root.get(orderby))); } } cq.orderBy(orders); } TypedQuery<E> query = em.createQuery(cq); // startIndex if( startindex != null ){ query = query.setFirstResult(startindex); } // limit if( size != null ){ query = query.setMaxResults(size.intValue()); } List<E> store = query.getResultList(); finalizeEntityManager(em); return store; } private Date zeroMilliseconds(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } private Date lastMillisecond(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); calendar.set(Calendar.MILLISECOND, 999); return calendar.getTime(); } protected EntityManager createEntityManager() { if( entityManager!=null ){ return entityManager; } return entityManagerFactory.createEntityManager(); } private void finalizeEntityManager(EntityManager em) { if( em != entityManager ) { em.close(); } else { System.out.println("***"); } } public EntityManagerFactory getEntityManagerFactory() { return entityManagerFactory; } public EntityManager getEntityManager() { return entityManager; } public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } /* * The parentize method hooks the items of the collections to the parent * entity. */ private void parentize(E entity){ for(Field f: entityClass.getDeclaredFields()){ for( Annotation a: f.getAnnotations()){ // discover the OneToMany if( a.annotationType().equals(javax.persistence.OneToMany.class) ) { String name = f.getName(); BeanAccess<Collection> collectionBeanAccess = new BeanAccess<Collection>(entity, name); Collection collection = collectionBeanAccess.getValue(); if( collection != null && collection.size()>0 ){ // discover the "mapped by" foreign key String foreignKey=null; try { Method mappedBy = a.annotationType().getDeclaredMethod("mappedBy"); foreignKey = (String) mappedBy.invoke(a); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } if( foreignKey != null ) { // parentize children for (Iterator it = collection.iterator(); it.hasNext(); ) { Object child = it.next(); BeanAccess<E> fkBeanAccess = new BeanAccess<>(child, foreignKey); fkBeanAccess.setValue(entity); } } } } } } } }
37.839888
132
0.572489
7fb8864d81ba2a504a0403c9f5b6a3f78c86e4d1
5,348
package com.assistant.albert.studentassistant.schedule; import android.graphics.Typeface; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.assistant.albert.studentassistant.R; import com.assistant.albert.studentassistant.authentification.SessionManager; import com.assistant.albert.studentassistant.utils.Utils; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class ScheduleRecyclerAdapter extends RecyclerView.Adapter<ScheduleRecyclerAdapter.ViewHolder> { private ScheduleItem dataSet; private View scheduleCardView; public ScheduleRecyclerAdapter(ScheduleItem dataSet) { this.dataSet = dataSet; } @Override public ScheduleRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { scheduleCardView = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_schedule, parent, false); return new ViewHolder(scheduleCardView); } @Override public void onBindViewHolder(ScheduleRecyclerAdapter.ViewHolder holder, int position) { if (holder.scheduleOfDay.getChildCount() == 0) { holder.weekDay.setText(ScheduleDays.list.get(position).toString()); ArrayList daySchedule = dataSet.Schedule().get(position); ArrayList<CardView> subjects = new ArrayList<>(); SessionManager sessionManager = new SessionManager(scheduleCardView.getContext()); Integer currentWeek = 0; try { currentWeek = Utils.getInstantInfoItemFromJson(new JSONObject(sessionManager.getInstantInfo())).CurrentWeek(); } catch (JSONException e) { e.printStackTrace(); } for (int i = 0; i < daySchedule.size(); i++) { ArrayList<String> classSchedule = (ArrayList<String>) daySchedule.get(i); CardView subjectCardView = (CardView) LayoutInflater.from(holder.scheduleOfDay.getContext()). inflate(R.layout.content_schedule_subject, holder.scheduleOfDay, false); TextView subjectNumber = subjectCardView.findViewById(R.id.subjectNumber); TextView numeratorSubject = subjectCardView.findViewById(R.id.numeratorSubject); TextView denominatorSubject = subjectCardView.findViewById(R.id.denomenatorSubject); TextView subjectDivider = subjectCardView.findViewById(R.id.subjectDivider); if (currentWeek % 2 != 0) { numeratorSubject.setTypeface(null, Typeface.BOLD); } else { denominatorSubject.setTypeface(null, Typeface.BOLD); } if (dataSet.CurrentDay() == position) subjectCardView.setBackgroundColor(subjectCardView.getResources().getColor(R.color.currentDay)); String subjectIndex = Integer.toString(i + 1) + ". "; String numeratorString = classSchedule.get(0); String denominatorString = classSchedule.get(1); subjectNumber.setText(subjectIndex); if ((!numeratorString.equals(denominatorString)) && (!numeratorString.isEmpty() && !denominatorString.isEmpty())) { numeratorSubject.setText(numeratorString); denominatorSubject.setText(denominatorString); subjectDivider.setText("|"); } else if (numeratorString.isEmpty() && !denominatorString.isEmpty()) { numeratorSubject.setText("-"); subjectDivider.setText("|"); denominatorSubject.setText(denominatorString); } else if (!numeratorString.isEmpty() && denominatorString.isEmpty()) { numeratorSubject.setText(numeratorString); denominatorSubject.setText("-"); subjectDivider.setText("|"); } else if ((numeratorString.equals(denominatorString)) && (!numeratorString.isEmpty())) { numeratorSubject.setText(numeratorString); if (currentWeek % 2 == 0) { numeratorSubject.setTypeface(null, Typeface.BOLD); } } subjects.add(subjectCardView); } for (int i = 0; i < subjects.size(); i++) { holder.scheduleOfDay.addView(subjects.get(i)); } } } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); } @Override public int getItemCount() { return dataSet.Schedule().size(); } public static class ViewHolder extends RecyclerView.ViewHolder { LinearLayout scheduleOfDay; TextView weekDay; public ViewHolder(View scheduleView) { super(scheduleView); weekDay = scheduleView.findViewById(R.id.weekDay); scheduleOfDay = scheduleView.findViewById(R.id.scheduleOfDay); } } }
39.614815
131
0.6408
4f8619219d707aeffdbf8da9cf4232d76b99f6ef
234
package com.world.cup.sticker.brick.worldcupstickerbrick.business.service.impl; import com.world.cup.sticker.brick.worldcupstickerbrick.business.service.StickerService; public class StickerServiceImpl implements StickerService { }
29.25
88
0.854701
e07f203fa8dad9fe0ada8d0a02c7166764986dc5
376
/* * Brandon Russeau * COSC 423 */ package scheduler; public class Work implements JobWorkable { String name = ""; public Work() { name = Thread.currentThread().getName(); } @Override public void doWork() { // TODO Auto-generated method stub // reference to current thread = Thread.currentThread(); System.out.println(name + " is currently running"); } }
17.090909
58
0.678191
6cbd15937203b236b1eddfab965538cd130f1894
17,561
/** * Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.diirt.datasource.sample; import org.diirt.datasource.PVReader; import org.diirt.datasource.PVReaderEvent; import org.diirt.datasource.ChannelHandler; import org.diirt.datasource.PVReaderListener; import org.diirt.datasource.PVManager; import org.diirt.vtype.AlarmSeverity; import org.diirt.vtype.ValueFormat; import org.diirt.vtype.ValueUtil; import org.diirt.vtype.SimpleValueFormat; import org.diirt.vtype.Alarm; import org.diirt.vtype.Time; import org.diirt.vtype.Display; import java.awt.Color; import java.util.EnumMap; import java.util.Map; import javax.swing.JOptionPane; import javax.swing.border.Border; import javax.swing.border.LineBorder; import static org.diirt.datasource.formula.ExpressionLanguage.*; import static org.diirt.util.time.TimeDuration.*; import org.diirt.util.time.TimeDuration; /** * * @author carcassi */ public class SimpleProbe extends javax.swing.JFrame { Map<AlarmSeverity, Border> borders = new EnumMap<AlarmSeverity, Border>(AlarmSeverity.class); /** * Creates new form MockPVFrame */ public SimpleProbe() { initComponents(); borders.put(AlarmSeverity.NONE, pvTextValue.getBorder()); borders.put(AlarmSeverity.MINOR, new LineBorder(Color.YELLOW)); borders.put(AlarmSeverity.MAJOR, new LineBorder(Color.RED)); borders.put(AlarmSeverity.INVALID, new LineBorder(Color.GRAY)); borders.put(AlarmSeverity.UNDEFINED, new LineBorder(Color.MAGENTA)); } ValueFormat format = new SimpleValueFormat(3); /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); pvName = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jLabel5 = new javax.swing.JLabel(); pvTextValue = new javax.swing.JTextField(); pvType = new javax.swing.JTextField(); lastError = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); pvTime = new javax.swing.JTextField(); indicator = new javax.swing.JSlider(); jLabel6 = new javax.swing.JLabel(); metadata = new javax.swing.JTextField(); channelDetailsButton = new javax.swing.JButton(); connected = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); writeConnected = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Value:"); jLabel2.setText("PV name:"); pvName.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pvNameActionPerformed(evt); } }); jLabel3.setText("Last error:"); jLabel5.setText("Type:"); pvTextValue.setEditable(false); pvType.setEditable(false); lastError.setEditable(false); jLabel4.setText("Timestamp:"); pvTime.setEditable(false); indicator.setEnabled(false); jLabel6.setText("Metadata:"); metadata.setEditable(false); channelDetailsButton.setText("Channel details..."); channelDetailsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { channelDetailsButtonActionPerformed(evt); } }); connected.setEditable(false); jLabel7.setText("Connected:"); jLabel8.setText("Write Connected:"); writeConnected.setEditable(false); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(pvName, javax.swing.GroupLayout.DEFAULT_SIZE, 319, Short.MAX_VALUE)) .addComponent(indicator, javax.swing.GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(pvTextValue, javax.swing.GroupLayout.DEFAULT_SIZE, 338, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(pvTime, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(pvType, javax.swing.GroupLayout.DEFAULT_SIZE, 342, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lastError, javax.swing.GroupLayout.DEFAULT_SIZE, 314, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(metadata)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(connected)) .addGroup(layout.createSequentialGroup() .addComponent(channelDetailsButton) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(writeConnected))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(pvName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(indicator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(pvTextValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(pvTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(pvType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lastError, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(metadata, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(connected, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(writeConnected, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(channelDetailsButton) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void pvNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pvNameActionPerformed long startTime = System.currentTimeMillis(); if (pv != null) { pv.close(); lastError.setText(""); } long total = System.currentTimeMillis() - startTime; if (total > 1) { System.out.println("Disconnect took " + total + " ms"); } try { startTime = System.currentTimeMillis(); pv = PVManager.read(formula(pvName.getText())) .timeout(TimeDuration.ofSeconds(5)) .readListener(new PVReaderListener<Object>() { @Override public void pvChanged(PVReaderEvent<Object> event) { setLastError(pv.lastException()); Object value = pv.getValue(); setTextValue(format.format(value)); setType(ValueUtil.typeOf(value)); setAlarm(ValueUtil.alarmOf(value)); setTime(ValueUtil.timeOf(value)); setIndicator(ValueUtil.normalizedNumericValueOf(value)); setMetadata(ValueUtil.displayOf(value)); setConnected(pv.isConnected()); } }) .maxRate(ofHertz(10)); total = System.currentTimeMillis() - startTime; if (total > 1) { System.out.println("Reconnect took " + total + " ms"); } } catch(Throwable t) { System.out.println("EXCEPTION WHILE CREATING PV!!! SHOULD NEVER HAPPEN!!!"); t.printStackTrace(); } }//GEN-LAST:event_pvNameActionPerformed private void channelDetailsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_channelDetailsButtonActionPerformed try { ChannelHandler handler = PVManager.getDefaultDataSource().getChannels().get(pvName.getText()); if (handler != null) { Map<String, Object> properties = handler.getProperties(); StringBuilder builder = new StringBuilder(); builder.append("Channel properties:\n"); for (Map.Entry<String, Object> entry : properties.entrySet()) { String string = entry.getKey(); Object object = entry.getValue(); builder.append(string).append(" = ").append(object).append("\n"); } JOptionPane.showMessageDialog(this, builder.toString()); } } catch (RuntimeException e) { e.printStackTrace(); } }//GEN-LAST:event_channelDetailsButtonActionPerformed PVReader<?> pv; private void setTextValue(String value) { if (value == null) { pvTextValue.setText(""); } else { pvTextValue.setText(value); } } private void setType(Class type) { if (type == null) { pvType.setText(""); } else { pvType.setText(type.getSimpleName()); } } private void setAlarm(Alarm alarm) { if (alarm != null) { pvTextValue.setBorder(borders.get(alarm.getAlarmSeverity())); } else { pvTextValue.setBorder(borders.get(AlarmSeverity.NONE)); } } private void setTime(Time time) { if (time == null) { pvTime.setText(""); } else { pvTime.setText(time.getTimestamp().toDate().toString()); } } private void setMetadata(Display display) { if (display == null) { metadata.setText(""); } else { metadata.setText(display.getUpperDisplayLimit() + " - " + display.getLowerDisplayLimit()); } } private void setLastError(Exception ex) { if (ex != null) { ex.printStackTrace(); lastError.setText(ex.getClass().getSimpleName() + " " + ex.getMessage()); } else { } } private void setConnected(Boolean connected) { if (connected != null) { this.connected.setText(connected.toString()); } else { this.connected.setText(""); } } private void setWriteConnected(Boolean connected) { if (connected != null) { this.writeConnected.setText(connected.toString()); } else { this.writeConnected.setText(""); } } private void setIndicator(Double value) { int range = indicator.getMaximum() - indicator.getMinimum(); int position = range / 2; if (value != null) { position = (int) (range * value); } indicator.setValue(position); } /** * @param args the command line arguments */ public static void main(String args[]) { SetupUtil.defaultCASetupForSwing(); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new SimpleProbe().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton channelDetailsButton; private javax.swing.JTextField connected; private javax.swing.JSlider indicator; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JSeparator jSeparator1; private javax.swing.JTextField lastError; private javax.swing.JTextField metadata; private javax.swing.JTextField pvName; private javax.swing.JTextField pvTextValue; private javax.swing.JTextField pvTime; private javax.swing.JTextField pvType; private javax.swing.JTextField writeConnected; // End of variables declaration//GEN-END:variables }
45.377261
168
0.628837
d3e50d871905c92ffd8612750865dd376ff183ef
1,112
//Class for register/login class Registration_Login { //Variables to store different stuff private String username; private String password; private String Name; private String number; //Constructor to initialise variables that are private Registration_Login(String name, String username, String password, String number) { setName(name); setUsername(username); setPassword(password); setNumber(number); } //Getters and setters as they are private public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getNumber() { return this.number; } public void setNumber(String number) { this.number = number; } public String getName() { return Name; } public void setName(String name) { this.Name = name; } }
22.693878
86
0.635791
1475af5d1201f5fbb34071e74a641fab04c0d3ea
280
package stepDefinition; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(features = { "src/logout" }, glue = { "stepDefinition" }) public class TestRunner { }
17.5
75
0.717857
1e453b00362cd1882dffd4f23c33ffa05189d472
4,919
package org.intermine.web.struts; /* * Copyright (C) 2002-2022 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.InterMineBag; import org.intermine.api.profile.Profile; import org.intermine.api.tracker.util.ListBuildMode; import org.intermine.metadata.StringUtil; import org.intermine.web.logic.session.SessionMethods; /** * Action class for saving a bag from the bagUploadConfirm page into the user profile. * @author Kim Rutherford */ public class BagUploadConfirmAction extends InterMineAction { /** * Action to save a bag from the bagUploadConfirm page into the user profile. * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws * an exception */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (request.getParameter("goBack") != null) { return mapping.findForward("back"); } HttpSession session = request.getSession(); Profile profile = SessionMethods.getProfile(session); InterMineAPI im = SessionMethods.getInterMineAPI(session); BagUploadConfirmForm confirmForm = (BagUploadConfirmForm) form; String bagName = (!"".equals(confirmForm.getNewBagName())) ? confirmForm.getNewBagName() : request.getParameter("upgradeBagName"); if (StringUtils.isBlank(bagName)) { recordError(new ActionMessage("bagUploadConfirm.noName"), request); return mapping.findForward("error"); } String idsString = confirmForm.getMatchIDs().trim(); String[] ids = StringUtil.split(idsString, " "); List<Integer> contents = new ArrayList<Integer>(); String bagType = confirmForm.getBagType(); for (int i = 0; i < ids.length; i++) { String idString = ids[i]; if (idString.length() == 0) { continue; } int id = Integer.parseInt(idString); contents.add(new Integer(id)); } for (int i = 0; i < confirmForm.getSelectedObjects().length; i++) { String idString = confirmForm.getSelectedObjects()[i]; int id = Integer.parseInt(idString); contents.add(new Integer(id)); } if (contents.size() == 0) { recordError(new ActionMessage("bagUploadConfirm.emptyBag"), request); return mapping.findForward("error"); } // if upgradeBagName is null we are creating a new bag, // otherwise we are upgrading an existing bag if (request.getParameter("upgradeBagName") == null) { InterMineBag bag = profile.createBag(bagName, bagType, "", im.getClassKeys()); bag.addIdsToBag(contents, bagType); //track the list creation im.getTrackerDelegate().trackListCreation(bagType, bag.getSize(), ListBuildMode.IDENTIFIERS, profile, session.getId()); session.removeAttribute("bagQueryResult"); } else { InterMineBag bagToUpgrade = profile.getSavedBags().get(bagName); if (bagToUpgrade == null) { recordError(new ActionMessage("bagUploadConfirm.notFound"), request); return mapping.findForward("error"); } bagToUpgrade.upgradeOsb(contents, true); session.removeAttribute("bagQueryResult_" + bagName); } confirmForm.reset(mapping, request); ForwardParameters forwardParameters = new ForwardParameters( mapping.findForward("bagDetails")); forwardParameters.addParameter("bagName", bagName); forwardParameters.addParameter("trackExecution", "false"); return forwardParameters.forward(); } }
40.991667
100
0.66294
6e6d97cf2da6c565bd6ec25ee0e1f66c7ee516f3
3,044
/** * Sachin Shah * version 1 */ import java.awt.Color; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.File; import java.util.Scanner; import java.util.ArrayList; import javax.imageio.ImageIO; public class Condenser { private String folderName = ""; public static void main(String[] args) { Condenser n = new Condenser(); n.run(); } public void run() { System.out.println("Welcome to the Condenser"); Reader reader = new Reader(); Scanner input = new Scanner(System.in); System.out.println("What folder should be condensed?"); folderName = input.nextLine().trim(); reader.changeFolder(folderName); ArrayList<BufferedImage> listImg = reader.loadBufferedImages(); ArrayList<String> names = reader.fileNames(); System.out.println("Finished Importing Data"); uniqueCount(listImg, names, reader); System.out.println("Done"); } public boolean unique(int r, int g, int b, ArrayList<Integer[]> list) { for (Integer[] i : list) { if (i[0] == r && i[1] == g && i[2] == b) return false; } list.add(array(r, g, b)); return true; } public void uniqueCount(ArrayList<BufferedImage> listImg, ArrayList<String> names, Reader r) { int uniqueCount = 0; int place = 0; ArrayList<Integer[]> pixels = new ArrayList<Integer[]>(); for (BufferedImage s : listImg) { int[][] t = r.imgToArray(s); System.out.println("ON TO: " + names.get(place)); for (int i = 0; i < t[0].length; i++){ if (unique(t[0][i], t[1][i], t[2][i], pixels)) uniqueCount++; } place++; } System.out.printf("Unique Total: %d%n", uniqueCount); System.out.printf("Image Total: %d%n", listImg.size()); create(pixels, "condensed" + folderName); } public BufferedImage create(ArrayList<Integer[]> list, String name) { if (list.size() == 0) return null; int start_val = (int) Math.ceil(Math.sqrt(list.size())); int current_val = start_val; int size = list.size(); int width = start_val; int height = start_val; int[] nums = new int[3]; int place = 0; while (current_val > 20) { if (size % current_val == 0) { width = current_val; height = size / current_val; break; } else { current_val--; } } System.out.printf("Dimensions: %dx%d", width, height); BufferedImage output = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Color temp = (place < size) ? new Color( list.get(place)[0], list.get(place)[1], list.get(place)[2], 1) : new Color(0, 0, 0, 1); output.setRGB(j, i, temp.getRGB()); place++; } } save(output, name); return output; } public void save(BufferedImage pic, String name) { try { ImageIO.write(pic, "png", new File(name + ".png")); } catch(IOException e) { System.out.println("Unable to save image"); } } private Integer[] array(int r, int g, int b) { return new Integer[] {r, g, b}; } }
19.895425
93
0.621879
1b9bab3c74e108c18a0a3415c3b496cd5c5fc557
2,900
/* Copyright (C) 2004 - 2011 Versant Inc. http://www.db4o.com */ package com.db4o.internal.query.processor; import com.db4o.foundation.*; import com.db4o.internal.*; import com.db4o.internal.classindex.*; import com.db4o.internal.fieldindex.*; /** * @exclude */ public class QueryResultCandidates { private QCandidateBase _candidates; private QCandidates _qCandidates; IntVisitable _candidateIds; public QueryResultCandidates(QCandidates qCandidates){ _qCandidates = qCandidates; } public void add(InternalCandidate candidate) { toQCandidates(); _candidates = Tree.add(_candidates, (QCandidateBase)candidate); } private void toQCandidates() { if(_candidateIds == null){ return; } _candidateIds.traverse(new IntVisitor() { public void visit(int id) { _candidates = Tree.add(_candidates, new QCandidate(_qCandidates, null, id)); } }); _candidateIds = null; } public void fieldIndexProcessorResult(FieldIndexProcessorResult result) { _candidateIds = result; } public void singleCandidate(QCandidateBase candidate) { _candidates = candidate; _candidateIds = null; } boolean filter(Visitor4 visitor) { toQCandidates(); if (_candidates != null) { _candidates.traverse(visitor); _candidates = (QCandidateBase) _candidates.filter(new Predicate4() { public boolean match(Object a_candidate) { return ((QCandidateBase) a_candidate)._include; } }); } return _candidates != null; } boolean filter(final QField field, final FieldFilterable filterable) { toQCandidates(); if (_candidates != null) { _candidates.traverse(new Visitor4() { @Override public void visit(Object candidate) { filterable.filter(field, (ParentCandidate)candidate); } }); _candidates = (QCandidateBase) _candidates.filter(new Predicate4() { public boolean match(Object a_candidate) { return ((QCandidateBase) a_candidate)._include; } }); } return _candidates != null; } public void loadFromClassIndex(ClassIndexStrategy index) { _candidateIds = index.idVisitable(_qCandidates.transaction()); } void traverse(Visitor4 visitor) { toQCandidates(); if(_candidates != null){ _candidates.traverse(visitor); } } public void traverseIds(final IntVisitor visitor) { if(_candidateIds != null){ _candidateIds.traverse(visitor); return; } traverse(new Visitor4() { public void visit(Object obj) { QCandidateBase candidate = (QCandidateBase) obj; if(candidate.include()){ visitor.visit(candidate._key); } } }); } }
25.892857
81
0.631034
352e9c21b48677fceac7251404864d19379d9d41
1,878
package de.aaaaaaah.velcom.backend.restapi.jsonobjects; import de.aaaaaaah.velcom.backend.data.commitcomparison.CommitComparison; import de.aaaaaaah.velcom.backend.access.entities.Commit; import java.util.Collection; import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.Nullable; /** * A helper class for serialization representing a comparison between two commits. */ public class JsonCommitComparison { @Nullable private final JsonCommit firstCommit; @Nullable private final JsonRun firstRun; private final JsonCommit secondCommit; @Nullable private final JsonRun secondRun; private final Collection<JsonDifference> differences; public JsonCommitComparison(CommitComparison commitComparison) { final Optional<Commit> maybeFirstCommit = commitComparison.getFirstCommit(); if (maybeFirstCommit.isPresent()) { firstCommit = new JsonCommit(maybeFirstCommit.get()); firstRun = commitComparison.getFirstRun() .map(run -> new JsonRun(run, maybeFirstCommit.get())) .orElse(null); } else { firstCommit = null; // There can't be a run without a commit, so the run would be null anyways firstRun = null; } secondCommit = new JsonCommit(commitComparison.getSecondCommit()); secondRun = commitComparison.getSecondRun() .map(run -> new JsonRun(run, commitComparison.getSecondCommit())) .orElse(null); differences = commitComparison.getDifferences().stream() .map(JsonDifference::new) .collect(Collectors.toUnmodifiableList()); } @Nullable public JsonCommit getFirstCommit() { return firstCommit; } @Nullable public JsonRun getFirstRun() { return firstRun; } public JsonCommit getSecondCommit() { return secondCommit; } @Nullable public JsonRun getSecondRun() { return secondRun; } public Collection<JsonDifference> getDifferences() { return differences; } }
25.726027
82
0.764111
f81d37237b4aef41f265f027f38e2560c0857cf2
1,231
package com.vzh.leetcode; import java.util.ArrayList; /* * Problem: https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/ * Submission: https://leetcode.com/submissions/detail/572630347/ */ public class P2038 { class Solution { public boolean winnerOfGame(String colors) { var ofA = get(colors, 'A'); var ofB = get(colors, 'B'); return ofA > ofB; } private int get(String colors, char ch) { var ans = new ArrayList<int[]>(); var start = -1; for (var i = 0; i < colors.length(); i++) { if (colors.charAt(i) == ch) { if (start == -1) { start = i; continue; } } if (colors.charAt(i) != ch) { if (start != -1) { ans.add(new int[]{start, i - 1}); start = -1; } } } if (colors.charAt(colors.length() - 1) == ch) { ans.add(new int[]{start, colors.length() - 1}); } var count = 0; for (var pair : ans) { if (pair[1] - pair[0] > 1) { count += pair[1] - pair[0] - 1; } } return count; } } }
23.673077
102
0.470349
c9bae162fd96542dc72ab55dec4de189860359c2
8,307
package com.google.widget.view; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.content.res.Configuration; import android.support.design.widget.FloatingActionButton; import android.view.View; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.FrameLayout; import android.widget.ImageButton; import com.google.widget.R; import java.util.ArrayList; /** * ============================================================ * Copyright:Google有限公司版权所有 (c) 2017 * Author: 陈冠杰 * Email: [email protected] * GitHub: https://github.com/JackChen1999 * 博客: http://blog.csdn.net/axi295309066 * 微博: AndroidDeveloper * <p> * Project_Name:Widgets * Package_Name:com.google.widget * Version:1.0 * time:2016/2/15 14:09 * des : * gitVersion:$Rev$ * updateAuthor:$Author$ * updateDate:$Date$ * updateDes:${TODO} * ============================================================ **/ public class PromotedActions { Context context; FrameLayout frameLayout; FloatingActionButton mainActionButton; RotateAnimation rotateOpenAnimation; RotateAnimation rotateCloseAnimation; ArrayList<FloatingActionButton> promotedActions; ObjectAnimator objectAnimator[]; private int px; private static final int ANIMATION_TIME = 200; private boolean isMenuOpened; public void setup(Context activityContext, FrameLayout layout) { context = activityContext; promotedActions = new ArrayList<>(); frameLayout = layout; px = (int) context.getResources().getDimension(R.dimen.dim45dp) + 10; openRotation(); closeRotation(); } public FloatingActionButton addMainItem(FloatingActionButton button) { button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (isMenuOpened) { closePromotedActions().start(); isMenuOpened = false; } else { isMenuOpened = true; openPromotedActions().start(); } } }); frameLayout.addView(button); mainActionButton = button; return button; } public void addItem(FloatingActionButton button, View.OnClickListener onClickListener) { button.setOnClickListener(onClickListener); promotedActions.add(button); frameLayout.addView(button); } /** * Set close animation for promoted actions */ public AnimatorSet closePromotedActions() { if (objectAnimator == null){ objectAnimatorSetup(); } AnimatorSet animation = new AnimatorSet(); for (int i = 0; i < promotedActions.size(); i++) { objectAnimator[i] = setCloseAnimation(promotedActions.get(i), i); } if (objectAnimator.length == 0) { objectAnimator = null; } animation.playTogether(objectAnimator); animation.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { mainActionButton.startAnimation(rotateCloseAnimation); mainActionButton.setClickable(false); } @Override public void onAnimationEnd(Animator animator) { mainActionButton.setClickable(true); hidePromotedActions(); } @Override public void onAnimationCancel(Animator animator) { mainActionButton.setClickable(true); } @Override public void onAnimationRepeat(Animator animator) {} }); return animation; } public AnimatorSet openPromotedActions() { if (objectAnimator == null){ objectAnimatorSetup(); } AnimatorSet animation = new AnimatorSet(); for (int i = 0; i < promotedActions.size(); i++) { objectAnimator[i] = setOpenAnimation(promotedActions.get(i), i); } if (objectAnimator.length == 0) { objectAnimator = null; } animation.playTogether(objectAnimator); animation.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { mainActionButton.startAnimation(rotateOpenAnimation); mainActionButton.setClickable(false); showPromotedActions(); } @Override public void onAnimationEnd(Animator animator) { mainActionButton.setClickable(true); } @Override public void onAnimationCancel(Animator animator) { mainActionButton.setClickable(true); } @Override public void onAnimationRepeat(Animator animator) {} }); return animation; } private void objectAnimatorSetup() { objectAnimator = new ObjectAnimator[promotedActions.size()]; } /** * Set close animation for single button * * @param promotedAction * @param position * @return objectAnimator */ private ObjectAnimator setCloseAnimation(ImageButton promotedAction, int position) { ObjectAnimator objectAnimator; if(context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { objectAnimator = ObjectAnimator.ofFloat(promotedAction, View.TRANSLATION_Y, -px * (promotedActions.size() - position), 0f); objectAnimator.setRepeatCount(0); objectAnimator.setDuration(ANIMATION_TIME * (promotedActions.size() - position)); } else { objectAnimator = ObjectAnimator.ofFloat(promotedAction, View.TRANSLATION_X, -px * (promotedActions.size() - position), 0f); objectAnimator.setRepeatCount(0); objectAnimator.setDuration(ANIMATION_TIME * (promotedActions.size() - position)); } return objectAnimator; } /** * Set open animation for single button * * @param promotedAction * @param position * @return objectAnimator */ private ObjectAnimator setOpenAnimation(ImageButton promotedAction, int position) { ObjectAnimator objectAnimator; if(context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { objectAnimator = ObjectAnimator.ofFloat(promotedAction, View.TRANSLATION_Y, 0f, -px * (promotedActions.size() - position)); objectAnimator.setRepeatCount(0); objectAnimator.setDuration(ANIMATION_TIME * (promotedActions.size() - position)); } else { objectAnimator = ObjectAnimator.ofFloat(promotedAction, View.TRANSLATION_X, 0f, -px * (promotedActions.size() - position)); objectAnimator.setRepeatCount(0); objectAnimator.setDuration(ANIMATION_TIME * (promotedActions.size() - position)); } return objectAnimator; } private void hidePromotedActions() { for (int i = 0; i < promotedActions.size(); i++) { promotedActions.get(i).setVisibility(View.GONE); } } private void showPromotedActions() { for (int i = 0; i < promotedActions.size(); i++) { promotedActions.get(i).setVisibility(View.VISIBLE); } } private void openRotation() { rotateOpenAnimation = new RotateAnimation(0, 45, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); rotateOpenAnimation.setFillAfter(true); rotateOpenAnimation.setFillEnabled(true); rotateOpenAnimation.setDuration(ANIMATION_TIME); } private void closeRotation() { rotateCloseAnimation = new RotateAnimation(45, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); rotateCloseAnimation.setFillAfter(true); rotateCloseAnimation.setFillEnabled(true); rotateCloseAnimation.setDuration(ANIMATION_TIME); } }
29.045455
135
0.627182
9bd6f5d319f8d76959f225fadb81ccd4053efda5
670
package rs.raf.projekat1.luka_petrovic_rn3318.ui.login.data; import rs.raf.projekat1.luka_petrovic_rn3318.ui.login.data.model.LoggedInUser; import java.io.IOException; /** * Class that handles authentication w/ login credentials and retrieves user information. */ public class LoginDataSource { public Result<LoggedInUser> login(String name, String surname, String bank) { try { LoggedInUser fakeUser = new LoggedInUser(name, surname, bank); return new Result.Success<>(fakeUser); } catch (Exception e) { return new Result.Error(new IOException("Error logging in", e)); } } }
30.454545
89
0.674627
8087cc7d03dc9e5d729b6955bf4ba3ecdbce1e16
1,804
package com.g2forge.alexandria.java.io.dataaccess; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.nio.channels.Channel; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.file.Path; import com.g2forge.alexandria.java.type.ref.ITypeRef; import lombok.Getter; import lombok.RequiredArgsConstructor; @Getter @RequiredArgsConstructor public class StringDataSource implements IDataSource { protected final String string; @Override public byte[] getBytes() { return getString().getBytes(); } @Override public <T extends Channel> T getChannel(ITypeRef<T> type) { if ((type != null) && !ReadableByteChannel.class.equals(type.getErasedType())) throw new IllegalArgumentException(); @SuppressWarnings("unchecked") final T retVal = (T) Channels.newChannel(toByteArrayInputStream()); return retVal; } @Override public Path getPath() { throw new UnsupportedOperationException(); } @Override public <T extends Reader> T getReader(ITypeRef<T> type) { if (type.isAssignableFrom(ITypeRef.of(StringReader.class))) { @SuppressWarnings({ "unchecked", "resource" }) final T retVal = (T) new StringReader(getString()); return retVal; } return IDataSource.getReader(this, type); } @Override public <T extends InputStream> T getStream(ITypeRef<T> type) { if (type.isAssignableFrom(ITypeRef.of(ByteArrayInputStream.class))) { @SuppressWarnings("unchecked") final T retVal = (T) toByteArrayInputStream(); return retVal; } return IDataSource.getStream(this, type); } @Override public boolean isUsed() { return false; } protected ByteArrayInputStream toByteArrayInputStream() { return new ByteArrayInputStream(getBytes()); } }
26.529412
118
0.755543
9dc8e9bac5eb133604f63fa50a3c924ec3ce9858
5,734
/* * Copyright (c) 2020 HRZN LTD * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.hrznstudio.galacticraft.server.command; import com.hrznstudio.galacticraft.api.celestialbodies.CelestialBodyType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback; import net.minecraft.command.argument.DimensionArgumentType; import net.minecraft.command.argument.EntityArgumentType; import net.minecraft.entity.Entity; import net.minecraft.server.command.CommandManager; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.world.ServerWorld; import net.minecraft.text.LiteralText; import net.minecraft.text.Style; import net.minecraft.text.TranslatableText; import net.minecraft.util.Formatting; import java.util.Collection; import java.util.function.Consumer; /** * @author <a href="https://github.com/StellarHorizons">StellarHorizons</a> */ public class GalacticraftCommands { public static void register() { CommandRegistrationCallback.EVENT.register((commandDispatcher, b) -> { commandDispatcher.register(LiteralArgumentBuilder.<ServerCommandSource>literal("dimensiontp") .requires(serverCommandSource -> serverCommandSource.hasPermissionLevel(2)) .then(CommandManager.argument("dimension", DimensionArgumentType.dimension()) .executes(GalacticraftCommands::teleport) .then(CommandManager.argument("entities", EntityArgumentType.entities()) .executes(((GalacticraftCommands::teleportMultiple)))))); commandDispatcher.register(LiteralArgumentBuilder.<ServerCommandSource>literal("gcr_listbodies") .executes(context -> { StringBuilder builder = new StringBuilder(); CelestialBodyType.getAll().forEach(celestialBodyType -> builder.append(celestialBodyType.getTranslationKey()).append("\n")); context.getSource().sendFeedback(new LiteralText(builder.toString()), true); return 1; })); }); } private static int teleport(CommandContext<ServerCommandSource> context) { context.getSource().getMinecraftServer().execute(() -> { try { ServerWorld serverWorld = DimensionArgumentType.getDimensionArgument(context, "dimension"); if (serverWorld == null) { context.getSource().sendError(new TranslatableText("commands.galacticraft-rewoven.dimensiontp.failure.dimension").setStyle(Style.EMPTY.withColor(Formatting.RED))); return; } context.getSource().getPlayer().moveToWorld(serverWorld); context.getSource().sendFeedback(new TranslatableText("commands.galacticraft-rewoven.dimensiontp.success.single", serverWorld.getRegistryKey().getValue()), true); } catch (CommandSyntaxException ignore) { context.getSource().sendError(new TranslatableText("commands.galacticraft-rewoven.dimensiontp.failure.entity").setStyle(Style.EMPTY.withColor(Formatting.RED))); } }); return -1; } private static int teleportMultiple(CommandContext<ServerCommandSource> context) { context.getSource().getMinecraftServer().execute(() -> { try { ServerWorld serverWorld = DimensionArgumentType.getDimensionArgument(context, "dimension"); if (serverWorld == null) { context.getSource().sendError(new TranslatableText("commands.galacticraft-rewoven.dimensiontp.failure.dimension").setStyle(Style.EMPTY.withColor(Formatting.RED))); return; } Collection<? extends Entity> entities = EntityArgumentType.getEntities(context, "entities"); entities.forEach((Consumer<Entity>) entity -> { entity.moveToWorld(serverWorld); context.getSource().sendFeedback(new TranslatableText("commands.galacticraft-rewoven.dimensiontp.success.multiple", entities.size(), serverWorld.getRegistryKey().getValue()), true); }); } catch (CommandSyntaxException ignore) { context.getSource().sendError(new TranslatableText("commands.galacticraft-rewoven.dimensiontp.failure.entity").setStyle(Style.EMPTY.withColor(Formatting.RED))); } }); return -1; } }
53.588785
201
0.69428
099157fff240aa3d2c8e537637c3f313dac9e1ef
13,010
package net.sharplab.springframework.security.webauthn.sample.domain.component; import net.sharplab.springframework.security.webauthn.sample.domain.config.ModelMapperConfig; import net.sharplab.springframework.security.webauthn.sample.domain.entity.AuthorityEntity; import net.sharplab.springframework.security.webauthn.sample.domain.entity.GroupEntity; import net.sharplab.springframework.security.webauthn.sample.domain.entity.UserEntity; import net.sharplab.springframework.security.webauthn.sample.domain.exception.WebAuthnSampleEntityNotFoundException; import net.sharplab.springframework.security.webauthn.sample.domain.model.Authority; import net.sharplab.springframework.security.webauthn.sample.domain.model.Group; import net.sharplab.springframework.security.webauthn.sample.domain.model.User; import net.sharplab.springframework.security.webauthn.sample.domain.repository.AuthorityEntityRepository; import net.sharplab.springframework.security.webauthn.sample.domain.repository.GroupEntityRepository; import net.sharplab.springframework.security.webauthn.sample.domain.repository.UserEntityRepository; import org.junit.Rule; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.modelmapper.ModelMapper; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; /** * Test for GroupManagerImpl */ @SuppressWarnings("unchecked") public class GroupManagerImplTest { @Rule public MockitoRule mockito = MockitoJUnit.rule(); @InjectMocks private GroupManagerImpl target; @Mock private UserEntityRepository userEntityRepository; @Mock private GroupEntityRepository groupEntityRepository; @Mock private AuthorityEntityRepository authorityEntityRepository; @Spy ModelMapper modelMapper = ModelMapperConfig.createModelMapper(); @Test public void findGroup_test1(){ //Input int groupId = 1; GroupEntity retrievedGroup = new GroupEntity(); retrievedGroup.setId(1); //Given when(groupEntityRepository.findById(groupId)).thenReturn(Optional.of(retrievedGroup)); //When Group result = target.findGroup(groupId); //Then assertThat(result.getId()).isEqualTo(groupId); } @Test public void findAllGroups_test1(){ List<GroupEntity> retreivedGroupEntities = Collections.emptyList(); //Given when(groupEntityRepository.findAll()).thenReturn(retreivedGroupEntities); //When List<Group> result = target.findAllGroups(); //Then assertThat(result).isEqualTo(retreivedGroupEntities); } @Test public void findUsersInGroup_test1(){ int groupId = 1; List<UserEntity> users = Collections.emptyList(); GroupEntity retreivedGroupEntity = new GroupEntity(); retreivedGroupEntity.setUsers(users); //Given when(groupEntityRepository.findById(groupId)).thenReturn(Optional.of(retreivedGroupEntity)); //When List<User> result = target.findUsersInGroup(groupId); //Then assertThat(result).isEqualTo(users); } @Test public void findUsersInGroup_test2(){ String groupName = "groupA"; List<UserEntity> users = Collections.emptyList(); GroupEntity retreivedGroup = new GroupEntity(); retreivedGroup.setUsers(users); //Given when(groupEntityRepository.findOneByGroupName(groupName)).thenReturn(Optional.of(retreivedGroup)); //When List<User> result = target.findUsersInGroup(groupName); //Then assertThat(result).isEqualTo(users); } @Test(expected = WebAuthnSampleEntityNotFoundException.class) public void findUsersInGroup_test3(){ int groupId = 1; //Given when(groupEntityRepository.findById(groupId)).thenReturn(Optional.empty()); //When target.findUsersInGroup(groupId); } @Test(expected = WebAuthnSampleEntityNotFoundException.class) public void findUsersInGroup_test4(){ String groupName = "groupA"; //Given when(groupEntityRepository.findOneByGroupName(groupName)).thenReturn(Optional.empty()); //When target.findUsersInGroup(groupName); } @Test public void createGroup_test1(){ GroupEntity savedGroupEntity = new GroupEntity(); savedGroupEntity.setId(1); Group group = new Group(); //Given when(groupEntityRepository.save(any(GroupEntity.class))).thenReturn(savedGroupEntity); //When Group result = target.createGroup(group); assertThat(result.getId()).isEqualTo(1); } @Test public void deleteGroup_test1(){ int groupId = 1; //Given doNothing().when(groupEntityRepository).deleteById(groupId); //When target.deleteGroup(groupId); } @Test public void renameGroup_test1(){ int groupId = 1; GroupEntity retreivedGroupEntity = mock(GroupEntity.class); //Given when(groupEntityRepository.findById(groupId)).thenReturn(Optional.of(retreivedGroupEntity)); //When target.renameGroup(groupId, "newName"); //Then verify(retreivedGroupEntity).setGroupName("newName"); } @Test(expected = WebAuthnSampleEntityNotFoundException.class) public void renameGroup_test2(){ int groupId = 1; //Given when(groupEntityRepository.findById(groupId)).thenReturn(Optional.empty()); //When target.renameGroup(groupId, "newName"); } @Test public void addUserToGroup_test1(){ int userId = 1; int groupId = 1; UserEntity retreivedUser = new UserEntity(); GroupEntity retreivedGroup = mock(GroupEntity.class); List<UserEntity> userList = mock(List.class); //Given when(userEntityRepository.findById(userId)).thenReturn(Optional.of(retreivedUser)); when(groupEntityRepository.findById(groupId)).thenReturn(Optional.of(retreivedGroup)); when(retreivedGroup.getUsers()).thenReturn(userList); //When target.addUserToGroup(userId, groupId); //Then verify(userList).add(retreivedUser); } @Test(expected = WebAuthnSampleEntityNotFoundException.class) public void addUserToGroup_test2(){ int userId = 1; int groupId = 1; GroupEntity retreivedGroup = mock(GroupEntity.class); //Given when(userEntityRepository.findById(userId)).thenReturn(Optional.empty()); when(groupEntityRepository.findById(groupId)).thenReturn(Optional.of(retreivedGroup)); //When target.addUserToGroup(userId, groupId); } @Test(expected = WebAuthnSampleEntityNotFoundException.class) public void addUserToGroup_test3(){ int userId = 1; int groupId = 1; UserEntity retreivedUser = new UserEntity(); //Given when(userEntityRepository.findById(userId)).thenReturn(Optional.of(retreivedUser)); when(groupEntityRepository.findById(groupId)).thenReturn(Optional.empty()); //When target.addUserToGroup(userId, groupId); } @Test public void removeUserFromGroup_test1(){ int userId = 1; int groupId = 1; GroupEntity retrievedGroup = mock(GroupEntity.class); List<UserEntity> userList = mock(List.class); //Given when(groupEntityRepository.findById(groupId)).thenReturn(Optional.of(retrievedGroup)); when(retrievedGroup.getUsers()).thenReturn(userList); //When target.removeUserFromGroup(userId, groupId); //Then verify(userList).remove(groupId); } @Test(expected = WebAuthnSampleEntityNotFoundException.class) public void removeUserFromGroup_test2(){ int userId = 1; int groupId = 1; //Given when(groupEntityRepository.findById(groupId)).thenReturn(Optional.empty()); //When target.removeUserFromGroup(userId, groupId); } @Test public void findGroupAuthorities_test1(){ int groupId = 1; GroupEntity retrievedGroup = new GroupEntity(); AuthorityEntity authorityEntity = new AuthorityEntity(); authorityEntity.setAuthority("ROLE_ADMIN"); List<AuthorityEntity> retrievedGroupAuthorities = Collections.singletonList(authorityEntity); retrievedGroup.setAuthorities(retrievedGroupAuthorities); //Given when(groupEntityRepository.findById(groupId)).thenReturn(Optional.of(retrievedGroup)); //When List<Authority> result = target.findGroupAuthorities(groupId); //Then assertThat(result.get(0).getAuthority()).isSameAs("ROLE_ADMIN"); } @Test(expected = WebAuthnSampleEntityNotFoundException.class) public void findGroupAuthorities_test2(){ int groupId = 1; //Given when(groupEntityRepository.findById(groupId)).thenReturn(Optional.empty()); //When target.findGroupAuthorities(groupId); } @Test public void addGroupAuthority_test1(){ int groupId = 1; GroupEntity retrievedGroup = mock(GroupEntity.class); List<AuthorityEntity> retrievedGroupAuthorities = mock(List.class); AuthorityEntity retrievedGroupAuthority = new AuthorityEntity(); Authority groupAuthority = new Authority(); //Given when(groupEntityRepository.findById(groupId)).thenReturn(Optional.of(retrievedGroup)); when(retrievedGroup.getAuthorities()).thenReturn(retrievedGroupAuthorities); when(retrievedGroupAuthorities.add(retrievedGroupAuthority)).thenReturn(true); //When target.addGroupAuthority(groupId, groupAuthority); //Then verify(retrievedGroup).getAuthorities(); verify(retrievedGroupAuthorities).add(any(AuthorityEntity.class)); } @Test(expected = WebAuthnSampleEntityNotFoundException.class) public void addGroupAuthority_test2(){ int groupId = 1; Authority groupAuthority = new Authority(); //Given when(groupEntityRepository.findById(groupId)).thenReturn(Optional.empty()); //When target.addGroupAuthority(groupId, groupAuthority); //Then } @Test public void removeGroupAuthority_test1(){ int groupId = 1; int authorityId = 2; GroupEntity retrievedGroup = new GroupEntity(); List<AuthorityEntity> retrievedAuthorities = new ArrayList<>(); AuthorityEntity retrievedAuthorityEntity = new AuthorityEntity(); retrievedGroup.setAuthorities(retrievedAuthorities); retrievedAuthorities.add(retrievedAuthorityEntity); retrievedAuthorityEntity.setId(authorityId); Authority groupAuthority = new Authority(); groupAuthority.setId(authorityId); //Given when(groupEntityRepository.findById(groupId)).thenReturn(Optional.of(retrievedGroup)); when(authorityEntityRepository.findById(authorityId)).thenReturn(Optional.of(retrievedAuthorityEntity)); //When target.removeGroupAuthority(groupId, groupAuthority); //Then assertThat(retrievedAuthorities).doesNotContain(retrievedAuthorityEntity); } @Test(expected = WebAuthnSampleEntityNotFoundException.class) public void removeGroupAuthority_test2(){ int groupId = 1; int authorityId = 2; Authority groupAuthority = new Authority(); //Given when(groupEntityRepository.findById(groupId)).thenReturn(Optional.empty()); when(authorityEntityRepository.findById(authorityId)).thenReturn(Optional.empty()); //When target.removeGroupAuthority(groupId, groupAuthority); //Then } @Test(expected = WebAuthnSampleEntityNotFoundException.class) public void removeGroupAuthority_test3(){ int groupId = 1; int authorityId = 2; GroupEntity retrievedGroup = mock(GroupEntity.class); AuthorityEntity retrievedAuthorityEntity = new AuthorityEntity(); retrievedAuthorityEntity.setId(authorityId); List<AuthorityEntity> retrievedGroupAuthorities = new ArrayList<>(); retrievedGroupAuthorities.add(retrievedAuthorityEntity); Authority groupAuthority = new Authority(); groupAuthority.setId(1); //Given when(groupEntityRepository.findById(groupId)).thenReturn(Optional.of(retrievedGroup)); when(authorityEntityRepository.findById(authorityId)).thenReturn(Optional.empty()); //When target.removeGroupAuthority(groupId, groupAuthority); //Then } }
31.425121
116
0.695004
f172fb9e5812de5784925e2ff769779bb2555c8f
171
package io.adenium.exceptions; public class EmptyProgramCounterException extends PapayaException { public EmptyProgramCounterException() { super(""); } }
21.375
67
0.736842
18f9908d60e4bcaea2104900d09d41bfa594f2cc
1,511
package theFishing.cards; import basemod.ReflectionHacks; import com.badlogic.gdx.graphics.Color; import com.megacrit.cardcrawl.actions.animations.VFXAction; import com.megacrit.cardcrawl.cards.DamageInfo; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.monsters.AbstractMonster; import com.megacrit.cardcrawl.vfx.AbstractGameEffect; import com.megacrit.cardcrawl.vfx.combat.ThrowDaggerEffect; import theFishing.FishingMod; import theFishing.actions.FatalRunnableAction; import java.awt.*; import static theFishing.FishingMod.makeID; import static theFishing.util.Wiz.atb; public class Harpoon extends AbstractFishingCard { public final static String ID = makeID("Harpoon"); // intellij stuff attack, enemy, uncommon, 18, 5, , , 2, 1 public Harpoon() { super(ID, 2, CardType.ATTACK, CardRarity.UNCOMMON, CardTarget.ENEMY); baseDamage = 18; baseMagicNumber = magicNumber = 2; exhaust = true; tags.add(CardTags.HEALING); } public void use(AbstractPlayer p, AbstractMonster m) { AbstractGameEffect tde = new ThrowDaggerEffect(m.hb.cX, m.hb.cY); ReflectionHacks.setPrivate(tde, AbstractGameEffect.class, "color", Color.DARK_GRAY.cpy()); atb(new VFXAction(tde)); atb(new FatalRunnableAction(m, new DamageInfo(p, damage, damageTypeForTurn), () -> { FishingMod.nextCombatFish += magicNumber; })); } public void upp() { upgradeDamage(6); } }
35.139535
98
0.724686
2a832dcf4950e224b7dbc6b5921a9f8a3b52abd0
10,796
package dominatingset; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Set; import graph.Graph; import graph.GraphVertex; import util.RandSet; import graph.CapGraph; // @author Karol Cichosz public class GreedyAlgorithm { protected CapGraph graph; protected AlgoSelectionMethod[] algos; protected HashMap<Integer, HashSet<Integer>> graphVertexesByNumOfEdges; private int methodRequestCounter; protected Random randGenerator; //5 versions of improved greedy algorithm public enum AlgoSelectionMethod { TOP_EDGE, ONEFORTH_OF_TOP_EDGES, RANDOM_EDGE, ONCE_TOP_ONCE_RANDOM_EDGE, TOP_RANDOM_EDGE; } public GreedyAlgorithm() { algos = new AlgoSelectionMethod[] { AlgoSelectionMethod.TOP_EDGE, AlgoSelectionMethod.ONEFORTH_OF_TOP_EDGES, AlgoSelectionMethod.RANDOM_EDGE, AlgoSelectionMethod.ONCE_TOP_ONCE_RANDOM_EDGE, AlgoSelectionMethod.TOP_RANDOM_EDGE }; methodRequestCounter = 0; randGenerator = new Random(System.currentTimeMillis()); graphVertexesByNumOfEdges = null; } public GreedyAlgorithm(CapGraph graph) { this(); this.setGraph(graph); } //key: numOfEdges object: set of Nodes with numOfEdges private HashMap<Integer, HashSet<Integer>> getVertexesByNumOfEdges() { HashMap<Integer, HashSet<Integer>> result = new HashMap<Integer, HashSet<Integer>>(); if (graph != null) { for (GraphVertex vertex : graph.getVertexes().values()) { //if first element added in the particular numOfEdge set if (!result.containsKey(vertex.getNumberOfEdges())) { //create set result.put(vertex.getNumberOfEdges(), new HashSet<Integer>()); } result.get(vertex.getNumberOfEdges()).add(vertex.getVertexNumber()); } } return result; } //finding dominating set by Naive algorithm public Set<Integer> getDominatingSetByEasyAlgo() { Set<Integer> result = new HashSet<Integer>(); if (graph == null) { return null; } if (graph.getVertexes().size() == 1) { result.add(graph.getVertexes().keySet().iterator().next()); return result; } //deep copy of the graph, which will be changed HashMap<Integer, GraphVertex> vertexesForDS = graph.cloneVertexes(); if (graphVertexesByNumOfEdges == null) { graphVertexesByNumOfEdges = getVertexesByNumOfEdges(); } //finding nodes by numOfEdges HashMap<Integer, HashSet<Integer>> vertexesByNumOfEdges = copyVertexesByNumOfEdges(graphVertexesByNumOfEdges); //sorting numOfEdges to find the greater one ArrayList<Integer> maxEdgesOrder = new ArrayList<Integer>(vertexesByNumOfEdges.keySet()); Collections.sort(maxEdgesOrder); int maxNumOfEdges; int numOfSelectedVertex; while (!vertexesForDS.isEmpty()) { //finding greatest edgeNum maxNumOfEdges = maxEdgesOrder.get(maxEdgesOrder.size() - 1); //geting first node with max edgeNum numOfSelectedVertex = vertexesByNumOfEdges.get(maxNumOfEdges).iterator().next(); // for every neighbour(edge) of selected vertex for (Integer neighbour : vertexesForDS.get(numOfSelectedVertex).getSecondVertexes()) { if (vertexesForDS.containsKey(neighbour)) { //remove node(neighbour) from numEdges HashMap vertexesByNumOfEdges.get(vertexesForDS.get(neighbour).getNumberOfEdges()).remove(neighbour); if (vertexesByNumOfEdges.get(vertexesForDS.get(neighbour).getNumberOfEdges()).isEmpty()) { maxEdgesOrder.remove(new Integer(vertexesForDS.get(neighbour).getNumberOfEdges())); } //remove node(neighbour) from deep copy of the graph vertexesForDS.remove(neighbour); } } //remove selected node from numEdges HashMap vertexesByNumOfEdges.get(vertexesForDS.get(numOfSelectedVertex).getNumberOfEdges()) .remove(numOfSelectedVertex); if (vertexesByNumOfEdges.get(vertexesForDS.get(numOfSelectedVertex).getNumberOfEdges()).isEmpty()) { maxEdgesOrder.remove(new Integer(vertexesForDS.get(numOfSelectedVertex).getNumberOfEdges())); } //remove selected node from deep copy of the graph vertexesForDS.remove(numOfSelectedVertex); //adding to solutions set result.add(numOfSelectedVertex); } return result; } //update network structures after removing selected Vertex private void updateNetwork(Integer numOfSelectedVertex, HashMap<Integer, GraphVertex> vertexesForDS, HashMap<Integer, HashSet<Integer>> vertexesByNumOfEdges) { ArrayList<Integer> vertexToRemove = new ArrayList<Integer>(); vertexToRemove.add(numOfSelectedVertex); vertexToRemove.addAll(vertexesForDS.get(numOfSelectedVertex).getSecondVertexes()); Iterator<Integer> it = vertexToRemove.iterator(); do { removeVertexFromNetwork(it.next(), vertexesForDS, vertexesByNumOfEdges); } while (it.hasNext()); } //selecting node as part of dominating set using indicated method private int chooseNum(AlgoSelectionMethod method, HashMap<Integer, HashSet<Integer>> vertexesByNumOfEdges) { ArrayList<Integer> maxEdgesOrder; int maxNumOfEdges; switch (method) { case TOP_EDGE: maxEdgesOrder = new ArrayList<Integer>(vertexesByNumOfEdges.keySet()); Collections.sort(maxEdgesOrder); maxNumOfEdges = maxEdgesOrder.get(maxEdgesOrder.size() - 1); //first in top edge list return vertexesByNumOfEdges.get(maxNumOfEdges).iterator().next(); case ONEFORTH_OF_TOP_EDGES: maxEdgesOrder = new ArrayList<Integer>(vertexesByNumOfEdges.keySet()); Collections.sort(maxEdgesOrder); int sel = maxEdgesOrder.size() - 1; if (maxEdgesOrder.size() > 3) { sel -= randGenerator.nextInt(maxEdgesOrder.size() / 4); } //finding numOfEdge among 25% of greatest int selectedNumOfEdges = maxEdgesOrder.get(sel); HashSet<Integer> vertexedBySelectedEdge = vertexesByNumOfEdges.get(selectedNumOfEdges); //getting first node in selected numEdge return vertexedBySelectedEdge.iterator().next(); case RANDOM_EDGE: ArrayList<Integer> selectedEdges = new ArrayList<Integer>(vertexesByNumOfEdges.keySet()); //getting random edge return vertexesByNumOfEdges.get(selectedEdges.get(randGenerator.nextInt(selectedEdges.size()))).iterator() .next(); case ONCE_TOP_ONCE_RANDOM_EDGE: if ((++methodRequestCounter) % 2 == 1) { //once top_edge method return chooseNum(AlgoSelectionMethod.TOP_EDGE, vertexesByNumOfEdges); } else { //once random_edge method return chooseNum(AlgoSelectionMethod.RANDOM_EDGE, vertexesByNumOfEdges); } case TOP_RANDOM_EDGE: //finding top numOfEdges maxEdgesOrder = new ArrayList<Integer>(vertexesByNumOfEdges.keySet()); Collections.sort(maxEdgesOrder); maxNumOfEdges = maxEdgesOrder.get(maxEdgesOrder.size() - 1); //lack of edges doesn't matter which one if (maxNumOfEdges == 0) { return vertexesByNumOfEdges.get(maxNumOfEdges).iterator().next(); } else { //get random vertex return RandSet.getRandomElement(vertexesByNumOfEdges.get(maxNumOfEdges)); } default: return -1; } } //created hard copy of hashmap for future changes protected HashMap<Integer, HashSet<Integer>> copyVertexesByNumOfEdges(HashMap<Integer, HashSet<Integer>> toCopyVertexesByNumOfEdges) { HashMap<Integer, HashSet<Integer>> result = new HashMap<Integer, HashSet<Integer>>(); for(Integer toCopyKey : toCopyVertexesByNumOfEdges.keySet()) { result.put(toCopyKey, new HashSet<Integer>(toCopyVertexesByNumOfEdges.get(toCopyKey))); } return result; } //implementation of improved greedy algorithm public Set<Integer> getDominatingSetBySelectedAlgo(AlgoSelectionMethod method) { //int resultCounter = 0; Set<Integer> result = new HashSet<Integer>(); //boundary cases if (graph == null) { return null; } if (graph.getVertexes().size() == 1) { result.add(graph.getVertexes().keySet().iterator().next()); return result; } //create deep copy of the graph for future change HashMap<Integer, GraphVertex> vertexesForDS = graph.cloneVertexes(); if (graphVertexesByNumOfEdges == null) { graphVertexesByNumOfEdges = getVertexesByNumOfEdges(); } //create deep copy of Hashmap (key: numOfEdges object: setOfVertexes with numOfEdges) HashMap<Integer, HashSet<Integer>> vertexesByNumOfEdges = copyVertexesByNumOfEdges(graphVertexesByNumOfEdges); int numOfSelectedVertex; //until remaining graph has nodes while (!vertexesForDS.isEmpty()) { numOfSelectedVertex = chooseNum(method, vertexesByNumOfEdges); updateNetwork(numOfSelectedVertex, vertexesForDS, vertexesByNumOfEdges); result.add(numOfSelectedVertex); /*if (++resultCounter % 50000 == 0) { System.out.println(resultCounter + " results; network has:" + vertexesForDS.size() + " elements"); }*/ } return result; } //remove vertex and related edges from network structures private void removeVertexFromNetwork(Integer numOfVertexToRemove, HashMap<Integer, GraphVertex> network, HashMap<Integer, HashSet<Integer>> vertexesByNumOfEdges) { if (network.containsKey(numOfVertexToRemove)) { int numOfEdges; //updating EdgesFrom Set for (Integer firstPartOfEdge : network.get(numOfVertexToRemove).getFirstVertexes()) { numOfEdges = network.get(firstPartOfEdge).getNumberOfEdges(); network.get(firstPartOfEdge).getSecondVertexes().remove(numOfVertexToRemove); // update vertexesByNumOfEdges vertexesByNumOfEdges.get(numOfEdges).remove(firstPartOfEdge); if (vertexesByNumOfEdges.get(numOfEdges).isEmpty()) { vertexesByNumOfEdges.remove(numOfEdges); } if (!vertexesByNumOfEdges.containsKey(numOfEdges - 1)) { vertexesByNumOfEdges.put(numOfEdges - 1, new HashSet<Integer>()); } vertexesByNumOfEdges.get(numOfEdges - 1).add(firstPartOfEdge); } //updating edgesTo set for (Integer secondPartOfEdge : network.get(numOfVertexToRemove).getSecondVertexes()) { network.get(secondPartOfEdge).getFirstVertexes().remove(numOfVertexToRemove); } numOfEdges = network.get(numOfVertexToRemove).getNumberOfEdges(); network.remove(numOfVertexToRemove); // update vertexesByNumOfEdges vertexesByNumOfEdges.get(numOfEdges).remove(numOfVertexToRemove); if (vertexesByNumOfEdges.get(numOfEdges).isEmpty()) { vertexesByNumOfEdges.remove(numOfEdges); } } } public Graph getGraph() { return graph; } public void setGraph(CapGraph graph) { this.graph = graph; } public AlgoSelectionMethod[] getAlgos() { return this.algos; } }
34.602564
136
0.727399
24cd68b3c24e4118b8f513e6fa8cd5298c9c7c1f
2,037
package org.rxjava.service.reward.entity; import lombok.Data; import org.rxjava.service.reward.status.RewardEventStatus; import org.rxjava.service.reward.type.RewardEventType; import org.rxjava.service.reward.type.RewardType; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.mongodb.core.index.IndexDirection; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; import java.time.LocalDateTime; import java.util.List; /** * @author happy 2019-05-14 16:39 * 奖励事件 */ @Document @Data public class RewardEvent { @Id private String id; /** * 奖励名称 */ private String name; /** * 客户Id */ private String partnerId; /** * 操作员Id */ private String operatorId; /** * 会员卡Id */ private String vipCardId; /** * 单人领取次数限制 */ private int personNumLimit; /** * 单人领取金额/张数/积分数 */ private int personValueLimit; /** * 总领取次数限制 */ private int totalNumLimit; /** * 总领取金额/张数/积分数 */ private int totalValueLimit; /** * 奖品类型:红包/积分/优惠券 * * @see RewardType */ private String rewardType; /** * 奖品Id列表:红包Id/积分Id/优惠券Id */ private List<String> rewardIds; /** * 可发放开始日期 */ private LocalDateTime availableBeginDate; /** * 可发放结束日期 */ private LocalDateTime availableEndDate; /** * 事件类型:系统SYSTEM/手动MANUAL/外部 * * @see RewardEventType */ private String eventType; /** * 奖励状态:正常NORMAL,关闭CLOSED */ private String status = RewardEventStatus.NORMAL.name(); /** * 创建日期 */ @CreatedDate @Indexed(direction = IndexDirection.DESCENDING) private LocalDateTime createDate; /** * 修改日期 */ @LastModifiedDate private LocalDateTime updateDate; }
20.785714
66
0.637703
23c961880d6d506aced6f244626cdde1c3466048
1,824
package com.yonyou.etl.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; /** * 数据校验 * * @author yhao */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("report_data_check") public class ReportDataCheck implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.UUID) private String id; @TableField("rpt_item_type_id") private String rptItemTypeId; @TableField("accbookid") private String accbookid; @TableField("pk_org") private String pkOrg; @TableField("period") private String period; /** * 0:未发布,1:发布 , 2:未发布 */ @TableField("state") private Integer state; @TableField("success") private Boolean success; @TableField("ts") private String ts; @TableField("tenantid") private String tenantid; @TableField("srctplid") private String srctplid; @TableField("year") private String year; /** * 结账状态: 0 未结账 1 已结账 */ @TableField("accbook_state") private Integer accbookState; /** * 0:正常,1:计算中, 2:无数据 */ @TableField("data_state") private Integer dataState; /** * 0或者空:未启用,1:已启用 */ @TableField("enabled") private Integer enabled; @TableField("ytenant_id") private String ytenantId; }
21.714286
58
0.615132
dc723a33f31bfa0d0e2fbcbb7572124d8c23d627
262
package com.kent.gumiho.sql.basic.ast.expr; import com.kent.gumiho.sql.basic.visitor.SQLVisitor; /** * @author kongtong.ouyang on 2018/2/8. */ public class SQLOrderByItemExpr { // @Override // protected void accept0(SQLVisitor visitor) { // // } }
17.466667
52
0.69084
ba51e638ce14e693cfb8692c3f7d11b8593b1511
1,280
package org.dimdev.dimdoors.world.pocket.type; import com.mojang.serialization.Codec; import net.minecraft.util.DyeColor; public enum PocketColor { WHITE(0, DyeColor.WHITE), ORANGE(1, DyeColor.ORANGE), MAGENTA(2, DyeColor.MAGENTA), LIGHT_BLUE(3, DyeColor.LIGHT_BLUE), YELLOW(4, DyeColor.YELLOW), LIME(5, DyeColor.LIME), PINK(6, DyeColor.PINK), GRAY(7, DyeColor.GRAY), LIGHT_GRAY(8, DyeColor.LIGHT_GRAY), CYAN(9, DyeColor.CYAN), PURPLE(10, DyeColor.PURPLE), BLUE(11, DyeColor.BLUE), BROWN(12, DyeColor.BROWN), GREEN(13, DyeColor.GREEN), RED(14, DyeColor.RED), BLACK(15, DyeColor.BLACK), NONE(16, null); private final int id; private final DyeColor color; public static Codec<PocketColor> CODEC = Codec.INT.xmap(PocketColor::from, PocketColor::getId); PocketColor(int id, DyeColor color) { this.id = id; this.color = color; } public DyeColor getColor() { return this.color; } public Integer getId() { return this.id; } public static PocketColor from(DyeColor color) { for (PocketColor a : PocketColor.values()) { if (color == a.color) { return a; } } return NONE; } public static PocketColor from(int id) { for (PocketColor a : PocketColor.values()) { if (id == a.id) { return a; } } return NONE; } }
20.31746
96
0.691406
ce2af127ca09efcf41681c820da982cc9e305ccc
492
public class FrenchKeyboard extends Keyboard { private static final String[] french=new String[] { " 0", ".1", "abc\u00E0\u00E2\u00E6\u00E72", "def\u00E9\u00E8\u00EA\u00EB3", "ghi\u00EE\u00EF4", "jkl5", "mno\u00F4\u0153\u00F16", "pqrs7", "tuv\u00FB\u00F9\u00FC8", "wxyz\u00FF9", "!,';:[]<>-/\\", "#-/\\"}; protected String[] getKeymap() { return french; } }
23.428571
55
0.479675
4c3055f09ea7ef08a5f73f27fff3ae223914eeb0
4,703
/* * Copyright 2005 JBoss 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 org.drools.guvnor.client.ruleeditor; import java.util.List; import org.drools.guvnor.client.messages.Constants; import org.drools.ide.common.client.modeldriven.brl.DSLSentence; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; /** * This is a popup list for "content assistance" - although on the web, * its not assistance - its mandatory ;) */ public class ChoiceList extends PopupPanel { private ListBox list; private final DSLSentence[] sentences; private HorizontalPanel buttons; private TextBox filter; private Constants constants = ((Constants) GWT.create( Constants.class )); /** * Pass in a list of suggestions for the popup lists. * Set a click listener to get notified when the OK button is clicked. */ public ChoiceList(final DSLSentence[] sen, final DSLRuleEditor self) { super( true ); setGlassEnabled( true ); this.sentences = sen; filter = new TextBox(); filter.setWidth( "100%" ); final String defaultMessage = constants.enterTextToFilterList(); filter.setText( defaultMessage ); filter.addFocusHandler( new FocusHandler() { public void onFocus(FocusEvent event) { filter.setText( "" ); } } ); filter.addBlurHandler( new BlurHandler() { public void onBlur(BlurEvent event) { filter.setText( defaultMessage ); } } ); filter.addKeyUpHandler( new KeyUpHandler() { public void onKeyUp(KeyUpEvent event) { if ( event.getNativeKeyCode() == KeyCodes.KEY_ENTER ) { applyChoice( self ); } else { populateList( ListUtil.filter( sentences, filter.getText() ) ); } } } ); filter.setFocus( true ); VerticalPanel panel = new VerticalPanel(); panel.add( filter ); list = new ListBox(); list.setVisibleItemCount( 5 ); populateList( ListUtil.filter( this.sentences, "" ) ); panel.add( list ); Button ok = new Button( constants.OK() ); ok.addClickHandler( new ClickHandler() { public void onClick(ClickEvent event) { applyChoice( self ); } } ); Button cancel = new Button( constants.Cancel() ); cancel.addClickHandler( new ClickHandler() { public void onClick(ClickEvent event) { hide(); } } ); buttons = new HorizontalPanel(); buttons.add( ok ); buttons.add( cancel ); panel.add( buttons ); add( panel ); setStyleName( "ks-popups-Popup" ); //NON-NLS } private void applyChoice(final DSLRuleEditor self) { self.insertText( getSelectedItem() ); hide(); } private void populateList(List<DSLSentence> filtered) { list.clear(); for ( int i = 0; i < filtered.size(); i++ ) { list.addItem( ((DSLSentence) filtered.get( i )).sentence ); } } public String getSelectedItem() { return list.getItemText( list.getSelectedIndex() ); } }
32.434483
88
0.619817
34e6710c706c149b79a69d14461cd2fe86ba3c84
1,447
/** * */ package backtracking; /** * @author PRATAP LeetCode 1255 * */ public class MaximumScoreWordsFormedByLetters { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String[] words = { "dog", "cat", "dad", "good" }; char[] letters = { 'a', 'a', 'c', 'd', 'd', 'd', 'g', 'o', 'o' }; int[] score = { 1, 0, 9, 5, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int maxScore = maxScoreWords(words, letters, score); System.out.println(maxScore); } public static int maxScoreWords(String[] words, char[] letters, int[] score) { int[] freq = new int[26]; for (int i = 0; i < letters.length; i++) { freq[letters[i] - 'a']++; } int ans = solve(words, freq, score, 0); return ans; } private static int solve(String[] words, int[] freq, int[] score, int idx) { // TODO Auto-generated method stub if (idx == words.length) return 0; int sno = solve(words, freq, score, idx + 1); int sscore = 0; String word = words[idx]; boolean flag = true; for (int i = 0; i < word.length(); i++) { if (freq[word.charAt(i) - 'a'] == 0) { flag = false; } freq[word.charAt(i) - 'a']--; sscore += score[word.charAt(i) - 'a']; } int syes = 0; if (flag) syes = sscore + solve(words, freq, score, idx + 1); for (int i = 0; i < word.length(); i++) { freq[word.charAt(i) - 'a']++; } return Math.max(sno, syes); } }
24.948276
97
0.555632
c22d8c1c335da5d88a5222532c9c33aab0572522
1,169
package model.VO; public class UserInfoVO { private int usercode; private String userid; private String userpw; private String username; private int userphone; private String useremail; public int getUsercode() { return usercode; } public void setUsercode(int usercode) { this.usercode = usercode; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getUserpw() { return userpw; } public void setUserpw(String userpw) { this.userpw = userpw; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getUserphone() { return userphone; } public void setUserphone(int userphone) { this.userphone = userphone; } public String getUseremail() { return useremail; } public void setUseremail(String useremail) { this.useremail = useremail; } @Override public String toString() { return "CoinVO [usercode=" + usercode + ", userid=" + userid + ", userpw=" + userpw + ", username=" + username + ", userphone=" + userphone + ", useremail=" + useremail + "]"; } }
21.254545
112
0.695466
2cb193ec9fc9ab0ab918121c4959a2874251720c
3,382
/* * 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.tika.parser.geo.topic.gazetteer; import java.lang.reflect.Type; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.apache.commons.io.Charsets; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.tika.parser.geo.topic.GeoParserConfig; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; public class GeoGazetteerClient { private static final String SEARCH_API = "/api/search"; private static final String SEARCH_PARAM = "s"; private static final String PING = "/api/ping"; private static final Logger LOG = Logger.getLogger(GeoGazetteerClient.class.getName()); private String url; /** * Pass URL on which lucene-geo-gazetteer is available - eg. http://localhost:8765/api/search * @param url */ public GeoGazetteerClient(String url) { this.url = url; } public GeoGazetteerClient(GeoParserConfig config) { this.url = config.getGazetteerRestEndpoint(); } /** * Calls API of lucene-geo-gazetteer to search location name in gazetteer. * @param locations List of locations to be searched in gazetteer * @return Map of input location strings to gazetteer locations */ public Map<String, List<Location>> getLocations(List<String> locations){ HttpClient httpClient = new DefaultHttpClient(); try { URIBuilder uri = new URIBuilder(url+SEARCH_API); for(String loc: locations){ uri.addParameter(SEARCH_PARAM, loc); } HttpGet httpGet = new HttpGet(uri.build()); HttpResponse resp = httpClient.execute(httpGet); String respJson = IOUtils.toString(resp.getEntity().getContent(), Charsets.UTF_8); @SuppressWarnings("serial") Type typeDef = new TypeToken<Map<String, List<Location>>>(){}.getType(); return new Gson().fromJson(respJson, typeDef); } catch (Exception e) { LOG.severe(e.getMessage()); } return null; } /** * Ping lucene-geo-gazetteer API * @return true if API is available else returns false */ public boolean checkAvail() { HttpClient httpClient = new DefaultHttpClient(); try { HttpGet httpGet = new HttpGet(url + PING); HttpResponse resp = httpClient.execute(httpGet); if(resp.getStatusLine().getStatusCode() == 200){ return true; } } catch (Exception e) { LOG.severe(e.getMessage()); } return false; } }
30.196429
94
0.73152
49dde40c164d702fb910fe4c0233ad6650e0f2fd
334
package com.google.android.gms.internal.auth; import android.os.IInterface; import android.os.RemoteException; import com.google.android.gms.auth.api.proxy.ProxyResponse; public interface zzal extends IInterface { void zza(ProxyResponse proxyResponse) throws RemoteException; void zzb(String str) throws RemoteException; }
27.833333
65
0.808383
123e503fe4e5f1aace9a5dbc14ffa2eab136b33d
663
package com.code10.security.model; import org.kie.api.definition.type.Expires; import org.kie.api.definition.type.Role; /** * Added to the running kie session every time a new {@link LogItem} is created. * Used only by the rule engine, so that old events are automatically retracted from the session. */ @Role(Role.Type.EVENT) @Expires("24h") public class LogEvent { private LogItem logItem; public LogEvent() { } public LogEvent(LogItem logItem) { this.logItem = logItem; } public LogItem getLogItem() { return logItem; } public void setLogItem(LogItem logItem) { this.logItem = logItem; } }
21.387097
97
0.678733
4e9ba248484f54061f24f893ed430604ac9f3d37
895
package day06; import java.util.*; public class HomeWork { public static void main(String[] args) { // {{1},{2,2},{3,4,5}}; int[][]scores = new int[3][5]; Scanner in = new Scanner(System.in); //给每个班的每个学生赋值 for(int i = 0;i<scores.length;i++){ //统计每个班总分 double sum = 0; System.out.println("=====请输入第"+(i+1)+"个班级的成绩========"); for(int j = 0;j<scores[i].length;j++){ System.out.println("请输入第"+(j+1)+"个学生的成绩:"); scores[i][j] = in.nextInt(); sum = sum+scores[i][j]; } System.out.println("第"+(i+1)+"个班级的平均分为:"+sum/scores[i].length); } int max = scores[0][0]; int min = scores[0][0]; for(int i = 0;i<scores.length;i++){ for(int j = 0;j<scores[i].length;j++){ if(max<scores[i][j]){ max = scores[i][j]; } if(min>scores[i][j]){ min = scores[i][j]; } } } System.out.println("最高分:"+max+",最低分:"+min); } }
22.375
66
0.532961
1a2633cf7ec161d9a760719021fb1fee0b3a5f93
6,782
// __________________________________ // ______| Copyright 2008-2015 |______ // \ | Breakpoint Pty Limited | / // \ | http://www.breakpoint.com.au | / // / |__________________________________| \ // /_________/ \_________\ // // 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 au.com.breakpoint.hedron.core; import static org.junit.Assert.assertTrue; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import org.junit.Test; import au.com.breakpoint.hedron.core.context.ThreadContext; public class SmartFileTest { @Test public void testSmartFileChanged () { try { writeSampleFile (TEMP_FILEPATH_1, LINE_COUNT); writeSampleFile (TEMP_FILEPATH_2, LINE_COUNT); assertTrue (HcUtilFile.areFilesIdentical (TEMP_FILEPATH_1, TEMP_FILEPATH_2)); final boolean updated = writeSmartSampleFile (TEMP_FILEPATH_2, LINE_COUNT + 1); assertTrue (updated); assertTrue (!HcUtilFile.areFilesIdentical (TEMP_FILEPATH_1, TEMP_FILEPATH_2)); } finally { HcUtilFile.safeDeleteFileNoThrow (TEMP_FILEPATH_1); HcUtilFile.safeDeleteFileNoThrow (TEMP_FILEPATH_2); } } @Test public void testSmartFileChanged_multi () { try { final int count = 3; writeSampleFile (TEMP_FILEPATH_1, LINE_COUNT, count); writeSampleFile (TEMP_FILEPATH_2, LINE_COUNT, count); assertTrue (HcUtilFile.areFilesIdentical (TEMP_FILEPATH_1, TEMP_FILEPATH_2)); final boolean updated = writeSmartSampleFile (TEMP_FILEPATH_2, LINE_COUNT + 1, count); assertTrue (updated); assertTrue (!HcUtilFile.areFilesIdentical (TEMP_FILEPATH_1, TEMP_FILEPATH_2)); } finally { HcUtilFile.safeDeleteFileNoThrow (TEMP_FILEPATH_1); HcUtilFile.safeDeleteFileNoThrow (TEMP_FILEPATH_2); } } @Test public void testSmartFileUnchanged () { try { writeSampleFile (TEMP_FILEPATH_1, LINE_COUNT); writeSampleFile (TEMP_FILEPATH_2, LINE_COUNT); assertTrue (HcUtilFile.areFilesIdentical (TEMP_FILEPATH_1, TEMP_FILEPATH_2)); final boolean updated = writeSmartSampleFile (TEMP_FILEPATH_2, LINE_COUNT); assertTrue (!updated); assertTrue (HcUtilFile.areFilesIdentical (TEMP_FILEPATH_1, TEMP_FILEPATH_2)); } finally { HcUtilFile.safeDeleteFileNoThrow (TEMP_FILEPATH_1); HcUtilFile.safeDeleteFileNoThrow (TEMP_FILEPATH_2); } } @Test public void testSmartFileUnchanged_multi () { try { final int count = 3; writeSampleFile (TEMP_FILEPATH_1, LINE_COUNT, count); writeSampleFile (TEMP_FILEPATH_2, LINE_COUNT, count); assertTrue (HcUtilFile.areFilesIdentical (TEMP_FILEPATH_1, TEMP_FILEPATH_2)); final boolean updated = writeSmartSampleFile (TEMP_FILEPATH_2, LINE_COUNT, count); assertTrue (!updated); assertTrue (HcUtilFile.areFilesIdentical (TEMP_FILEPATH_1, TEMP_FILEPATH_2)); } finally { HcUtilFile.safeDeleteFileNoThrow (TEMP_FILEPATH_1); HcUtilFile.safeDeleteFileNoThrow (TEMP_FILEPATH_2); } } private static String getTempPath (final String filename) { return HcUtil.formFilepath (HcUtil.getTempDirectoryName (), filename); } private static void writeSampleFile (final String filepath, final int lines) { writeSampleFile (filepath, lines, 1); } private static void writeSampleFile (final String filepath, final int lines, final int count) { try (final PrintWriter pw = new PrintWriter (new FileWriter (filepath))) { writeSampleLines (pw, lines, count); } catch (final IOException e) { // Translate the exception. ThreadContext.throwFault (e); } } private static void writeSampleLines (final PrintWriter pw, final int lines, final int count) { for (int k = 0; k < count; ++k) { for (int i = 0; i < lines; ++i) { for (int j = 0; j < i; ++j) { pw.print (k + ":line " + i + " "); } pw.println (k + ":line " + i); } } } private static boolean writeSmartSampleFile (final String filePath, final int lines) { boolean updated = false; SmartFile f = null; try { f = new SmartFile (filePath); for (int i = 0; i < lines; ++i) { for (int j = 0; j < i; ++j) { f.print ("0:line " + i + " "); } f.printf ("0:line %s%n", i); } } finally { updated = HcUtilFile.safeClose (f); } return updated; } private static boolean writeSmartSampleFile (final String filePath, final int lines, final int count) { boolean updated = false; SmartFile f = null; try { f = new SmartFile (filePath); for (int k = 0; k < count; ++k) { f.setSectionNumber (k); for (int i = 0; i < lines; ++i) { for (int j = 0; j < i; ++j) { f.print (k + ":line " + i + " "); } f.printf ("%s:line %s%n", k, i); } } } finally { updated = HcUtilFile.safeClose (f); } return updated; } private static final int LINE_COUNT = 3; private static final String TEMP_FILEPATH_1 = getTempPath ("SmartFileTest-1.temp"); private static final String TEMP_FILEPATH_2 = getTempPath ("SmartFileTest-2.temp"); }
32.449761
105
0.567532
36a768f1f2c59220a644e4e2020a760f3394eaed
1,034
/* */ package com.infinityraider.agricraft.api.v1.adapter; import java.util.Optional; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * Interface for determining the true value of certain objects. * * @param <T> The type adapted by this adapter. */ public interface IAgriAdapter<T> { /** * Determines if this adapter is capable of converting the given object to the target type. * * @param obj The object that needs to be converted. * @return {@literal true} if this adapter can convert the given object to the target type, * {@literal false} otherwise. */ boolean accepts(@Nullable Object obj); /** * Converts the given object to the target type of this adapter, or returns the empty optional. * <p> * Notice, implementations of this method should never return null, instead the method should * return {@link Optional#empty()}. * * @param obj * @return */ @Nonnull Optional<T> valueOf(@Nullable Object obj); }
27.210526
99
0.675048
0346c635f4abef6f46d1c49714b02c93093adc03
269
package main.server.connection.request.base; public enum RequestType { Add, Auth, Contact, Message, Register, ContactList, Empty, AuthSuccess, AuthFailed, RegistationSuccess, RegistationFailed, InvalidMessage, InvalidRequest, AddSuccess, AddFailed }
13.45
44
0.769517
edfdbbf4776a63edb02b163280362137199c6494
69
public abstract class Test { Runnable r = new TestSubclass() {}; }
23
38
0.681159
8d6bf57e3ef4401046dcdc6d55149e5216107cd7
874
package org.cyclops.commoncapabilities.modcompat.ic2.capability.work; import ic2.api.item.ElectricItem; import ic2.core.block.machine.tileentity.TileEntityAdvMiner; import ic2.core.item.tool.ItemScanner; import ic2.core.util.StackUtil; /** * Worker capability for {@link TileEntityAdvMiner}. * @author rubensworks */ public class TileAdvMinerWorker extends TileElectricMachineWorkerBase<TileEntityAdvMiner> { public TileAdvMinerWorker(TileEntityAdvMiner tile) { super(tile); } @Override public boolean canWork() { return super.canWork() || (getEnergy().getEnergy() >= 512.0D && !getTile().getWorld().isBlockPowered(getTile().getPos()) && !StackUtil.isEmpty(getTile().scannerSlot.get()) && ElectricItem.manager.canUse(getTile().scannerSlot.get(), 64.0D) ); } }
32.37037
91
0.679634
3b3f097bfa7041a5e450fa35f67a5433d6263da1
8,062
/* * (C) Copyright 2017 Nuxeo (http://nuxeo.com/) and others. * * 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. * * Contributors: * Funsho David * */ package org.nuxeo.directory.test; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.NuxeoException; import org.nuxeo.ecm.core.api.SystemPrincipal; import org.nuxeo.ecm.core.api.local.ClientLoginModule; import org.nuxeo.ecm.core.api.local.LoginStack; import org.nuxeo.ecm.core.test.CoreFeature; import org.nuxeo.ecm.core.test.annotations.Granularity; import org.nuxeo.ecm.core.test.annotations.RepositoryConfig; import org.nuxeo.ecm.directory.Directory; import org.nuxeo.ecm.directory.DirectoryDeleteConstraintException; import org.nuxeo.ecm.directory.DirectoryException; import org.nuxeo.ecm.directory.Session; import org.nuxeo.ecm.directory.api.DirectoryService; import org.nuxeo.ecm.directory.multi.MultiDirectory; import org.nuxeo.ecm.platform.login.test.ClientLoginFeature; import org.nuxeo.runtime.api.Framework; import org.nuxeo.runtime.test.runner.Deploy; import org.nuxeo.runtime.test.runner.Features; import org.nuxeo.runtime.test.runner.FeaturesRunner; import org.nuxeo.runtime.test.runner.RunnerFeature; import org.nuxeo.runtime.transaction.TransactionHelper; import com.google.inject.Binder; import com.google.inject.name.Names; /** * @since 9.2 */ @Features({ CoreFeature.class, ClientLoginFeature.class }) @RepositoryConfig(cleanup = Granularity.METHOD) @Deploy("org.nuxeo.ecm.directory.api") @Deploy("org.nuxeo.ecm.directory") @Deploy("org.nuxeo.ecm.core.schema") @Deploy("org.nuxeo.ecm.directory.types.contrib") @Deploy("org.nuxeo.ecm.directory.sql") @Deploy("org.nuxeo.directory.mongodb") public class DirectoryFeature implements RunnerFeature { public static final String USER_DIRECTORY_NAME = "userDirectory"; public static final String GROUP_DIRECTORY_NAME = "groupDirectory"; protected CoreFeature coreFeature; protected DirectoryConfiguration directoryConfiguration; protected Granularity granularity; protected Map<String, Map<String, Map<String, Object>>> allDirectoryData; protected LoginStack loginStack; @Override public void beforeRun(FeaturesRunner runner) { granularity = runner.getFeature(CoreFeature.class).getGranularity(); } @Override public void configure(final FeaturesRunner runner, Binder binder) { bindDirectory(binder, USER_DIRECTORY_NAME); bindDirectory(binder, GROUP_DIRECTORY_NAME); } @Override public void start(FeaturesRunner runner) { coreFeature = runner.getFeature(CoreFeature.class); directoryConfiguration = new DirectoryConfiguration(coreFeature.getStorageConfiguration()); directoryConfiguration.init(); try { directoryConfiguration.deployContrib(runner); } catch (Exception e) { throw new NuxeoException(e); } } @Override public void beforeSetup(FeaturesRunner runner) { if (granularity != Granularity.METHOD) { return; } // record all directories in their entirety allDirectoryData = new HashMap<>(); DirectoryService directoryService = Framework.getService(DirectoryService.class); loginStack = ClientLoginModule.getThreadLocalLogin(); loginStack.push(new SystemPrincipal(null), null, null); try { for (Directory dir : directoryService.getDirectories()) { // Do not save multi-directories as subdirectories will be saved if (dir.isReadOnly() || dir instanceof MultiDirectory) { continue; } try (Session session = dir.getSession()) { session.setReadAllColumns(true); // needs to fetch the password too List<DocumentModel> entries = session.query(Collections.emptyMap(), Collections.emptySet(), Collections.emptyMap(), true); // fetch references Map<String, Map<String, Object>> data = entries.stream().collect( Collectors.toMap(DocumentModel::getId, entry -> entry.getProperties(dir.getSchema()))); allDirectoryData.put(dir.getName(), data); } } if (TransactionHelper.isTransactionActiveOrMarkedRollback()) { TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); } } catch (Exception e) { loginStack.pop(); throw e; } } @Override public void afterTeardown(FeaturesRunner runner) { if (granularity != Granularity.METHOD) { return; } if (allDirectoryData == null) { // failure (exception or assumption failed) before any method was run return; } DirectoryService directoryService = Framework.getService(DirectoryService.class); try { // clear all directories boolean isAllClear; do { isAllClear = true; for (Directory dir : directoryService.getDirectories()) { // Do not purge multi-directories as subdirectories will be purged if (dir.isReadOnly() || dir instanceof MultiDirectory) { continue; } try (Session session = dir.getSession()) { List<String> ids = session.getProjection(Collections.emptyMap(), dir.getIdField()); for (String id : ids) { try { session.deleteEntry(id); } catch (DirectoryDeleteConstraintException e) { isAllClear = false; } } } } } while (!isAllClear); // re-create all directory entries for (Map.Entry<String, Map<String, Map<String, Object>>> each : allDirectoryData.entrySet()) { String directoryName = each.getKey(); Directory directory = directoryService.getDirectory(directoryName); Collection<Map<String, Object>> data = each.getValue().values(); try (Session session = directory.getSession()) { for (Map<String, Object> map : data) { try { session.createEntry(map); } catch (DirectoryException e) { // happens for filter directories // or when testing config changes if (!e.getMessage().contains("already exists") && !e.getMessage().contains("Missing id")) { throw e; } } } } } } finally { loginStack.pop(); } allDirectoryData = null; } protected void bindDirectory(Binder binder, final String name) { binder.bind(Directory.class).annotatedWith(Names.named(name)).toProvider( () -> Framework.getService(DirectoryService.class).getDirectory(name)); } }
39.135922
119
0.624907
33e4e1b0f09ad4fd014aa208cf378c29cb8ea755
12,757
/* * Copyright 2005-2014 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/ecl1.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.kra.irb.actions.decision; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JUnit4Mockery; import org.jmock.lib.concurrent.Synchroniser; import org.jmock.lib.legacy.ClassImposteriser; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.kuali.coeus.common.committee.impl.bo.CommitteeDecisionMotionType; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.kra.committee.bo.CommitteeMembership; import org.kuali.kra.committee.service.CommitteeService; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.irb.Protocol; import org.kuali.kra.irb.ProtocolDocument; import org.kuali.kra.irb.actions.ProtocolAction; import org.kuali.kra.irb.actions.ProtocolActionType; import org.kuali.kra.irb.actions.ProtocolStatus; import org.kuali.kra.irb.actions.assigncmtsched.ProtocolAssignCmtSchedBean; import org.kuali.kra.irb.actions.assigncmtsched.ProtocolAssignCmtSchedService; import org.kuali.kra.irb.actions.reviewcomments.ReviewCommentsBean; import org.kuali.kra.irb.actions.submit.*; import org.kuali.kra.irb.test.ProtocolFactory; import org.kuali.kra.test.infrastructure.KcIntegrationTestBase; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.service.DocumentService; import java.util.ArrayList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class CommitteeDecisionServiceTest extends KcIntegrationTestBase { private static final Integer YES_COUNT = 2; private static final Integer NO_COUNT = 0; private static final Integer ABSTAIN_COUNT = 0; private static final Integer RECUSED_COUNT = 0; private static final String VOTING_COMMENTS = "just some dumb comments"; private CommitteeDecisionServiceImpl service; private ProtocolSubmitActionService protocolSubmitActionService; private ProtocolAssignCmtSchedService protocolAssignCmtSchedService; private Mockery context = new JUnit4Mockery() {{ setImposteriser(ClassImposteriser.INSTANCE); setThreadingPolicy(new Synchroniser()); }}; @Before public void setUp() throws Exception { service = new CommitteeDecisionServiceImpl(); service.setProtocolActionService(KcServiceLocator.getService(ProtocolActionService.class)); service.setBusinessObjectService(KcServiceLocator.getService(BusinessObjectService.class)); service.setCommitteeService(getMockCommitteeService()); service.setDocumentService(getMockDocumentService()); protocolSubmitActionService = KcServiceLocator.getService(ProtocolSubmitActionService.class); protocolAssignCmtSchedService = KcServiceLocator.getService(ProtocolAssignCmtSchedService.class); } @After public void tearDown() throws Exception { service = null; protocolSubmitActionService = null; protocolAssignCmtSchedService = null; } @Test public void testProcessApproveCommitteeDecision() throws Exception { Protocol protocol = getProtocolAssignedToAgenda(); CommitteeDecision committeeDecision = getMockCommitteeDecisionBean(CommitteeDecisionMotionType.APPROVE); service.processCommitteeDecision(protocol, committeeDecision); ProtocolAction lastAction = protocol.getLastProtocolAction(); assertNotNull(lastAction); assertEquals(ProtocolActionType.RECORD_COMMITTEE_DECISION, lastAction.getProtocolActionTypeCode()); ProtocolSubmission submission = protocol.getProtocolSubmission(); assertNotNull(submission); assertEquals(CommitteeDecisionMotionType.APPROVE, submission.getCommitteeDecisionMotionTypeCode()); assertEquals(YES_COUNT, submission.getYesVoteCount()); assertEquals(NO_COUNT, submission.getNoVoteCount()); assertEquals(ABSTAIN_COUNT, submission.getAbstainerCount()); assertEquals(RECUSED_COUNT, submission.getRecusedCount()); assertEquals(VOTING_COMMENTS, submission.getVotingComments()); } @Test public void testProcessDisapproveCommitteeDecision() throws Exception { Protocol protocol = getProtocolAssignedToAgenda(); CommitteeDecision committeeDecision = getMockCommitteeDecisionBean(CommitteeDecisionMotionType.DISAPPROVE); service.processCommitteeDecision(protocol, committeeDecision); ProtocolAction lastAction = protocol.getLastProtocolAction(); assertNotNull(lastAction); assertEquals(ProtocolActionType.RECORD_COMMITTEE_DECISION, lastAction.getProtocolActionTypeCode()); ProtocolSubmission submission = protocol.getProtocolSubmission(); assertNotNull(submission); assertEquals(CommitteeDecisionMotionType.DISAPPROVE, submission.getCommitteeDecisionMotionTypeCode()); assertEquals(YES_COUNT, submission.getYesVoteCount()); assertEquals(NO_COUNT, submission.getNoVoteCount()); assertEquals(ABSTAIN_COUNT, submission.getAbstainerCount()); assertEquals(RECUSED_COUNT, submission.getRecusedCount()); assertEquals(VOTING_COMMENTS, submission.getVotingComments()); } @Test public void testProcessSMRCommitteeDecision() throws Exception { Protocol protocol = getProtocolAssignedToAgenda(); CommitteeDecision committeeDecision = getMockCommitteeDecisionBean(CommitteeDecisionMotionType.SPECIFIC_MINOR_REVISIONS); service.processCommitteeDecision(protocol, committeeDecision); ProtocolAction lastAction = protocol.getLastProtocolAction(); assertNotNull(lastAction); assertEquals(ProtocolActionType.RECORD_COMMITTEE_DECISION, lastAction.getProtocolActionTypeCode()); ProtocolSubmission submission = protocol.getProtocolSubmission(); assertNotNull(submission); assertEquals(CommitteeDecisionMotionType.SPECIFIC_MINOR_REVISIONS, submission.getCommitteeDecisionMotionTypeCode()); assertEquals(YES_COUNT, submission.getYesVoteCount()); assertEquals(NO_COUNT, submission.getNoVoteCount()); assertEquals(ABSTAIN_COUNT, submission.getAbstainerCount()); assertEquals(RECUSED_COUNT, submission.getRecusedCount()); assertEquals(VOTING_COMMENTS, submission.getVotingComments()); } @Test public void testProcessSRRCommitteeDecision() throws Exception { Protocol protocol = getProtocolAssignedToAgenda(); CommitteeDecision committeeDecision = getMockCommitteeDecisionBean(CommitteeDecisionMotionType.SUBSTANTIVE_REVISIONS_REQUIRED); service.processCommitteeDecision(protocol, committeeDecision); ProtocolAction lastAction = protocol.getLastProtocolAction(); assertNotNull(lastAction); assertEquals(ProtocolActionType.RECORD_COMMITTEE_DECISION, lastAction.getProtocolActionTypeCode()); ProtocolSubmission submission = protocol.getProtocolSubmission(); assertNotNull(submission); assertEquals(CommitteeDecisionMotionType.SUBSTANTIVE_REVISIONS_REQUIRED, submission.getCommitteeDecisionMotionTypeCode()); assertEquals(YES_COUNT, submission.getYesVoteCount()); assertEquals(NO_COUNT, submission.getNoVoteCount()); assertEquals(ABSTAIN_COUNT, submission.getAbstainerCount()); assertEquals(RECUSED_COUNT, submission.getRecusedCount()); assertEquals(VOTING_COMMENTS, submission.getVotingComments()); } private Protocol getProtocolAssignedToAgenda() throws Exception { ProtocolDocument protocolDocument = ProtocolFactory.createProtocolDocument(); protocolSubmitActionService.submitToIrbForReview(protocolDocument.getProtocol(), getMockSubmitAction()); assertEquals(ProtocolStatus.SUBMITTED_TO_IRB, protocolDocument.getProtocol().getProtocolStatusCode()); protocolAssignCmtSchedService.assignToCommitteeAndSchedule(protocolDocument.getProtocol(), getMockAssignCmtSchedBean()); assertEquals(ProtocolSubmissionStatus.SUBMITTED_TO_COMMITTEE, protocolDocument.getProtocol().getProtocolSubmission().getSubmissionStatusCode()); return protocolDocument.getProtocol(); } private ProtocolSubmitAction getMockSubmitAction() { final ProtocolSubmitAction action = context.mock(ProtocolSubmitAction.class); context.checking(new Expectations() {{ allowing(action).getSubmissionTypeCode(); will(returnValue(ProtocolSubmissionType.INITIAL_SUBMISSION)); allowing(action).getProtocolReviewTypeCode(); will(returnValue(ProtocolReviewType.FULL_TYPE_CODE)); allowing(action).getSubmissionQualifierTypeCode(); will(returnValue(ProtocolSubmissionQualifierType.ANNUAL_SCHEDULED_BY_IRB)); allowing(action).getNewCommitteeId(); will(returnValue(Constants.EMPTY_STRING)); allowing(action).getNewScheduleId(); will(returnValue(Constants.EMPTY_STRING)); allowing(action).getReviewers(); will(returnValue(new ArrayList<ProtocolReviewerBean>())); }}); return action; } private ProtocolAssignCmtSchedBean getMockAssignCmtSchedBean() { final ProtocolAssignCmtSchedBean bean = context.mock(ProtocolAssignCmtSchedBean.class); context.checking(new Expectations() {{ allowing(bean).getNewCommitteeId(); will(returnValue(Constants.EMPTY_STRING)); allowing(bean).getNewScheduleId(); will(returnValue(Constants.EMPTY_STRING)); allowing(bean).scheduleHasChanged(); will(returnValue(false)); }}); return bean; } private CommitteeService getMockCommitteeService() { final CommitteeService service = context.mock(CommitteeService.class); context.checking(new Expectations() {{ allowing(service).getAvailableMembers(null, null); will(returnValue(new ArrayList<CommitteeMembership>())); }}); return service; } private DocumentService getMockDocumentService() { final DocumentService service = context.mock(DocumentService.class); context.checking(new Expectations() {{ ignoring(service); }}); return service; } private CommitteeDecision getMockCommitteeDecisionBean(final String motionTypeCode) { final CommitteeDecision bean = context.mock(CommitteeDecision.class); context.checking(new Expectations() {{ allowing(bean).getMotionTypeCode(); will(returnValue(motionTypeCode)); allowing(bean).getYesCount(); will(returnValue(YES_COUNT)); allowing(bean).getNoCount(); will(returnValue(NO_COUNT)); allowing(bean).getAbstainCount(); will(returnValue(ABSTAIN_COUNT)); allowing(bean).getRecusedCount(); will(returnValue(RECUSED_COUNT)); allowing(bean).getVotingComments(); will(returnValue(VOTING_COMMENTS)); allowing(bean).getAbstainers(); will(returnValue(new ArrayList<CommitteePerson>())); allowing(bean).getRecused(); will(returnValue(new ArrayList<CommitteePerson>())); allowing(bean).getAbstainersToDelete(); will(returnValue(new ArrayList<CommitteePerson>())); allowing(bean).getRecusedToDelete(); will(returnValue(new ArrayList<CommitteePerson>())); allowing(bean).getReviewCommentsBean(); will(returnValue(new ReviewCommentsBean(Constants.EMPTY_STRING))); }}); return bean; } }
44.919014
152
0.717959
319819df27fb039997f7ebee40fe7e24a819cb7a
14,955
package fr.jrds.smiextensions.objects; import java.io.IOException; import java.nio.ByteBuffer; import java.time.Duration; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.snmp4j.asn1.BER; import org.snmp4j.asn1.BERInputStream; import org.snmp4j.smi.Integer32; import org.snmp4j.smi.IpAddress; import org.snmp4j.smi.OID; import org.snmp4j.smi.OctetString; import org.snmp4j.smi.Opaque; import org.snmp4j.smi.TimeTicks; import org.snmp4j.smi.Variable; import fr.jrds.smiextensions.Utils; import fr.jrds.smiextensions.log.LogAdapter; /** * A enumeration of Snmp types to help conversion and parsing. * @author Fabrice Bacchella * */ public enum SnmpType { /** * This can also manage the special float type as defined by Net-SNMP. But it don't parse float. * @author Fabrice Bacchella */ Opaque { @Override public Variable getVariable() { return new org.snmp4j.smi.Opaque(); } @Override public Object convert(Variable v) { Opaque var = (Opaque) v; //If not resolved, we will return the data as an array of bytes Object value = var.getValue(); try { byte[] bytesArray = var.getValue(); ByteBuffer bais = ByteBuffer.wrap(bytesArray); BERInputStream beris = new BERInputStream(bais); byte t1 = bais.get(); byte t2 = bais.get(); int l = BER.decodeLength(beris); if(t1 == TAG1) { if(t2 == TAG_FLOAT && l == 4) value = new Float(bais.getFloat()); else if(t2 == TAG_DOUBLE && l == 8) value = new Double(bais.getDouble()); } } catch (IOException e) { logger.error(var.toString()); } return value; } @Override public Variable parse(OidInfos oi, String text) { return new org.snmp4j.smi.Opaque(text.getBytes()); } }, /** * This type can use the context OidInfos to format numerical value to string and parse them. * @author Fabrice Bacchella * */ EnumVal { @Override public Variable getVariable() { return new org.snmp4j.smi.Integer32(); } @Override public Object convert(Variable v) { return v.toInt(); } @Override public String format(OidInfos oi, Variable v) { return java.lang.String.format("%s(%d)", oi.values.resolve(v.toInt()), v.toInt()); } @Override public Variable parse(OidInfos oi, String text) { Matcher m = VARIABLEPATTERN.matcher(text); m.find(); String numval = m.group("num"); String textval = m.group("text"); if( numval != null && oi.values.resolve(Integer.parseInt(numval)) !=null) { return new Integer32(Integer.parseInt(numval)); } else if (textval != null && oi.values.resolve(textval) != null){ return new Integer32(oi.values.resolve(textval)); } else { return null; } } }, String { @Override public Variable getVariable() { return new org.snmp4j.smi.OctetString(); } @Override public Object convert(Variable v) { OctetString octetVar = (OctetString)v; //It might be a C string, try to remove the last 0; //But only if the new string is printable int length = octetVar.length(); if(length > 1 && octetVar.get(length - 1) == 0) { OctetString newVar = octetVar.substring(0, length - 1); if(newVar.isPrintable()) { v = newVar; logger.debug("Convertion an octet stream from %s to %s", octetVar, v); } } return v.toString(); } @Override public String format(OidInfos oi, Variable v) { return v.toString(); } @Override public Variable parse(OidInfos oi, String text) { return OctetString.fromByteArray(text.getBytes()); } }, Unsigned { @Override public Variable getVariable() { return new org.snmp4j.smi.UnsignedInteger32(); } @Override public Object convert(Variable v) { return v.toLong(); } }, Unsigned32 { @Override public Variable getVariable() { return new org.snmp4j.smi.UnsignedInteger32(); } @Override public Object convert(Variable v) { return v.toLong(); } }, /** * Net-Snmp create it from LMS-COMPONENT-MIB, as an alias for UInteger32 * @author Fabrice Bacchella * */ UInteger { @Override public Variable getVariable() { return new org.snmp4j.smi.UnsignedInteger32(); } @Override public Object convert(Variable v) { return v.toLong(); } }, BitString { @SuppressWarnings("deprecation") @Override public Variable getVariable() { return new org.snmp4j.smi.BitString(); } @Override public Object convert(Variable v) { return v.toLong(); } }, /** * <ul> * <li>{@link #getVariable()} return an empty {@link org.snmp4j.smi.IpAddress} variable.</li> * <li>{@link #convert(Variable)} return a {@link java.net.InetAddress}.</li> * <li>{@link #format(OidInfos, Variable)} try to resolve the hostname associated with the IP address.</li> * <li>{@link #parse(OidInfos, String)} parse the string as an hostname or a IP address.</li> * </ul> * @author Fabrice Bacchella * */ IpAddr { @Override public Variable getVariable() { return new org.snmp4j.smi.IpAddress(); } @Override public Object convert(Variable v) { return ((IpAddress)v).getInetAddress(); } @Override public String format(OidInfos oi, Variable v) { IpAddress ip = (IpAddress) v; return ip.getInetAddress().getHostName(); } @Override public Variable parse(OidInfos oi, String text) { return new org.snmp4j.smi.IpAddress(text); } }, /** * <ul> * <li>{@link #getVariable()} return an empty {@link org.snmp4j.smi.IpAddress} variable.</li> * <li>{@link #convert(Variable)} return a {@link java.net.InetAddress}.</li> * <li>{@link #format(OidInfos, Variable)} try to resolve the hostname associated with the IP address.</li> * <li>{@link #parse(OidInfos, String)} parse the string as an hostname or a IP address.</li> * </ul> * @author Fabrice Bacchella * */ NetAddr { @Override public Variable getVariable() { return new org.snmp4j.smi.IpAddress(); } @Override public Object convert(Variable v) { return ((IpAddress)v).getInetAddress(); } @Override public String format(OidInfos oi, Variable v) { IpAddress ip = (IpAddress) v; return ip.getInetAddress().getHostName(); } @Override public Variable parse(OidInfos oi, String text) { return new org.snmp4j.smi.IpAddress(text); } }, ObjID { @Override public Variable getVariable() { return new org.snmp4j.smi.OID(); } @Override public Object convert(Variable v) { return v; } @Override public String format(OidInfos oi, Variable v) { return ((OID)v).format(); } @Override public Variable parse(OidInfos oi, String text) { return new OID(text); } }, INTEGER { @Override public Variable getVariable() { return new org.snmp4j.smi.Integer32(); } @Override public Object convert(Variable v) { return v.toInt(); } @Override public String format(OidInfos oi, Variable v) { return java.lang.String.valueOf(v.toInt()); } @Override public Variable parse(OidInfos oi, String text) { return new org.snmp4j.smi.Integer32(Integer.getInteger(text)); } }, Integer32 { @Override public Variable getVariable() { return new org.snmp4j.smi.Integer32(); } @Override public Object convert(Variable v) { return v.toInt(); } @Override public String format(OidInfos oi, Variable v) { return java.lang.String.valueOf(v.toInt()); } @Override public Variable parse(OidInfos oi, String text) { return new org.snmp4j.smi.Integer32(Integer.getInteger(text)); } }, /** * <ul> * <li>{@link #getVariable()} return an empty {@link org.snmp4j.smi.Counter32} variable.</li> * <li>{@link #convert(Variable)} return the value stored in a {@link java.lang.Long}.</li> * <li>{@link #parse(OidInfos, String)} parse the string as a long value.</li> * </ul> * @author Fabrice Bacchella * */ Counter { @Override public Variable getVariable() { return new org.snmp4j.smi.Counter32(); } @Override public Object convert(Variable v) { return v.toLong(); } @Override public String format(OidInfos oi, Variable v) { return java.lang.String.valueOf(v.toLong()); } @Override public Variable parse(OidInfos oi, String text) { return new org.snmp4j.smi.Counter32(Long.getLong(text)); } }, /** * <ul> * <li>{@link #getVariable()} return an empty {@link org.snmp4j.smi.Counter64} variable.</li> * <li>{@link #convert(Variable)} return the value stored in a {@link fr.jrds.SmiExtensions.Utils.UnsignedLong}.</li> * <li>{@link #parse(OidInfos, String)} parse the string as a long value.</li> * </ul> * @author Fabrice Bacchella * */ Counter64 { @Override public Variable getVariable() { return new org.snmp4j.smi.Counter64(); } @Override public Object convert(Variable v) { return Utils.getUnsigned(v.toLong()); } @Override public String format(OidInfos oi, Variable v) { return Long.toUnsignedString(v.toLong()); } @Override public Variable parse(OidInfos oi, String text) { return new org.snmp4j.smi.Counter64(Long.getLong(text)); } }, /** * <ul> * <li>{@link #getVariable()} return an empty {@link org.snmp4j.smi.Gauge32} variable.</li> * <li>{@link #convert(Variable)} return the value stored in a Long.</li> * <li>{@link #parse(OidInfos, String)} parse the string as a long value.</li> * </ul> * @author Fabrice Bacchella * */ Gauge { @Override public Variable getVariable() { return new org.snmp4j.smi.Gauge32(); } @Override public Object convert(Variable v) { return v.toLong(); } @Override public String format(OidInfos oi, Variable v) { return java.lang.String.valueOf(v.toLong()); } @Override public Variable parse(OidInfos oi, String text) { return new org.snmp4j.smi.Gauge32(Long.getLong(text)); } }, /** * <ul> * <li>{@link #getVariable()} return an empty {@link org.snmp4j.smi.TimeTicks} variable.</li> * <li>{@link #convert(Variable)} return the time ticks as a number of milliseconds stored in a Long</li> * <li>{@link #format(OidInfos, Variable)} format the value using {@link org.snmp4j.smi.TimeTicks#toString()} * <li>{@link #parse(OidInfos, String)} can parse a number, expressing timeticks or the result of {@link org.snmp4j.smi.TimeTicks#toString()} * </ul> * @author Fabrice Bacchella * */ TimeTicks { @Override public Variable getVariable() { return new org.snmp4j.smi.TimeTicks(); } @Override public Object convert(Variable v) { return ((TimeTicks)v).toMilliseconds(); } @Override public String format(OidInfos oi, Variable v) { return v.toString(); } @Override public Variable parse(OidInfos oi, String text) { try { long duration = Long.parseLong(text); return new org.snmp4j.smi.TimeTicks(duration); } catch (NumberFormatException e) { Matcher m = TimeTicksPattern.matcher(text); if (m.matches()) { String days = m.group("days") != null ? m.group("days") : "0"; String hours = m.group("hours"); String minutes = m.group("minutes"); String seconds = m.group("seconds"); String fraction = m.group("fraction"); String formatted = java.lang.String.format("P%sDT%sH%sM%s.%sS", days, hours, minutes,seconds, fraction); TimeTicks tt = new TimeTicks(); tt.fromMilliseconds(Duration.parse(formatted).toMillis()); return tt; } else { return new org.snmp4j.smi.Null(); } } } }, ; // Used to parse time ticks static final private Pattern TimeTicksPattern = Pattern.compile("(?:(?<days>\\d+) days?, )?(?<hours>\\d+):(?<minutes>\\d+):(?<seconds>\\d+)(?:\\.(?<fraction>\\d+))?"); static final private LogAdapter logger = LogAdapter.getLogger(SnmpType.class); static final private byte TAG1 = (byte) 0x9f; static final private byte TAG_FLOAT = (byte) 0x78; static final private byte TAG_DOUBLE = (byte) 0x79; static final private Pattern VARIABLEPATTERN = Pattern.compile("(?<text>.*?)\\((?<num>\\d+)\\)"); /** * @return a empty instance of the associated Variable type */ public abstract Variable getVariable(); public String format(OidInfos oi, Variable v) { return v.toString(); }; public Variable parse(OidInfos oi, String text) { return null; }; public abstract Object convert(Variable v); public Object make(int[] in){ Variable v = getVariable(); OID oid = new OID(in); v.fromSubIndex(oid, true); return convert(v); }; }
33.606742
171
0.552123
935ec80cd116aa53ad67d8f634ead2fd4354e710
2,395
package uk.gov.dvla.oepp.domain.payment; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.MoreObjects; /** * Represents an initiate offence payment response. * The nested {@link Builder} should be used to create this class. * <p> * Example JSON * <pre> * { * "paymentID": 1, * "paymentReference": "9c2e189c19ed", * "paymentPageUrl": "http://localhost/secure-payment-form" * } * </pre> */ public class InitiateOffencePaymentResponse { private final Long paymentID; private final String paymentReference; private final String paymentPageUrl; @JsonCreator private InitiateOffencePaymentResponse(@JsonProperty("paymentID") Long paymentID, @JsonProperty("paymentReference") String paymentReference, @JsonProperty("paymentPageUrl") String paymentPageUrl) { this.paymentID = paymentID; this.paymentReference = paymentReference; this.paymentPageUrl = paymentPageUrl; } public Long getPaymentID() { return paymentID; } public String getPaymentReference() { return paymentReference; } public String getPaymentPageUrl() { return paymentPageUrl; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("paymentID", paymentID) .add("paymentReference", paymentReference) .add("paymentPageUrl", paymentPageUrl) .toString(); } public static class Builder { private Long paymentID; private String paymentReference; private String paymentPageUrl; public Builder setPaymentID(Long paymentID) { this.paymentID = paymentID; return this; } public Builder setPaymentReference(String paymentReference) { this.paymentReference = paymentReference; return this; } public Builder setPaymentPageUrl(String paymentPageUrl) { this.paymentPageUrl = paymentPageUrl; return this; } public InitiateOffencePaymentResponse create() { return new InitiateOffencePaymentResponse(paymentID, paymentReference, paymentPageUrl); } } }
29.207317
101
0.639666
05d63828d5e7dda7b0529c19d3dd008c5db9757b
2,775
package allbegray.slack.type; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Group { protected String id; protected String name; protected String is_group; protected Long created; protected String creator; protected Boolean is_archived; protected Boolean is_mpim; protected List<String> members; protected Topic topic; protected Purpose purpose; protected String last_read; protected int unread_count; protected int unread_count_display; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIs_group() { return is_group; } public void setIs_group(String is_group) { this.is_group = is_group; } public Long getCreated() { return created; } public void setCreated(Long created) { this.created = created; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Boolean getIs_archived() { return is_archived; } public void setIs_archived(Boolean is_archived) { this.is_archived = is_archived; } public Boolean getIs_mpim() { return is_mpim; } public void setIs_mpim(Boolean is_mpim) { this.is_mpim = is_mpim; } public List<String> getMembers() { if (members == null) { members = new ArrayList<String>(); } return members; } public void setMembers(List<String> members) { this.members = members; } public Topic getTopic() { return topic; } public void setTopic(Topic topic) { this.topic = topic; } public Purpose getPurpose() { return purpose; } public void setPurpose(Purpose purpose) { this.purpose = purpose; } public String getLast_read() { return last_read; } public void setLast_read(String last_read) { this.last_read = last_read; } public int getUnread_count() { return unread_count; } public void setUnread_count(int unread_count) { this.unread_count = unread_count; } public int getUnread_count_display() { return unread_count_display; } public void setUnread_count_display(int unread_count_display) { this.unread_count_display = unread_count_display; } @Override public String toString() { return "Group [id=" + id + ", name=" + name + ", is_group=" + is_group + ", created=" + created + ", creator=" + creator + ", is_archived=" + is_archived + ", is_mpim=" + is_mpim + ", members=" + members + ", topic=" + topic + ", purpose=" + purpose + ", last_read=" + last_read + ", unread_count=" + unread_count + ", unread_count_display=" + unread_count_display + "]"; } }
19.821429
180
0.708468
d9f6faea55bfb2c36fa7cdb7c13a94d3dc4c8901
654
package permutation; /** * A(A也是他的编号)是一个孤傲的人,在一个n个人(其中编号依次为1到n)的队列中, * 他于其中的标号为b和标号c的人都有矛盾,所以他不会和他们站在相邻的位置。 现在问你满足A的要求的对列有多少种? * * 给定人数n和三个人的标号A,b和c,请返回所求答案,保证人数小于等于11且大于等于3。 * * @author dell * */ public class LonelyA { // N个人全排列总数为n!,其中a与b相邻总数为(将ab和ba看做一个人)=(n-1)*2! // 其中a与c相邻的总数为(将ac和ca看做一个人)= (n-1)*2! // 这其中有bac和cab两种情况被包含进去(将三个看成一个人,多减了一次) = (n-2)!*2 // 所以结果为n!-(n-1)!-(n-1)!+(n-2)!*2 public int getWays(int n, int A, int b, int c) { if (n == 0) { return 0; } return go(n) - (go(n - 1) * 4) + (go(n - 2) * 2); } public int go(int n) { int res = 1; for (int i = 1; i <= n; i++) { res *= i; } return res; } }
19.818182
58
0.591743
9654334e4dbae3ae9b4b419c0e205179485c0e2a
40,401
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.mky.image; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import java.awt.*; import java.awt.image.DataBufferInt; import java.awt.image.FilteredImageSource; import java.awt.image.ImageFilter; import java.awt.image.ImageObserver; import java.awt.image.ImageProducer; import java.awt.image.RGBImageFilter; import java.util.Random; import java.util.Vector; /** * * @author PDI */ public class UIToolKit { public static void main(String[] args) { //Tests ImageIcon icon = new ImageIcon(); //getWin7StyleRectNewsInk icon.setImage(getWithShadow(getWin7StyleRectNewsInk(800, 600,1.0f, true),1.0f,false)); JOptionPane.showMessageDialog(null, icon); //getSphereImage icon.setImage(getSphereImage(800, 600,1.0f, true)); JOptionPane.showMessageDialog(null, icon); //getRandomShape icon.setImage(getRandomShape(800, 600,1.0f, true)); JOptionPane.showMessageDialog(null, icon); //getRandomCurve icon.setImage(getRandomCurve(800, 600,8,1.0f, true)); JOptionPane.showMessageDialog(null, icon); icon.setImage(getWithShadow(getWin7StyleRectWC(800, 600,1.0f, true),1.0f,false)); JOptionPane.showMessageDialog(null, icon); icon.setImage(getWithShadow(getWin7StyleRect(800, 600,1.0f, true),1.0f,false)); JOptionPane.showMessageDialog(null, icon); icon.setImage(getWithShadow(getWin7StyleRect2(800, 600,1.0f, true),1.0f,false)); JOptionPane.showMessageDialog(null, icon); icon.setImage(getWithShadow(getWin7StyleRect3(800, 600,1.0f, true),1.0f,false)); JOptionPane.showMessageDialog(null, icon); icon.setImage(getNewsPrintBG(800, 600, 5,1.0f, true)); JOptionPane.showMessageDialog(null, icon); icon.setImage(getParametricCurve(800, 600,1.0f, true)); JOptionPane.showMessageDialog(null, icon); //getNewsPrintBG//getParametricCurve } public static BufferedImage getWithShadow( BufferedImage toTessilate,float Transparency, boolean debug) { BufferedImage bimg=new DropShadowPanel().createDropShadow(toTessilate);// BufferedImage img = new BufferedImage(bimg.getWidth(), bimg.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); g.drawImage(bimg, 0, 0, null); g.drawImage(toTessilate, 0, 0, null); return img; } /** * Returns Khakee color combination * 0- Khakee, 1-LightInk, 2- DarkInk, 3- DarkPage * @return */ public static Color[] KhakeeTheme(){ Color[] result=new Color[4]; Color Khakee = new Color(242,242,192); result[0]=Khakee; Color LightInk = new Color(6, 112, 154); result[1]=LightInk; Color DarkInk = new Color(14,16,93); result[2]=DarkInk; Color DarkPage = new Color(164, 160, 135); result[3]=DarkPage; return result; } /** * Takes integer as input and returns the number of rows and columns needs to put them in a GUI. * @param BlocksToDisplay * @param debug * @return */ public static int[] getBestVisualArrangement(int BlocksToDisplay,boolean debug){ int rows=1; int columns=1; boolean incrementRow=true; while(true){ if(rows*columns>=BlocksToDisplay){ if(debug) //System.out.println("#getBestVisualArrangement BlocksToDisplay="+BlocksToDisplay+" rows="+rows+"\t columns="+columns +"\t scale= 1/"+Math.max(rows, columns)); return new int[]{rows,columns,Math.max(rows, columns)}; } if(incrementRow) // Start with row increment {rows++; incrementRow=false;} else {columns++; incrementRow=true;} } } /** * This will speed up the animation.Based on Cos() * Using the array in reverse will slow down animation. * @param MaxDelay * @return */ public static int[] getFastMotionDelay(int MaxDelay){ double LocXScale=0.01; int[] result=new int[(int)(1.0/LocXScale)]; for (int i = 0; i< result.length; i++) { MaxDelay = MaxDelay - (int) (MaxDelay * Math.cos(LocXScale * Math.PI / 2)); result[i]=MaxDelay; //System.out.println("Animdelay="+Animdelay); LocXScale = LocXScale + 0.01; } return result; } /** * This will speed up the animation.Based on Cos() * Using the array in reverse will slow down animation. * * @param MaxDelay * @return */ public static int[] getSlowMotionDelay(int MaxDelay){ double LocXScale=0.001; int[] result=new int[(int)(1.0/LocXScale)]; for (int i = 0; i< result.length; i++) { MaxDelay = MaxDelay - (int) (MaxDelay * Math.cos(LocXScale * Math.PI / 2)); result[i]=MaxDelay; //System.out.println("Animdelay="+Animdelay); LocXScale = LocXScale + 0.001; } return result; } public static BufferedImage getParametricCurve(int Width, int Height,float Transparency, boolean debug) { Color blue4 = new Color(6,112,154); Color Khakee = new Color(242,242,142); // 14 16 93 BufferedImage img = new BufferedImage(Width, Height, BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); int temp[]=ParametricCurve.RandomCurve3(0.0, 200, 100); for(int i=0;i<10000;i++){ int[] result=ParametricCurve.RandomCurve3(i/10000.0, 200, 100); //g.fillOval(Width/2+result[0], Height/2+result[2], 3, 3); g.drawLine(Width+result[0], Height/2+result[2], Width+temp[0], Height/2+temp[2]); g.drawLine(0+result[0], 0/2+result[2], 0+temp[0], 0/2+temp[2]); g.setColor(blue4); //result=ParametricCurve.RandomCurve2(i/10000.0, 200, 100); //g.fillOval(Width/2+result[0], Height/2+result[2], 3, 3); //g.drawLine(Width/2+result[0], Height/2+result[2], Width/2+result[0], Height/2+result[2]); temp=result; } return img; } public static BufferedImage getRandomShape(int Width, int Height,float Transparency, boolean debug) { Color blue4 = new Color(6,112,154); Color Khakee = new Color(242,242,142); // 14 16 93 BufferedImage img = new BufferedImage(Width, Height, BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); // int result[][]=ParametricCurve.RandomClosedLoopCurve(10, 500); Double result[][]=ParametricCurve.RandomShape(4); //RandomClosedLoopSmoothCurve for(int i=0;i<result.length-1;i++){ g.setColor(blue4); // g.drawLine(Width+result[0], Height/2+result[2], Width+temp[0], Height/2+temp[2]); g.drawLine((int)(Width*result[i][0]), (int)(Height*result[i][1]),(int)( Width*result[i+1][0]),(int)(Height*result[i+1][1])); } g.drawLine((int)(Width*result[0][0]), (int)(Height*result[0][1]),(int)( Width*result[result.length-1][0]),(int)(Height*result[result.length-1][1])); return img; } public static BufferedImage getSphereImage(int Width, int Height,float Transparency, boolean debug) { Color blue4 = new Color(6,112,154); Color Khakee = new Color(242,242,142); // 14 16 93 BufferedImage img = new BufferedImage(Width, Height, BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); // int result[][]=ParametricCurve.RandomClosedLoopCurve(10, 500); double temp[]=ParametricCurve.Sphere(0); //RandomClosedLoopSmoothCurve for(int i=0;i<10000;i++){ double result[]=ParametricCurve.Sphere(i/10000.0); g.setColor(blue4); // g.drawLine(Width+result[0], Height/2+result[2], Width+temp[0], Height/2+temp[2]); g.drawLine((int)(.5*Width*result[2]), (int)(.5*Height*result[1]),(int)( .5*Width*temp[2]),(int)(.5*Height*temp[1])); temp=result; } // g.drawLine((int)(Width*result[0][0]), (int)(Height*result[0][1]),(int)( Width*result[result.length-1][0]),(int)(Height*result[result.length-1][1])); return img; } public static BufferedImage getRandomCurve(int Width, int Height,int numOfPoints,float Transparency, boolean debug) { Color blue4 = new Color(6,112,154); Color Khakee = new Color(242,242,142); // 14 16 93 BufferedImage img = new BufferedImage(Width, Height, BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); // int result[][]=ParametricCurve.RandomClosedLoopCurve(10, 500); int result[][]=ParametricCurve.RandomClosedLoopSmoothCurve(numOfPoints,Width<Height?Width:Height); //RandomClosedLoopSmoothCurve for(int i=0;i<result.length-1;i++){ g.setColor(blue4); // g.drawLine(Width+result[0], Height/2+result[2], Width+temp[0], Height/2+temp[2]); g.drawLine(result[i][0], result[i][1], result[i+1][0], result[i+1][1]); } g.drawLine(result[0][0], result[0][1], result[result.length-1][0], result[result.length-1][1]); return img; } /** * Returns Image with repeat * @param Width * @param Height * @param Transparency * @param toTessilate * @param debug * @return */ public static BufferedImage getTessilatedImage(int Width, int Height,float Transparency, BufferedImage toTessilate, boolean debug) { BufferedImage img = new BufferedImage(Width, Height, BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); int imageWidth = toTessilate.getWidth(); int imageHeight = toTessilate.getHeight(); int componentWidth = Width; int componentHeigth = Height; int ImageRepeatX = componentWidth / imageWidth; int ImageRepeatY = componentHeigth / imageHeight; //System.out.println("#OldBackground ImageRepeat="+ImageRepeatX); //if ((ImageRepeatX >= 1) | (ImageRepeatY >= 1)) { for (int i = 0; i <= ImageRepeatX; i++) { for (int j = 0; j <= ImageRepeatY; j++) { //System.out.println("#OldBackground Drawing="+i*imageWidth); g.drawImage(toTessilate, i * imageWidth, j * imageHeight, null); } } // } return img; } /** * Preview the image from byte data * @param ImageData * @param width * @param height */ // public static void PreviewImage(byte[] ImageData, int width,int height){ // BufferedImage originalImage = ScreenCapture.getByteAsImage(ImageData); // double xRatio = (double) width / originalImage.getWidth(); // double yRatio = (double) height / originalImage.getHeight(); // double imageScaleRatio = Math.min(xRatio, yRatio); // AffineTransform trans = AffineTransform.getScaleInstance(imageScaleRatio, imageScaleRatio); // // BufferedImage PreviewImage = new BufferedImage((int) (imageScaleRatio * originalImage.getWidth()), // (int) (imageScaleRatio * originalImage.getHeight()), BufferedImage.TYPE_INT_RGB); // Graphics2D g = PreviewImage.createGraphics(); // // g.drawImage(originalImage, 0, 0, getWidth(), getHeight(), null); // g.drawRenderedImage(originalImage, trans); // g.dispose(); // g.setComposite(AlphaComposite.Src); // g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // // ImageIcon icon = new ImageIcon(); // icon.setImage(PreviewImage); // JOptionPane.showMessageDialog(null, icon); // // } public static BufferedImage getNewsPrintBG(int Width, int Height, int BorderThickness, float Transparency, boolean DropShadow) { Color Khakee = new Color(242,242,192); BufferedImage img = new BufferedImage(Width, Height, BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); g.setStroke(new BasicStroke(8)); g.setColor(new Color(14,16,93)); //News Print Dark Ink g.fillRoundRect(0, 0, Width, Height, Width/10, Width/10); g.setColor(Khakee); g.fillRoundRect(BorderThickness, BorderThickness, Width-2*BorderThickness, Height-2*BorderThickness, Width/10-BorderThickness, Width/10-BorderThickness); if(DropShadow) return getWithShadow( img, Transparency, DropShadow); // g.drawRoundRect(0, 0, Width, Height, Width/10, Height/10); return img; } public static BufferedImage getNewsPrintBG2(int Width, int Height, int BorderThickness, float Transparency, boolean DropShadow) { Color Khakee = new Color(242,242,192); BufferedImage img = new BufferedImage(Width, Height, BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); g.setStroke(new BasicStroke(8)); g.setColor(new Color(14,16,93)); //News Print Dark Ink g.fillRect(0, 0, Width, Height); g.setColor(Khakee); g.fillRect(BorderThickness, BorderThickness, Width-2*BorderThickness, Height-2*BorderThickness); if(DropShadow) return getWithShadow( img, Transparency, DropShadow); // g.drawRoundRect(0, 0, Width, Height, Width/10, Height/10); return img; } public static BufferedImage getWin7StyleRectNewsInk(int Width, int Height,float Transparency, boolean debug) { // Color clrHi = new Color(0, 229, 0); Color border = new Color(50, 50,73); Color blue = KhakeeTheme()[1]; Color blue2 = new Color(157, 166, 254); Color blue3 = new Color(150, 156, 254); Color blue4 = KhakeeTheme()[1]; BufferedImage img = new BufferedImage(Width, Height, BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); GradientPaint gp = new GradientPaint(0, 0, blue2, Height/2, Height,blue, true); //Here we are setting our Gradient Paint as the color we want to use g.setPaint(gp); /* Here we are creating a rectangle and filling it * with our GradientPaint, this will serve as the background to our JPanel */ //g.fillRect(0, 0, Width, Height); g.fillPolygon(new int[]{0,0,Width/10,Width/5,Width/10}, new int[]{0,Height,Height,Height/2,0}, 5); g.fillRoundRect(0, 0, Width, Height, 10, 10); gp = new GradientPaint(0, 0, blue4, Height-Height/10, Height,blue3, false); g.setPaint(gp); g.fillRoundRect(0, Height/2, Width, Height, 0, 10); gp = new GradientPaint(0, 0, blue, Height/2, Height,blue2, true); g.setPaint(gp); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); g.fillPolygon(new int[]{Width,Width,Width-Width/5,Width-Width/10}, new int[]{0,Height,Height,0}, 4); g.setColor(border);//orange //g.setColor(orange);//orange //g.drawRect(0, 0, Width-1, Height-1); g.drawRoundRect(0, 0, Width-1, Height-1, 10, 10); g.setColor(Color.GREEN); return img; } /** * * @param Width * @param Height * @param Transparency * @param debug * @return */ public static BufferedImage getWin7StyleRect(int Width, int Height,float Transparency, boolean debug) { // Color clrHi = new Color(0, 229, 0); Color border = new Color(50, 50,73); Color blue = new Color(133, 137, 192); Color blue2 = new Color(157, 166, 254); Color blue3 = new Color(150, 156, 254); Color blue4 = new Color(200, 206, 254); BufferedImage img = new BufferedImage(Width, Height, BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); GradientPaint gp = new GradientPaint(0, 0, blue2, Height/2, Height,blue, true); //Here we are setting our Gradient Paint as the color we want to use g.setPaint(gp); /* Here we are creating a rectangle and filling it * with our GradientPaint, this will serve as the background to our JPanel */ //g.fillRect(0, 0, Width, Height); g.fillPolygon(new int[]{0,0,Width/10,Width/5,Width/10}, new int[]{0,Height,Height,Height/2,0}, 5); g.fillRoundRect(0, 0, Width, Height, 10, 10); gp = new GradientPaint(0, 0, blue4, Height-Height/10, Height,blue3, false); g.setPaint(gp); g.fillRoundRect(0, Height/2, Width, Height, 0, 10); gp = new GradientPaint(0, 0, blue, Height/2, Height,blue2, true); g.setPaint(gp); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); g.fillPolygon(new int[]{Width,Width,Width-Width/5,Width-Width/10}, new int[]{0,Height,Height,0}, 4); g.setColor(border);//orange //g.setColor(orange);//orange //g.drawRect(0, 0, Width-1, Height-1); g.drawRoundRect(0, 0, Width-1, Height-1, 10, 10); g.setColor(Color.GREEN); return img; } public static BufferedImage getWin7StyleRectWC(int Width, int Height,float Transparency, boolean debug) { // Color clrHi = new Color(0, 229, 0); Color border = new Color(50, 50,73); Color blue = new Color(133, 137, 192); Color blue2 = new Color(157, 166, 254); Color blue3 = new Color(150, 156, 254); Color blue4 = new Color(200, 206, 254); BufferedImage img = new BufferedImage(Width, Height, BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); GradientPaint gp = new GradientPaint(0, 0, blue2, Height/2, Height,blue, true); //Here we are setting our Gradient Paint as the color we want to use g.setPaint(gp); /* Here we are creating a rectangle and filling it * with our GradientPaint, this will serve as the background to our JPanel */ //g.fillRect(0, 0, Width, Height); g.fillPolygon(new int[]{0,0,Width/10,Width/5,Width/10}, new int[]{0,Height,Height,Height/2,0}, 5); g.fillRoundRect(0, 0, Width, Height, 10, 10); gp = new GradientPaint(0, 0, blue4, Height-Height/10, Height,blue3, false); g.setPaint(gp); g.fillRoundRect(0, Height/2, Width, Height, 0, 10); gp = new GradientPaint(0, 0, blue, Height/2, Height,blue2, true); g.setPaint(gp); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); g.fillPolygon(new int[]{Width,Width,Width-Width/5,Width-Width/10}, new int[]{0,Height,Height,0}, 4); //g.setColor(border);//orange //g.setColor(orange);//orange //g.drawRect(0, 0, Width-1, Height-1); g.drawRoundRect(0, 0, Width-1, Height-1, 10, 10); //g.setColor(Color.GREEN); int temp[]=ParametricCurve.RandomCurve3(0.0, 200, 100); for(int i=0;i<10000;i++){ int[] result=ParametricCurve.RandomCurve3(i/10000.0, 200, 100); //g.fillOval(Width/2+result[0], Height/2+result[2], 3, 3); g.drawLine(Width+result[0], Height/2+result[2], Width+temp[0], Height/2+temp[2]); g.setColor(blue4); //result=ParametricCurve.RandomCurve2(i/10000.0, 200, 100); //g.fillOval(Width/2+result[0], Height/2+result[2], 3, 3); //g.drawLine(Width/2+result[0], Height/2+result[2], Width/2+result[0], Height/2+result[2]); temp=result; } return img; } /** * * @param Width * @param Height * @param Transparency * @param debug * @return */ public static BufferedImage getWin7StyleRect2(int Width, int Height,float Transparency, boolean debug) { // if (Width < 100) { // Width = 100; // } //Check and set Threshold to 100px // if (Height < 70) { // Height = 70; // } //Check and set Threshold to 70px // Color clrHi = new Color(0, 229, 0); Color border = new Color(50, 73,50); Color blue = new Color(133, 192, 137); Color blue2 = new Color(157, 254, 166); Color blue3 = new Color(150, 254, 156); Color blue4 = new Color(200, 254, 206); Color orange = new Color(255, 63, 229); BufferedImage img = new BufferedImage(Width, Height, BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); GradientPaint gp = new GradientPaint(0, 0, blue2, Height/2, Height,blue, true); //Here we are setting our Gradient Paint as the color we want to use g.setPaint(gp); /* Here we are creating a rectangle and filling it * with our GradientPaint, this will serve as the background to our JPanel */ //g.fillRect(0, 0, Width, Height); g.fillPolygon(new int[]{0,0,Width/10,Width/5,Width/10}, new int[]{0,Height,Height,Height/2,0}, 5); g.fillRoundRect(0, 0, Width, Height, 10, 10); gp = new GradientPaint(0, 0, blue4, Height-Height/10, Height,blue3, false); g.setPaint(gp); g.fillRoundRect(0, Height/2, Width, Height, 0, 10); gp = new GradientPaint(0, 0, blue, Height/2, Height,blue2, true); g.setPaint(gp); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); g.fillPolygon(new int[]{Width,Width,Width-Width/5,Width-Width/10}, new int[]{0,Height,Height,0}, 4); g.setColor(border);//orange //g.setColor(orange);//orange //g.drawRect(0, 0, Width-1, Height-1); g.drawRoundRect(0, 0, Width-1, Height-1, 10, 10); g.setColor(Color.GREEN); return img; } /** * * @param Width * @param Height * @param Transparency * @param debug * @return */ public static BufferedImage getWin7StyleRect3(int Width, int Height,float Transparency, boolean debug) { // if (Width < 100) { // Width = 100; // } //Check and set Threshold to 100px // if (Height < 70) { // Height = 70; // } //Check and set Threshold to 70px // Color clrHi = new Color(0, 229, 0); Color border = new Color(73,50,50); Color blue = new Color(192,133,137); Color blue2 = new Color(254,157,166); Color blue3 = new Color(254,150,156); Color blue4 = new Color(254,200,206); Color orange = new Color(63,255,229); BufferedImage img = new BufferedImage(Width, Height, BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); GradientPaint gp = new GradientPaint(0, 0, blue2, Height/2, Height,blue, true); //Here we are setting our Gradient Paint as the color we want to use g.setPaint(gp); /* Here we are creating a rectangle and filling it * with our GradientPaint, this will serve as the background to our JPanel */ //g.fillRect(0, 0, Width, Height); g.fillPolygon(new int[]{0,0,Width/10,Width/5,Width/10}, new int[]{0,Height,Height,Height/2,0}, 5); g.fillRoundRect(0, 0, Width, Height, 10, 10); gp = new GradientPaint(0, 0, blue4, Height-Height/10, Height,blue3, false); g.setPaint(gp); g.fillRoundRect(0, Height/2, Width, Height, 0, 10); gp = new GradientPaint(0, 0, blue, Height/2, Height,blue2, true); g.setPaint(gp); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); g.fillPolygon(new int[]{Width,Width,Width-Width/5,Width-Width/10}, new int[]{0,Height,Height,0}, 4); g.setColor(border);//orange //g.setColor(orange);//orange //g.drawRect(0, 0, Width-1, Height-1); g.drawRoundRect(0, 0, Width-1, Height-1, 10, 10); g.setColor(Color.GREEN); return img; } public static void applyShadow(BufferedImage image) { int shadowSize = 5; float shadowOpacity = 0.5f; Color shadowColor = new Color(0x000000); int dstWidth = image.getWidth(); int dstHeight = image.getHeight(); int left = (shadowSize - 1) >> 1; int right = shadowSize - left; int xStart = left; int xStop = dstWidth - right; int yStart = left; int yStop = dstHeight - right; int shadowRgb = shadowColor.getRGB() & 0x00FFFFFF; int[] aHistory = new int[shadowSize]; int historyIdx = 0; int aSum; int[] dataBuffer = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); int lastPixelOffset = right * dstWidth; float sumDivider = shadowOpacity / shadowSize; // horizontal pass for (int y = 0, bufferOffset = 0; y < dstHeight; y++, bufferOffset = y * dstWidth) { aSum = 0; historyIdx = 0; for (int x = 0; x < shadowSize; x++, bufferOffset++) { int a = dataBuffer[bufferOffset] >>> 24; aHistory[x] = a; aSum += a; } bufferOffset -= right; for (int x = xStart; x < xStop; x++, bufferOffset++) { int a = (int) (aSum * sumDivider); dataBuffer[bufferOffset] = a << 24 | shadowRgb; // substract the oldest pixel from the sum aSum -= aHistory[historyIdx]; // get the lastest pixel a = dataBuffer[bufferOffset + right] >>> 24; aHistory[historyIdx] = a; aSum += a; if (++historyIdx >= shadowSize) { historyIdx -= shadowSize; } } } // vertical pass for (int x = 0, bufferOffset = 0; x < dstWidth; x++, bufferOffset = x) { aSum = 0; historyIdx = 0; for (int y = 0; y < shadowSize; y++, bufferOffset += dstWidth) { int a = dataBuffer[bufferOffset] >>> 24; aHistory[y] = a; aSum += a; } bufferOffset -= lastPixelOffset; for (int y = yStart; y < yStop; y++, bufferOffset += dstWidth) { int a = (int) (aSum * sumDivider); dataBuffer[bufferOffset] = a << 24 | shadowRgb; // substract the oldest pixel from the sum aSum -= aHistory[historyIdx]; // get the lastest pixel a = dataBuffer[bufferOffset + lastPixelOffset] >>> 24; aHistory[historyIdx] = a; aSum += a; if (++historyIdx >= shadowSize) { historyIdx -= shadowSize; } } } } /** * * @param imgSize * @param boundary * @return */ public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) { int original_width = imgSize.width; int original_height = imgSize.height; int bound_width = boundary.width; int bound_height = boundary.height; int new_width = original_width; int new_height = original_height; // first check if we need to scale width if (original_width > bound_width) { //scale width to fit new_width = bound_width; //scale height to maintain aspect ratio new_height = (new_width * original_height) / original_width; } // then check if we need to scale even with the new height if (new_height > bound_height) { //scale height to fit instead new_height = bound_height; //scale width to maintain aspect ratio new_width = (new_height * original_width) / original_height; } return new Dimension(new_width, new_height); } /** * we want the x and o to be resized when the JFrame is resized * * @param originalImage an x or an o. Use cross or oh fields. * * @param biggerWidth * @param biggerHeight */ public static BufferedImage scaleImage(BufferedImage originalImage, int biggerWidth, int biggerHeight) { Dimension newDimension= getScaledDimension(new Dimension( originalImage.getWidth(), originalImage.getHeight()), new Dimension(biggerWidth, biggerHeight)); ; biggerWidth=newDimension.width; biggerHeight=newDimension.height; int type = BufferedImage.TYPE_INT_ARGB; BufferedImage resizedImage = new BufferedImage(biggerWidth, biggerHeight, type); Graphics2D g = resizedImage.createGraphics(); g.setComposite(AlphaComposite.Src); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.drawImage(originalImage, 0, 0, biggerWidth, biggerHeight, null); g.dispose(); return resizedImage; } /** * Method to overlay Images * * @param bgImage --> The background Image * @param fgImage --> The foreground Image * @return --> overlayed image (fgImage over bgImage) */ public static BufferedImage overlayImages(BufferedImage bgImage, BufferedImage fgImage) { /** * Doing some preliminary validations. * Foreground image height cannot be greater than background image height. * Foreground image width cannot be greater than background image width. * * returning a null value if such condition exists. */ if (fgImage.getHeight() > bgImage.getHeight() || fgImage.getWidth() > fgImage.getWidth()) { JOptionPane.showMessageDialog(null, "Foreground Image Is Bigger In One or Both Dimensions" + "nCannot proceed with overlay." + "nn Please use smaller Image for foreground"); return null; } /**Create a Graphics from the background image**/ Graphics2D g = bgImage.createGraphics(); /**Set Antialias Rendering**/ g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); /** * Draw background image at location (0,0) * You can change the (x,y) value as required */ g.drawImage(bgImage, 0, 0, null); /** * Draw foreground image at location (0,0) * Change (x,y) value as required. */ g.drawImage(fgImage, 0, 0, null); g.dispose(); return bgImage; } public static BufferedImage particleEffects(int WIDE,int HIGH,float Transparency){ //screen dimensions //particles int MAX_PARTICLES = 50; int MAX_FRAMES = 2; BufferedImage screen = new BufferedImage(WIDE, HIGH, 1); //BufferedImage. int[] pixl = ((DataBufferInt) screen.getRaster().getDataBuffer()).getData(); Graphics2D g = screen.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,Transparency)); g.setColor(new Color(0x00000000)); // Graphics gCanvas = getGraphics(); Random ran = new Random(); //prep particle lightarray //x,y,fade-frames int[][][] particleFrame = new int[10][10][MAX_FRAMES]; for (int i = 0; i < MAX_FRAMES; i++) { for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { double dist = Math.sqrt((x - 5d) * (x - 5d) + (y - 5d) * (y - 5d)); dist = 255 - dist * 60 - i; dist = dist < 0 ? 0 : dist; dist = dist > 255 ? 255 : dist; particleFrame[x][y][i] = (int) dist; } } } int[] particlesFrame = new int[MAX_PARTICLES]; //frame float[][] particlesBase = new float[MAX_PARTICLES][4]; //x,y , velocity x,y for (int i = 0; i < MAX_PARTICLES; i++) { particlesBase[i][0] = ran.nextInt(WIDE);//WIDE/2+ ran.nextInt(WIDE/2) - WIDE/4; particlesBase[i][1] = HIGH/2+ ran.nextInt(HIGH/2)- HIGH/4; particlesBase[i][2] = ran.nextFloat()*2 - 1f; particlesBase[i][3] = ran.nextFloat()*2 - 1f; particlesFrame[i] = ran.nextInt(MAX_FRAMES); } g.fillRect(0, 0, screen.getWidth(), screen.getHeight()); for (int i = 0; i < MAX_PARTICLES; i++) { particlesFrame[i]++; if (particlesFrame[i] >= MAX_FRAMES) particlesFrame[i] = 0; if (particlesBase[i][2] < 0d && particlesBase[i][0] < 10) particlesBase[i][2] = -particlesBase[i][2]; else if (particlesBase[i][2] > 0d && particlesBase[i][0] > WIDE - 15) particlesBase[i][2] = -particlesBase[i][2]; if (particlesBase[i][3] < 0d && particlesBase[i][1] < 10) particlesBase[i][3] = -particlesBase[i][3]; else if (particlesBase[i][3] > 0d && particlesBase[i][1] > HIGH - 15) particlesBase[i][3] = -particlesBase[i][3]; particlesBase[i][0] += particlesBase[i][2]; particlesBase[i][1] += particlesBase[i][3]; int px = (int) particlesBase[i][0]; int py = (int) particlesBase[i][1]; for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { int pc = (pixl[WIDE * (y + py) + x + px]) & 0xFF; pc += particleFrame[x][y][particlesFrame[i]]; pc = pc > 255 ? 255 : pc; int pc2 = (pc > 230) ? pc : 0; pixl[WIDE * (y + py) + x + px] = pc | (pc << 8) | (pc2 << 16); } } } //gCanvas.drawImage(screen, 0, 0, null); return screen; } /** * * @param image * @param Color 0xFF000000 * @return */ public static Image TransformColorToTransparency(BufferedImage image, int Color) { ImageFilter filter = new RGBImageFilter() { @Override public final int filterRGB(int x, int y, int rgb) { return (rgb << 8) & Color; //0xFF000000 } }; ImageProducer ip = new FilteredImageSource(image.getSource(), filter); return Toolkit.getDefaultToolkit().createImage(ip); } /** * Converts a given Image into a BufferedImage * * @param img The Image to be converted * @return The converted BufferedImage */ public static BufferedImage toBufferedImage(Image img) { if (img instanceof BufferedImage) { return (BufferedImage) img; } // Create a buffered image with transparency BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); // Draw the image on to the buffered image Graphics2D bGr = bimage.createGraphics(); bGr.drawImage(img, 0, 0, null); bGr.dispose(); // Return the buffered image return bimage; } }
41.650515
176
0.584515
89e676b0b01413160e7bd0f229a0254890d37241
350
package org.jetlinks.community.gateway.external.socket; import lombok.Getter; import lombok.Setter; import java.util.Map; @Getter @Setter public class MessagingRequest { private String id; private Type type; private String topic; private Map<String,Object> parameter; public enum Type{ pub,sub,unsub,ping } }
14
55
0.708571
09706e7d367515e748da58e02a2ca2b6d1cb7276
818
package com.ttulka.ecommerce.portal; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import static io.restassured.RestAssured.with; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class PortalApplicationTest { @LocalServerPort private int port; @Test void index_works() { with().log().ifValidationFails() .port(port) .basePath("/") .then() .statusCode(200); } @Test void JS_resource_works() { with().log().ifValidationFails() .port(port) .basePath("/js/Application.js") .then() .statusCode(200); } }
24.787879
75
0.610024
e95baeeee583a0c164df8c2bb6d883cdee17c0f4
134
package com.ustc.ruoan.framework.cache.autoconfigure; /** * @author ruoan * @date 2022/5/4 4:12 下午 */ public class HelloWorld { }
14.888889
53
0.69403
c671764bfcd51dddfb18305af9efebed82d0b0c4
469
package com.pigmo.gbms.enums; public enum ResultStatusEnum { SUCCESS("10000","成功"), NOT_FOUND("10001","未找到"), FAILED("10002","失败"), UNKNOWN("10003","未知"); private String code; private String message; ResultStatusEnum(String code, String message) { this.code = code; this.message = message; } public String getCode() { return code; } public String getMessage() { return message; } }
18.038462
51
0.592751
b163b5e204ae3490c7d72b3a372fa14291bb5960
103
package rbl.serial; /** * Created by Peter Mösenthin. */ public class ModuleSessionStateHandler { }
11.444444
38
0.728155
2b00ea72e832b9d27be4e1e8e2eabf3df8f28333
942
package edu.stuy.starlorn.upgrades; import edu.stuy.starlorn.sound.AudioPlayer; public class FocusShotUpgrade extends GunUpgrade { private int _shotNum; public FocusShotUpgrade() { super(); _name = "Crazy Piss"; _description = "Now you can't piss straight!"; _shotNum = 0; try { _voiceLine = new AudioPlayer("/voice/crazypiss.wav", false); }catch (Exception e){ System.out.println("Problem with upgrade voiceline."); System.out.println(e.getMessage()); System.exit(0); } } @Override public int getNumShots(){ return 1; } @Override public double getAimAngle() { int direction = _shotNum; _shotNum++; if (_shotNum > 400) _shotNum = 0; return direction * Math.PI/200; } @Override public String getSpriteName() { return "upgrade/doubleshot"; } @Override public Upgrade clone() { return new FocusShotUpgrade(); } }
20.478261
62
0.642251
d07d2588dafe4c53dd70b6e290b781bafeec4bec
585
package core; import java.awt.*; import entity.Rect; public class CollisionBox { private Rect bounds; public CollisionBox(Rect bounds) { this.bounds = bounds; } public boolean collidesWith(CollisionBox other) { return bounds.overlaps(other.getBounds()); } public Rect getBounds() { return bounds; } public static CollisionBox of(Position position, Size size) { return new CollisionBox( new Rect( (int)position.getX(), (int)position.getY(), size.getWidth(), size.getHeight() ) ); } }
17.205882
62
0.622222
398d79ae84404e0c80cd977cdfe4788fdcdc2fbe
3,587
package net.sourceforge.retroweaver.runtime.java.util; import java.util.Locale; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.io.IOException; public class Formatter { public Formatter() { this(new StringBuilder(), Locale.getDefault()); } public Formatter(Appendable a) { this(a, Locale.getDefault()); } public Formatter(Locale l) { this(new StringBuilder(), l); } public Formatter(Appendable a, Locale l) { buffer = a == null?new StringBuilder():a; try { appendMethod = buffer.getClass().getMethod("append", new Class[] { String.class }); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } locale = l; } private Appendable buffer; private Method appendMethod; private Locale locale; private boolean closed; private IOException ioe; public Locale locale() { if (closed) { throw new FormatterClosedException(); } return locale; } public Appendable out() { if (closed) { throw new FormatterClosedException(); } return buffer; } public String toString() { if (closed) { throw new FormatterClosedException(); } return buffer.toString(); } public void flush() { if (closed) { throw new FormatterClosedException(); } // Flushable is 1.5+ try { Method m = buffer.getClass().getMethod("flush", new Class<?>[0]); m.invoke(buffer, new Object[0]); } catch (Exception e) { // ignored; } } public void close() { if (!closed) { closed = true; // Closeable is 1.5+ try { Method m = buffer.getClass().getMethod("close", new Class<?>[0]); m.invoke(buffer, new Object[0]); } catch (Exception e) { // ignored; } } } public IOException ioException() { return ioe; } public Formatter format(String format, Object... args) throws IllegalFormatException, FormatterClosedException { return format(locale, format, args); } public Formatter format(Locale l, String format, Object... args) throws IllegalFormatException, FormatterClosedException { if (closed) { throw new FormatterClosedException(); } //System.err.println("Format: " + format + ' ' + args.length); //for (Object a: args) System.err.println("\t" + a.getClass() + ": " + a); int start = 0; int end; int argIndex = 0; while (true) { try { end = format.indexOf('%', start); if (end == -1) { append(format.substring(start, format.length())); break; } append(format.substring(start, end)); if (end == format.length()) { throw new IllegalFormatException(); } char c = format.charAt(end+1); Object o = args[argIndex++]; switch (c) { case '%': append("%"); break; case 's': append(o==null?null:o.toString()); break; case 'd': append(o.toString()); break; default: throw new IllegalFormatException(); } start = end + 2; } catch (IOException ioe) { this.ioe = ioe; } } return this; } private void append(String s) throws IOException { try { appendMethod.invoke(buffer, s); } catch (InvocationTargetException ite) { if (ite.getCause() instanceof IOException) { throw (IOException) ite.getCause(); } } catch (Exception e) { throw new RuntimeException(e); } } }
23.141935
124
0.587957
bbdbeb216b43fce6378f7ec45c34e27006210ffc
2,361
package de.uni_hildesheim.sse.functions; import java.text.DecimalFormat; /** * Defines an {@link IFunction} which stores the avg of a given attribute. * * @author Stephan Dederichs * * @since 1.00 * @version 1.00 */ public class AvgFunction implements IFunction { /** * Stores the {@link IIdentity} of the class to watch. * * @since 1.00 */ private IIdentity identity; /** * Stores the avg value. * * @since 1.00 */ private Double avg = Double.MAX_VALUE; /** * Stores the type of the function. This will be displayed if the function * is used. */ private String functionType = "avg"; /** * Stores a count for calculating the avg. * * @since 1.00 */ private int count = 0; /** * Public default Constructor. * * @since 1.00 */ public AvgFunction() { } /** * Constructor. * * @param identity * The {@link IIdentity} of the function. */ public AvgFunction(IIdentity identity) { this.identity = identity; } @Override public String getFunctionType() { return functionType; } @Override public void setFunctionType(String functionType) { this.functionType = functionType; } @Override public IIdentity getIdentity() { return identity; } @Override public void setIdentity(IIdentity identity) { this.identity = identity; } @Override public Object getValue() { DecimalFormat df = new DecimalFormat("0.00"); return df.format(avg); } @Override public void calculate() { Double act = avg; // getting the actual attribute value act = Double.valueOf(identity.getCls() .getSpecificAttribute(identity.getAttributeName()).toString()); // calculating the new value if (count == 0) { // If there is no avg yet avg = act; } else { avg = ((count * avg) + act) / (count + 1); } count++; } @Override public String toString() { return "Functiontype: " + functionType + " " + identity; } }
21.27027
80
0.531131
20835823e4618282cb84471ee924f3e10f68bc5c
1,105
package com.chaoppo.db.storm.test.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class HashcodeTester { /** * Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode * method must consistently return the same integer */ public static void testHashCodeConsistency(Object o1) { assertEquals("object hashcode consistency with itself failed! Weird. ", o1.hashCode(), o1.hashCode()); } /** * if o1 is equals to o2, then o1.hashcode should be equals to o2.hashcode * * @param o1 * @param o2 */ public static void testHashCodeEquality(Object o1, Object o2) { if (o1.equals(o2)) { assertEquals("if o1 and o2 are equals, then they should have the same hashcode!", o1.hashCode(), o2.hashCode()); } else { assertNotEquals("if o1 and o2 are not equals, then they should not have the same hashcode!", o1.hashCode(), o2.hashCode()); } } }
34.53125
119
0.640724
5e00de1d015917013459cc5448e5c2976d4208cf
4,067
/* * Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved. * <p> * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.gateway.evaluators.xpathevaluator; import net.sf.saxon.s9api.DocumentBuilder; import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.SaxonApiException; import net.sf.saxon.s9api.XPathCompiler; import net.sf.saxon.s9api.XPathSelector; import net.sf.saxon.s9api.XdmNode; import org.wso2.carbon.gateway.core.flow.contentaware.MIMEType; import org.wso2.carbon.gateway.core.flow.contentaware.abstractcontext.MessageBodyEvaluator; import org.wso2.carbon.gateway.core.flow.contentaware.exceptions.MessageBodyEvaluationException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import javax.xml.transform.stream.StreamSource; /** * This class can be used to evaluate an XML message against a given XPath expression. * This implements, * @see org.wso2.carbon.gateway.core.flow.contentaware.abstractcontext.MessageBodyEvaluator * which contains the method definitions for the functionality expected from a class that supports * evaluating a message body */ public class XPathEvaluator implements MessageBodyEvaluator { // An XPathCompiler object allows XPath queries to be compiled. private XPathCompiler xPathCompiler; // The Processor acts as a factory for generating XQuery, XPath, and XSLT compilers; // Once established, a Processor may be used in multiple threads. private Processor processor; public XPathEvaluator() { // The boolean argument indicates whether this is the licensed edition or not. processor = new Processor(false); xPathCompiler = processor.newXPathCompiler(); } /** * This evaluates an XML message against a provided XPath expression. * * @param inputStream input stream to be evaluated * @param xpathExpression XPath expression to evaluate the OMElement against * @return The resulting value * @throws MessageBodyEvaluationException */ @Override public Object evaluate(InputStream inputStream, String xpathExpression) throws MessageBodyEvaluationException { try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); DocumentBuilder builder = processor.newDocumentBuilder(); XdmNode doc = builder.build(new StreamSource(inputStreamReader)); XPathSelector selector = xPathCompiler.compile(xpathExpression).load(); selector.setContextItem(doc); return selector.evaluate(); } catch (SaxonApiException e) { throw new MessageBodyEvaluationException("There is a problem evaluating the XPath", e); } } /** * Returns the path language of this evaluator. * * @return enum for XPATH */ @Override public String getPathLanguage() { return "xpath"; } /** * Returns a boolean depending on whether the provided mime type is supported in this Path Evaluator * * @param mimeType The mime type that need to be checked if it is supported * @return Whether the mime type is supported */ @Override public Boolean isContentTypeSupported(String mimeType) { switch (mimeType) { case MIMEType.XML: return true; case MIMEType.TEXT_XML: return true; default: return false; } } }
38.009346
115
0.71822
84b291e20152720708c5832232174e1be1dce068
17,038
package io.advantageous.qbit.meta.builder; import io.advantageous.boon.core.TypeType; import io.advantageous.boon.core.reflection.MethodAccess; import io.advantageous.qbit.http.request.HttpBinaryResponse; import io.advantageous.qbit.http.request.HttpTextResponse; import io.advantageous.qbit.jsend.JSendResponse; import io.advantageous.qbit.meta.GenericReturnType; import io.advantageous.qbit.meta.RequestMeta; import io.advantageous.qbit.meta.ServiceMethodMeta; import io.advantageous.qbit.reactive.Callback; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.*; @SuppressWarnings("UnusedReturnValue") public class ServiceMethodMetaBuilder { private List<RequestMeta> requestEndpoints = new ArrayList<>(); private MethodAccess methodAccess; private String name; private String address; private TypeType returnTypeEnum; private List<TypeType> paramTypes; private boolean hasCallBack; private GenericReturnType genericReturnType = GenericReturnType.NONE; private Class<?> returnType; private Class<?> returnTypeComponent; private Class<?> returnTypeComponentKey; private Class<?> returnTypeComponentValue; private boolean hasReturn; private String description; private String summary; private String returnDescription; private int responseCode; private String contentType; public String getDescription() { return description; } public ServiceMethodMetaBuilder setDescription(String description) { this.description = description; return this; } public static ServiceMethodMetaBuilder serviceMethodMetaBuilder() { return new ServiceMethodMetaBuilder(); } public String getAddress() { return address; } public ServiceMethodMetaBuilder setAddress(String address) { this.address = address; return this; } public List<RequestMeta> getRequestEndpoints() { return requestEndpoints; } public ServiceMethodMetaBuilder setRequestEndpoints(List<RequestMeta> requestEndpoints) { this.requestEndpoints = requestEndpoints; return this; } public ServiceMethodMetaBuilder addRequestEndpoint(RequestMeta requestEndpoint) { this.requestEndpoints.add(requestEndpoint); return this; } public ServiceMethodMetaBuilder addRequestEndpoint(RequestMeta... requestEndpointArray) { Collections.addAll(this.requestEndpoints, requestEndpointArray); return this; } public MethodAccess getMethodAccess() { return methodAccess; } public ServiceMethodMetaBuilder setMethodAccess(MethodAccess methodAccess) { this.methodAccess = methodAccess; return this; } public String getName() { if (name == null) { if (methodAccess!=null) { name = methodAccess.name(); } } return name; } public ServiceMethodMetaBuilder setName(String name) { this.name = name; return this; } public TypeType getReturnTypeEnum() { return returnTypeEnum; } public ServiceMethodMetaBuilder setReturnTypeEnum(TypeType returnTypeEnum) { this.returnTypeEnum = returnTypeEnum; return this; } public List<TypeType> getParamTypes() { return paramTypes; } public ServiceMethodMetaBuilder setParamTypes(List<TypeType> paramTypes) { this.paramTypes = paramTypes; return this; } public ServiceMethodMeta build() { if (methodAccess != null) { setHasCallBack(detectCallback()); deduceReturnTypes(); return new ServiceMethodMeta(isHasReturn(), getMethodAccess(), getName(), getRequestEndpoints(), getReturnTypeEnum(), getParamTypes(), hasCallback(), getGenericReturnType(), getReturnType(), getReturnTypeComponent(), getReturnTypeComponentKey(), getReturnTypeComponentValue(), getDescription(), getSummary(), getReturnDescription(), getResponseCode(), getContentType()); } else { return new ServiceMethodMeta(getName(), this.getRequestEndpoints(), this.getReturnTypeEnum(), this.getParamTypes()); } } private void deduceReturnTypes() { if (hasCallback()) { deduceReturnInfoFromCallbackArg(); } else { returnType = methodAccess.returnType(); returnTypeEnum = TypeType.getType(returnType); if (Collection.class.isAssignableFrom(returnType)) { genericReturnType = GenericReturnType.COLLECTION; ParameterizedType genericReturnType = (ParameterizedType) methodAccess.method().getGenericReturnType(); this.returnTypeComponent = (Class) genericReturnType.getActualTypeArguments()[0]; } else if (Map.class.isAssignableFrom(returnType)) { genericReturnType = GenericReturnType.MAP; ParameterizedType genericReturnType = (ParameterizedType) methodAccess.method().getGenericReturnType(); this.returnTypeComponentKey = (Class) genericReturnType.getActualTypeArguments()[0]; this.returnTypeComponentValue = (Class) genericReturnType.getActualTypeArguments()[1]; } else if (Optional.class.isAssignableFrom(returnType)) { genericReturnType = GenericReturnType.OPTIONAL; ParameterizedType genericReturnType = (ParameterizedType) methodAccess.method().getGenericReturnType(); this.returnTypeComponent = (Class) genericReturnType.getActualTypeArguments()[0]; } else if (JSendResponse.class.isAssignableFrom(returnType)) { genericReturnType = GenericReturnType.JSEND; ParameterizedType genericReturnType = (ParameterizedType) methodAccess.method().getGenericReturnType(); final Type type = genericReturnType.getActualTypeArguments()[0]; if (type instanceof Class) { this.returnTypeComponent = (Class) type; this.genericReturnType = GenericReturnType.JSEND; } else if (type instanceof ParameterizedType) { final ParameterizedType jsendGenericReturnType = ((ParameterizedType) type); if (jsendGenericReturnType.getRawType() instanceof Class) { final Class rawType = (Class) jsendGenericReturnType.getRawType(); if (Collection.class.isAssignableFrom(rawType) || rawType.isArray()) { this.genericReturnType = GenericReturnType.JSEND_ARRAY; Type componentType = jsendGenericReturnType.getActualTypeArguments()[0]; if (componentType instanceof Class) { this.returnTypeComponent = ((Class) componentType); } } else if (Map.class.isAssignableFrom(rawType)) { this.genericReturnType = GenericReturnType.JSEND_MAP; Type componentKey = jsendGenericReturnType.getActualTypeArguments()[0]; if (componentKey instanceof Class) { this.returnTypeComponentKey = ((Class) componentKey); } this.genericReturnType = GenericReturnType.JSEND_MAP; Type componentValue = jsendGenericReturnType.getActualTypeArguments()[0]; if (componentValue instanceof Class) { this.returnTypeComponentValue = ((Class) componentValue); } } } } } else if (returnType == HttpTextResponse.class) { genericReturnType = GenericReturnType.HTTP_TEXT_RESPONSE; } else if (returnType == HttpBinaryResponse.class) { genericReturnType = GenericReturnType.HTTP_BINARY_RESPONSE; } else { if (returnType.isArray()) { genericReturnType = GenericReturnType.ARRAY; this.returnTypeComponent = returnType.getComponentType(); } } } if (returnType!= void.class && returnType !=Void.class) { hasReturn = true; } } private void deduceReturnInfoFromCallbackArg() { Type[] genericParameterTypes = methodAccess.method().getGenericParameterTypes(); Type callback = genericParameterTypes[0]; if (callback instanceof ParameterizedType) { Type callbackReturn = ((ParameterizedType) callback).getActualTypeArguments()[0]; /* Now we know it is a map or list */ if (callbackReturn instanceof ParameterizedType) { final Class containerType = (Class)((ParameterizedType) callbackReturn).getRawType(); this.returnTypeEnum = TypeType.getType(containerType); this.returnType = containerType; if (Collection.class.isAssignableFrom(containerType)) { this.genericReturnType = GenericReturnType.COLLECTION; this.returnTypeComponent =(Class) ((ParameterizedType) callbackReturn).getActualTypeArguments()[0]; } else if (Map.class.isAssignableFrom(containerType)) { this.genericReturnType = GenericReturnType.MAP; this.returnTypeComponentKey =(Class)((ParameterizedType) callbackReturn).getActualTypeArguments()[0]; this.returnTypeComponentValue =(Class)((ParameterizedType) callbackReturn).getActualTypeArguments()[1]; } else if (Optional.class.isAssignableFrom(containerType)) { this.genericReturnType = GenericReturnType.OPTIONAL; this.returnTypeComponent =(Class) ((ParameterizedType) callbackReturn).getActualTypeArguments()[0]; } else if (JSendResponse.class.isAssignableFrom(containerType)) { final Type returnTypeForComponent = ((ParameterizedType) callbackReturn).getActualTypeArguments()[0]; if (returnTypeForComponent instanceof Class) { this.returnTypeComponent = (Class) returnTypeForComponent; this.genericReturnType = GenericReturnType.JSEND; } else if (returnTypeForComponent instanceof ParameterizedType){ final ParameterizedType jsendGenericReturnType = ((ParameterizedType) returnTypeForComponent); if (jsendGenericReturnType.getRawType() instanceof Class) { final Class rawType = (Class) jsendGenericReturnType.getRawType(); if (Collection.class.isAssignableFrom(rawType) || rawType.isArray()) { this.genericReturnType = GenericReturnType.JSEND_ARRAY; Type componentType = jsendGenericReturnType.getActualTypeArguments()[0]; if (componentType instanceof Class) { this.returnTypeComponent = ((Class) componentType); } } else if (Map.class.isAssignableFrom(rawType)) { this.genericReturnType = GenericReturnType.JSEND_MAP; Type componentKey = jsendGenericReturnType.getActualTypeArguments()[0]; if (componentKey instanceof Class) { this.returnTypeComponentKey = ((Class) componentKey); } this.genericReturnType = GenericReturnType.JSEND_MAP; Type componentValue = jsendGenericReturnType.getActualTypeArguments()[0]; if (componentValue instanceof Class) { this.returnTypeComponentValue = ((Class) componentValue); } } } } } }/* Now we know it is not a list or map */ else if (callbackReturn instanceof Class) { this.returnType = ((Class) callbackReturn); if (this.returnType == HttpTextResponse.class) { this.genericReturnType = GenericReturnType.HTTP_TEXT_RESPONSE; } else if (this.returnType == HttpBinaryResponse.class) { this.genericReturnType = GenericReturnType.HTTP_BINARY_RESPONSE; } else if (returnType.isArray()) { this.genericReturnType = GenericReturnType.ARRAY; } this.returnTypeEnum = TypeType.getType(returnType); } } } private boolean detectCallback() { boolean hasCallback = false; Class<?>[] classes = methodAccess.parameterTypes(); if (classes.length > 0) { if (classes[0] == Callback.class) { hasCallback = true; } } return hasCallback; } public ServiceMethodMetaBuilder setHasCallBack(boolean hasCallBack) { this.hasCallBack = hasCallBack; return this; } public boolean isHasCallBack() { return hasCallBack; } public boolean hasCallback() { return hasCallBack; } public boolean isReturnCollection() { return genericReturnType == GenericReturnType.COLLECTION; } public ServiceMethodMetaBuilder setReturnCollection(boolean returnCollection) { this.genericReturnType = GenericReturnType.COLLECTION; return this; } public boolean isReturnMap() { return genericReturnType == GenericReturnType.MAP; } public ServiceMethodMetaBuilder setReturnMap(boolean returnMap) { this.genericReturnType = GenericReturnType.MAP; return this; } public boolean isReturnArray() { return genericReturnType == GenericReturnType.ARRAY; } public ServiceMethodMetaBuilder setReturnArray(boolean returnArray) { this.genericReturnType = GenericReturnType.ARRAY; return this; } public Class<?> getReturnType() { return returnType; } public ServiceMethodMetaBuilder setReturnType(Class<?> returnType) { this.returnType = returnType; return this; } public Class<?> getReturnTypeComponent() { return returnTypeComponent; } public ServiceMethodMetaBuilder setReturnTypeComponent(Class<?> returnTypeComponent) { this.returnTypeComponent = returnTypeComponent; return this; } public Class<?> getReturnTypeComponentKey() { return returnTypeComponentKey; } public ServiceMethodMetaBuilder setReturnTypeComponentKey(Class<?> returnTypeComponentKey) { this.returnTypeComponentKey = returnTypeComponentKey; return this; } public Class<?> getReturnTypeComponentValue() { return returnTypeComponentValue; } public ServiceMethodMetaBuilder setReturnTypeComponentValue(Class<?> returnTypeComponentValue) { this.returnTypeComponentValue = returnTypeComponentValue; return this; } public boolean isHasReturn() { return hasReturn; } public ServiceMethodMetaBuilder setHasReturn(boolean hasReturn) { this.hasReturn = hasReturn; return this; } public ServiceMethodMetaBuilder setSummary(String summary) { this.summary = summary; return this; } public String getSummary() { return summary; } public ServiceMethodMetaBuilder setReturnDescription(String returnDescription) { this.returnDescription = returnDescription; return this; } public String getReturnDescription() { return returnDescription; } public GenericReturnType getGenericReturnType() { return genericReturnType; } public ServiceMethodMetaBuilder setGenericReturnType(GenericReturnType genericReturnType) { this.genericReturnType = genericReturnType; return this; } public ServiceMethodMetaBuilder setResponseCode(int responseCode) { this.responseCode = responseCode; return this; } public int getResponseCode() { return responseCode; } public String getContentType() { return contentType; } public ServiceMethodMetaBuilder setContentType(String contentType) { this.contentType = contentType; return this; } }
37.03913
123
0.624663
67058587a7572fbbf57f0198388378e4634640fe
2,449
/* * Copyright 2018 Tallence AG * * 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.tallence.formeditor.cae.mocks; import com.tallence.formeditor.cae.actions.FormEditorMailAdapter; import com.tallence.formeditor.cae.elements.FormElement; import com.tallence.formeditor.contentbeans.FormEditor; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import java.util.List; /** * Mocking the {@link FormEditorMailAdapter} and storing the params in local variables, * which can be checked by tests afterwards. * */ @Component @Primary public class MailAdapterMock implements FormEditorMailAdapter { public String usersFormData; public String usersRecipient; public String adminFormData; public String adminRecipient; @Override public boolean sendAdminMail(FormEditor target, String recipient, String formData, List<FormElement> elements) { if (this.adminFormData != null || this.adminRecipient != null) { throw new IllegalStateException("Call com.tallence.formeditor.cae.mocks.MailAdapterMock.clear before setting adminFormData or adminRecipient again"); } this.adminFormData = formData; this.adminRecipient = recipient; return true; } @Override public boolean sendUserMail(FormEditor target, String recipient, String formData, List<FormElement> elements, List<MultipartFile> files) { if (this.usersFormData != null || this.usersRecipient != null) { throw new IllegalStateException("Call com.tallence.formeditor.cae.mocks.MailAdapterMock.clear before setting usersFormData or usersRecipient again"); } this.usersFormData = formData; this.usersRecipient = recipient; return true; } public void clear() { this.usersFormData = null; this.usersRecipient = null; this.adminFormData = null; this.adminRecipient = null; } }
34.013889
155
0.761944
4398a5c847f37ab19b2016883356d466e69391ab
1,532
package br.com.ibnetwork.guara.app.modules; import br.com.ibnetwork.guara.bean.BeanUtils; import br.com.ibnetwork.guara.metadata.BeanInfo; import xingu.container.Inject; import xingu.factory.Factory; import xingu.store.PersistentBean; import xingu.validator.ValidatorContext; public class Result { @Inject private Factory factory; private PersistentBean bean; private ValidatorContext ctx; private BeanInfo beanInfo; private int index = -1; private String prefix; public PersistentBean getBean() { return bean; } public void setBean(PersistentBean bean) { this.bean = bean; } public ValidatorContext getValidatorContext() { return ctx; } public void setValidatorContext(ValidatorContext ctx) { this.ctx = ctx; } public String getBeanName() throws Exception { return BeanUtils.getBeanName(bean); } public BeanInfo getBeanInfo() { if(beanInfo == null) { beanInfo = (BeanInfo) factory.create(BeanInfo.class, new Object[]{bean}, new String[]{Object.class.getName()}); } return beanInfo; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public String getPrefix() throws Exception { if(prefix != null) { return prefix; } if(bean instanceof Prefixable) { prefix = ((Prefixable)bean).getPrefix(); } if(prefix == null) { prefix = getBeanName(); } return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } }
16.473118
115
0.686031
d2a6e0215429ecd96ab90ec21ceab848159a3d64
1,101
/** Copyright by Barry G. Becker, 2000-2011. Licensed under MIT License: http://www.opensource.org/licenses/MIT */ package com.barrybecker4.game.twoplayer.tictactoe; import com.barrybecker4.game.common.player.PlayerList; import com.barrybecker4.game.twoplayer.gomoku.GoMokuSearchable; import com.barrybecker4.game.twoplayer.gomoku.pattern.Patterns; /** * Defines everything the computer needs to know to play TicTacToe. * * @author Barry Becker */ public class TicTacToeSearchable extends GoMokuSearchable<TicTacToeBoard> { /** * Constructor */ public TicTacToeSearchable(TicTacToeBoard board, PlayerList players) { super(board, players); } public TicTacToeSearchable(TicTacToeSearchable searchable) { super(searchable); } @Override protected Patterns createPatterns() { return new TicTacToePatterns(); } @Override public TicTacToeSearchable copy() { return new TicTacToeSearchable(this); } @Override protected int getJeopardyWeight() { return TicTacToeWeights.JEOPARDY_WEIGHT; } }
26.853659
115
0.718438
45bb68621b421dcbf495ff0a9a4d69adffe3c42a
1,317
package io.opentelemetry.auto.instrumentation.trace_annotation; import static io.opentelemetry.auto.instrumentation.trace_annotation.TraceDecorator.DECORATE; import static io.opentelemetry.auto.instrumentation.trace_annotation.TraceDecorator.TRACER; import io.opentelemetry.auto.instrumentation.api.MoreTags; import io.opentelemetry.auto.instrumentation.api.SpanWithScope; import io.opentelemetry.trace.Span; import java.lang.reflect.Method; import net.bytebuddy.asm.Advice; public class TraceAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) public static SpanWithScope onEnter(@Advice.Origin final Method method) { final Span span = TRACER.spanBuilder("trace.annotation").startSpan(); final String resourceName = DECORATE.spanNameForMethod(method); span.setAttribute(MoreTags.RESOURCE_NAME, resourceName); DECORATE.afterStart(span); return new SpanWithScope(span, TRACER.withSpan(span)); } @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class) public static void stopSpan( @Advice.Enter final SpanWithScope spanWithScope, @Advice.Thrown final Throwable throwable) { final Span span = spanWithScope.getSpan(); DECORATE.onError(span, throwable); DECORATE.beforeFinish(span); span.end(); spanWithScope.closeScope(); } }
39.909091
98
0.791192
2ab5fec8c5cced4be417d459b493189a6527fdbb
3,198
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.fxb.jeesite.modules.oa.service; import com.fxb.jeesite.common.persistence.Page; import com.fxb.jeesite.common.service.CrudService; import com.fxb.jeesite.modules.oa.dao.UserInfoDao; import com.fxb.jeesite.modules.oa.entity.GradeSeach; import com.fxb.jeesite.modules.oa.entity.UserInfo; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; /** * 单表生成Service * * @author fxb * @version 2017-07-24 */ @Service @Transactional(readOnly = true) public class UserInfoService extends CrudService<UserInfoDao, UserInfo> { public UserInfo get(String id) { return super.get(id); } public List<UserInfo> findList(UserInfo userInfo) { return super.findList(userInfo); } public Page<UserInfo> findPage(Page<UserInfo> page, UserInfo userInfo) { return super.findPage(page, userInfo); } @Transactional(readOnly = false) public void save(UserInfo userInfo) { super.save(userInfo); } @Transactional(readOnly = false) public void delete(String[] ids) { for (String id : ids) { if(null!=id) { UserInfo userInfo = new UserInfo(); userInfo.setId(id); super.delete(userInfo); } } } @Transactional public void restore(String[] ids, int flag) { for (String i : ids) { UserInfo user = new UserInfo(); user.setId(i); user.setFlag(flag + ""); super.restore(user); } } @Transactional public List<GradeSeach> gradeSeach(GradeSeach gradeSeach) { List<GradeSeach> gradeDatas = new ArrayList<GradeSeach>(); List<Object> grades = this.dao.findDistrictGrade(); for (Object obj : grades) { if(null != obj){ int grade = (Integer)obj; GradeSeach gs = new GradeSeach(); gs.setGrade(grade); int rowCounts = this.dao.getRowCounts(gs); gs.setPeopleCount(rowCounts); int carCounts = this.dao.getCardCounts(gs); gs.setCardCount(carCounts); gradeDatas.add(gs); } } return gradeDatas; } @Transactional public String batchSave(List<UserInfo> userInfos) { StringBuilder msg = new StringBuilder("导入信息:"); int count = 0; int errorCount = 0; for (UserInfo userInfo : userInfos) { try { super.save(userInfo); count++; } catch (Exception e) { if(errorCount<10) { msg.append(userInfo.getXykid() + ","); }else if(errorCount==10){ msg.append(userInfo.getXykid() + "等,"); } errorCount++; continue; } } msg.append("共计"+errorCount + "条信息导入失败," + errorCount + "条信息导入成功"); return msg.toString(); } }
29.88785
108
0.578799
89c12511731d5c80c88bf24a7a4c0482396cbac4
1,902
package de.bitnoise.sonferenz.service.v2.services.impl; import static org.fest.assertions.Assertions.assertThat; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Mockito.*; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.internal.verification.NoMoreInteractions; import de.bitnoise.sonferenz.model.ConferenceModel; import de.bitnoise.sonferenz.repo.ConferenceRepository; import de.bitnoise.sonferenz.service.v2.BaseTestClass; import de.bitnoise.sonferenz.service.v2.exceptions.GeneralConferenceException; import de.bitnoise.sonferenz.service.v2.services.impl.ConferenceService2Impl; public class ConferenceFacadeImplTest extends BaseTestClass { ConferenceRepository conferenceRepoMock = mock(ConferenceRepository.class); ConferenceService2Impl sut = new ConferenceService2Impl() { { conferenceRepo = conferenceRepoMock; } }; ConferenceModel _current = new ConferenceModel(); @Test public void testGetActiveConference_One() { // prepare when(conferenceRepoMock.findByActive(anyBoolean())).thenReturn(_current); // execute ConferenceModel active = sut.getActiveConference2(); // verify assertThat(active).isEqualTo(_current); } @Test public void testGetActiveConference_None() { // prepare when(conferenceRepoMock.findByActive(anyBoolean())).thenReturn(null); // execute ConferenceModel active = sut.getActiveConference2(); // verify assertThat(active).isNull(); } @Test @SuppressWarnings("unchecked") public void testGetActiveConference_Fail() { // prepare when(conferenceRepoMock.findByActive(anyBoolean())) .thenThrow(RuntimeException.class); // expect a exception expectException.expect(GeneralConferenceException.class); // execute sut.getActiveConference2(); } }
26.416667
78
0.760778