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
b3e9aa9751253d2d922ddb502ad149339c1ac8ed
1,006
package fi.aalto.cs.apluscourses.intellij.utils; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * A class that makes it easy to use projects as keys in maps. The equals and hashCode methods are * based on the project base path. No reference to the project is stored, only a string containing * the path. */ public class ProjectKey { @NotNull private final String projectPath; /** * Construct an instance with the given project. */ public ProjectKey(@Nullable Project project) { if (project == null || project.isDefault()) { this.projectPath = ""; } else { this.projectPath = project.getBasePath(); } } @Override public boolean equals(Object other) { if (!(other instanceof ProjectKey)) { return false; } return projectPath.equals(((ProjectKey) other).projectPath); } @Override public int hashCode() { return projectPath.hashCode(); } }
25.15
98
0.696819
fd34a61639dd9d71603784a8d65c90f384341d25
428
package net.pladema.establishment.controller.dto; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.io.Serializable; @Getter @Setter @ToString public class InstitutionDto implements Serializable { private static final long serialVersionUID = -6806500543924261426L; private Integer id; private String name; private String website; private InstitutionAddressDto institutionAddressDto; }
17.833333
68
0.817757
a762d12b5dfc9b8403b62aec310b9618fbcbe4e5
1,107
package mylab.puzzles; import java.io.BufferedReader; import java.io.FileReader; import java.util.*; /** * Created with IntelliJ IDEA. * User: iguana * Date: 21/9/14 * Time: 11:28 PM * * Rules : * 1. Each unique account + security identifier combination creates one aggregated position. * 2. The position quantity will be incremented when a trade has following attributes : * a) direction = BUY, operation = NEW or AMEND * b) direction = SELL, operation = CANCEL * * 3. The position quantity will be decremented when a trade has following attributes : * a) direction = SELL, operation = NEW or AMEND * b) direction = BUY, operation = CANCEL * * 4. Multiple versions of a trade with the same trade ID can be processed, however * the trade highest version transaction should remain part of the aggregated position * record. */ public class TradeCruncher { public static void main(String args[]) throws Exception { TradeProcessor processor = new TradeProcessor(); processor.processTransactions("trade_input.txt","trade_output.txt"); } }
31.628571
92
0.70551
1906f04ca3f3bd76938216d28737a7f56e573474
2,885
package edu.yctc.face.function; import java.io.IOException; import edu.yctc.project.system.infost.domain.Infost; /** * 人脸识别相关功能接口 * * @author xiaotao */ public interface FaceFunction { /** * 功能:填写数据库tb_user表的face_token<br> * 1)通过UserDO得到picture<br> * 2)识别picture(通过face++)得到face_token<br> * 3)把face_token保存到tb_user表的face_token<br> * 4)把face_token保存到face++平台的faceset * * @param infost 档案 */ public void alterFaceToken(Infost infost); /** * 功能:处理视频 标记出视频中的人的脸部位置 重新生成视频给前端显示<br> * 1)把一段视频截成图片<br> * 2)处理其中的若干图片标记出视频中的人的脸部位置<br> * 3)把图片合成视频<br> * 注:解析视频开始时间和解析视频结束时间要和生成的视频时长对应 * * @param videoPath 视频文件地址 * @param savePath 处理好的视频保存地址 * @param startTime 解析视频开始时间(默认00:00) * @param endTime 解析视频结束时间(默认00:10) * @param totalTime 生成的视频时长(默认10秒) * @param frame 生成的视频的帧率(默认10帧/秒) * @param resolutionRatio 生成的视频的分辨率(默认为1280*720) */ public void dealMedia(String videoPath, String savePath, String startTime, String endTime, String totalTime, String frame, String resolutionRatio); /** * 控制摄像头的活动 * * @param command 控制摄像头的命令 */ public void cameraControl(String command); /** * 识别图片中的文字 * * @param imgPath 图片路径(jpg格式) * @return */ public String ocrControl(String imgPath); /** * 功能:考勤 判断学生签到情况 把学生的签到情况记录到数据库sys_attendance表<br> * 1)课程id--所有学生<br> * 2)课程id-- 教室DO--equipmentId--视频地址<br> * 3)从视频中抽取几张图片进行人脸识别<br> * 4)把 签到的 且在先前得到的所有学生数组里面的学生 的考勤信息更新 即更新数据库sys_attendance表的attendState * * @param lessonId 课程id */ public void checkByLessonId(Long lessonId, String image) throws IOException; /** * 功能:学生检测状态 判断学生的上课状态 把学生的状态记录到数据库中的sys_student_state表的state<br> * 1)课程id--所有学生<br> * 2)课程id-- 教室DO--equipmentId--视频地址<br> * 3)从视频中抽取几张图片进行抠图(把图片中的背景去掉 把图片中的人单独截图出来)<br> * 4)把截出来的图片用python模型进行状态检测<br> * 5)更新数据库对应学生的对应时间段的听课状态 * * @param lessonId 课程Id */ public void checkStatusByLessonId(String lessonId) throws IOException; /** * 功能:学生检测状态 判断学生的上课状态 把学生的状态记录到数据库中的sys_knowledge_student_state表的state<br> * 1)课程id--所有学生<br> * 2)课程id-- 教室DO--equipmentId--视频地址<br> * 3)从视频中抽取几张图片进行抠图(把图片中的背景去掉 把图片中的人单独截图出来)<br> * 4)把截出来的图片用python模型进行状态检测<br> * 5)更新数据库对应学生的对应时间段的听课状态 * * @param lessonId 课程Id * @param knowledge 上课对应的知识点 */ public void checkStatusByLessonId(String lessonId, long knowledge) throws IOException; /** * 功能:检测此时上课所放的PPT是否存在该知识点 <br> * 1)得到视频拍摄PPT图片 <br> * 2)OCR检测图片中的文字 <br> * 3)检测图片中是否包含知识点 <br> * 4)如果包含知识点,返回true <br> * 5)如果不包含知识点,返回false <br> * * @param knowledge * @return */ public boolean checkKnowledge(String knowledge, String image) throws IOException; }
26.46789
112
0.651646
c74e8ab84f28565441221103516a25bef4daa250
4,229
package com.smartdevicelink.test.streaming; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.List; import junit.framework.TestCase; import com.smartdevicelink.SdlConnection.ISdlConnectionListener; import com.smartdevicelink.SdlConnection.SdlSession; import com.smartdevicelink.protocol.ProtocolMessage; import com.smartdevicelink.protocol.enums.SessionType; import com.smartdevicelink.proxy.RPCRequest; import com.smartdevicelink.streaming.AbstractPacketizer; import com.smartdevicelink.streaming.IStreamListener; import com.smartdevicelink.test.Test; import com.smartdevicelink.transport.BTTransportConfig; import com.smartdevicelink.transport.BaseTransportConfig; /** * This is a unit test class for the SmartDeviceLink library project class : * {@link com.smartdevicelink.streaming.AbstractPacketizer} */ public class AbstractPacketizerTests extends TestCase { /** * This is a unit test for the following methods : * {@link com.smartdevicelink.streaming.AbstractPacketizer#AbstractPacketizer(IStreamListener, InputStream, SessionType, byte)} * {@link com.smartdevicelink.streaming.AbstractPacketizer#AbstractPacketizer(IStreamListener, InputStream, RPCRequest, SessionType, byte, byte)} */ public void testConstructors () { // Test Values byte testSessionId = (byte) 0x0A; byte testWiproVersion = (byte) 0x0B; RPCRequest testRpcRequest = new RPCRequest("test"); SessionType testSessionType = SessionType.RPC; SdlSession testSdlSession = null; InputStream testInputStream = null; MockPacketizer testPacketizer1 = null; MockPacketizer testPacketizer2 = null; MockPacketizer testPacketizer3 = null; IStreamListener testListener = new MockStreamListener(); try { testInputStream = new BufferedInputStream(new ByteArrayInputStream("sdl streaming test".getBytes())); MockInterfaceBroker _interfaceBroker = new MockInterfaceBroker(); BaseTransportConfig _transportConfig = new BTTransportConfig(true); testSdlSession = SdlSession.createSession(testWiproVersion,_interfaceBroker, _transportConfig); testPacketizer1 = new MockPacketizer(testListener, testInputStream, testSessionType, testSessionId, testSdlSession); testPacketizer2 = new MockPacketizer(null, null, null, testSessionId, testSdlSession); testPacketizer3 = new MockPacketizer(testListener, testInputStream, testRpcRequest, testSessionType, testSessionId, testWiproVersion, testSdlSession); try { new MockPacketizer(null, null, null, null, testSessionId, testWiproVersion, null); fail("Exception should be thrown"); }catch(Exception e) { assertTrue(e instanceof IllegalArgumentException); } // Valid Tests assertNotNull(Test.NOT_NULL, testPacketizer1); assertNotNull(Test.NOT_NULL, testPacketizer2); assertNotNull(Test.NOT_NULL, testPacketizer3); assertEquals(Test.MATCH, testListener, testPacketizer1.getListener()); assertEquals(Test.MATCH, testInputStream, testPacketizer1.getInputStream()); assertEquals(Test.MATCH, testSessionType, testPacketizer1.getSessionType()); assertEquals(Test.MATCH, testSessionId, testPacketizer1.getSessionId()); assertEquals(Test.MATCH, testListener, testPacketizer3.getListener()); assertEquals(Test.MATCH, testInputStream, testPacketizer3.getInputStream()); assertEquals(Test.MATCH, testSessionType, testPacketizer3.getSessionType()); assertEquals(Test.MATCH, testSessionId, testPacketizer3.getSessionId()); assertEquals(Test.MATCH, testWiproVersion, testPacketizer3.getWiproVersion()); assertEquals(Test.MATCH, testRpcRequest.getFunctionName(), testPacketizer3.getRPCRequest().getFunctionName()); assertEquals(Test.MATCH, testSdlSession, testPacketizer3.getSdlSession()); // Invalid/Null Tests assertNull(Test.NULL, testPacketizer2.getListener()); assertNull(Test.NULL, testPacketizer2.getInputStream()); assertNull(Test.NULL, testPacketizer2.getSessionType()); } catch (IOException e) { e.printStackTrace(); fail("IOException was thrown."); } } }
45.473118
153
0.784819
758c8e797b3dd5f03853a411a1586e99df5df9a3
4,047
/* * Copyright 2014 Phil Burk, Mobileer 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.jsyn.unitgen; import com.jsyn.data.SpectralWindow; import com.jsyn.data.SpectralWindowFactory; import com.jsyn.data.Spectrum; import com.jsyn.ports.UnitInputPort; import com.jsyn.ports.UnitOutputPort; import com.jsyn.ports.UnitSpectralInputPort; import com.jsyn.ports.UnitSpectralOutputPort; /** * Process a signal using multiple overlapping FFT and IFFT pairs. For passthrough, you can connect * the spectral outputs to the spectral inputs. Or you can connect one or more SpectralProcessors * between them. * * <pre> * for (int i = 0; i &lt; numFFTs; i++) { * filter.getSpectralOutput(i).connect(processors[i].input); * processors[i].output.connect(filter.getSpectralInput(i)); * } * </pre> * * See the example program "HearSpectralFilter.java". Note that this spectral API is experimental * and may change at any time. * * @author Phil Burk (C) 2014 Mobileer Inc * @see SpectralProcessor */ public class SpectralFilter extends Circuit implements UnitSink, UnitSource { public UnitInputPort input; public UnitOutputPort output; private SpectralFFT[] ffts; private SpectralIFFT[] iffts; private PassThrough inlet; // fan out to FFTs private PassThrough sum; // mix output of IFFTs /** * Create a default sized filter with 2 FFT/IFFT pairs and a sizeLog2 of * Spectrum.DEFAULT_SIZE_LOG_2. */ public SpectralFilter() { this(2, Spectrum.DEFAULT_SIZE_LOG_2); } /** * @param numFFTs number of FFT/IFFT pairs for the overlap and add * @param sizeLog2 for example, use 10 to get a 1024 bin FFT, 12 for 4096 */ public SpectralFilter(int numFFTs, int sizeLog2) { add(inlet = new PassThrough()); add(sum = new PassThrough()); ffts = new SpectralFFT[numFFTs]; iffts = new SpectralIFFT[numFFTs]; int offset = (1 << sizeLog2) / numFFTs; for (int i = 0; i < numFFTs; i++) { add(ffts[i] = new SpectralFFT(sizeLog2)); inlet.output.connect(ffts[i].input); ffts[i].setOffset(i * offset); add(iffts[i] = new SpectralIFFT()); iffts[i].output.connect(sum.input); } setWindow(SpectralWindowFactory.getHammingWindow(sizeLog2)); addPort(input = inlet.input); addPort(output = sum.output); } public SpectralWindow getWindow() { return ffts[0].getWindow(); } /** * Specify one window to be used for all FFTs and IFFTs. The window should be the same size as * the FFTs. * * @param window default is HammingWindow * @see SpectralWindowFactory */ public void setWindow(SpectralWindow window) { // Use the same window everywhere. for (int i = 0; i < ffts.length; i++) { ffts[i].setWindow(window); // TODO review, both sides or just one iffts[i].setWindow(window); } } @Override public UnitOutputPort getOutput() { return output; } @Override public UnitInputPort getInput() { return input; } /** * @param i * @return the output of the indexed FFT */ public UnitSpectralOutputPort getSpectralOutput(int i) { return ffts[i].output; } /** * @param i * @return the input of the indexed IFFT */ public UnitSpectralInputPort getSpectralInput(int i) { return iffts[i].input; } }
30.89313
99
0.656536
b340e4ef554c79b5dd90c211e171a0251cd6f2b4
2,788
package com.revature.mikeworks.drivers; import com.revature.mikeworks.components.BankData; import com.revature.mikeworks.components.Customer; import com.revature.mikeworks.controllers.CentralMenuController; import com.revature.mikeworks.enums.BankSecurity; import com.revature.mikeworks.handlers.BankAccountHandler; public class BankUserDriver { private static final CentralMenuController cmc = new CentralMenuController(); private static final AccountApprovalDriver aaDriver = new AccountApprovalDriver(); private static final BankAccountDriver baDriver = new BankAccountDriver(); private static final CustomerDirectoryDriver cdDriver = new CustomerDirectoryDriver(); private static final CustomerEditDriver ceDriver = new CustomerEditDriver(); private static boolean looping; public static Customer whoAmI; public static final BankAccountHandler baHandler = BankData.getBaHandler(); public static final BankAccountTransactionDriver batDriver = new BankAccountTransactionDriver(); private void setup() { whoAmI = BankData.getWhoAmI(); baHandler.loadAll(); baHandler.assignAccountOwners(); looping = true; } public void doMain() { setup(); while (looping) { int option = cmc.readOption(whoAmI.getSecurity()); BankUserDriver.mainStep(option); } } private static void mainStep(int option) { switch(option) { case (1) -> processProfileOptionsMenu(); case (2) -> processBankAccountOptionsMenu(); case (3) -> processViewCustomerInformation(); case (4) -> processApproveDenyAccounts(); case (5) -> processEditProfiles(); case (6) -> processEditBankAccounts(); default -> { looping = false; } } } private static void processEditBankAccounts() { if (BankSecurity.authEqualOrGreater(BankSecurity.ADMIN, whoAmI.getSecurity()) ) { batDriver.doMain(); } } private static void processEditProfiles() { if (BankSecurity.authEqualOrGreater(BankSecurity.ADMIN, whoAmI.getSecurity())) { ceDriver.doMain(); } } private static void processApproveDenyAccounts() { if(BankSecurity.authEqualOrGreater(BankSecurity.EMPLOYEE, whoAmI.getSecurity())) { aaDriver.doMain(); } } private static void processViewCustomerInformation() { if (BankSecurity.authEqualOrGreater(BankSecurity.EMPLOYEE, whoAmI.getSecurity()) ) { cdDriver.doMain(); } } private static void processBankAccountOptionsMenu() { baDriver.doMain(); } private static void processProfileOptionsMenu() { cdDriver.doMain(); } }
34.419753
100
0.678623
78862ba6d75fca09085be9ea46699d46088aa70f
1,493
package be.intecbrussel.dakplusplus.model.project; import be.intecbrussel.dakplusplus.model.invoice.Invoice; import javax.persistence.*; @Entity public class Equipment { @Id @GeneratedValue private long id; private String designation; private float cost; private int quantity; @ManyToOne(cascade = {CascadeType.ALL}) private Invoice invoice; @ManyToOne(cascade = {CascadeType.ALL}) private Task task; public Equipment() { } public Equipment(String designation, float cost, int quantity) { this.designation = designation; this.cost = cost; this.quantity = quantity; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public float getCost() { return cost; } public void setCost(float cost) { this.cost = cost; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public Invoice getInvoice() { return invoice; } public void setInvoice(Invoice invoice) { this.invoice = invoice; } public Task getTask() { return task; } public void setTask(Task task) { this.task = task; } }
19.141026
68
0.61353
c78236e4a4bc776d5d7254538810efa660c44f3e
10,000
/* * Copyright (C) 2020 The zfoo Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ package com.zfoo.protocol.serializer.enhance; import com.zfoo.protocol.generate.GenerateProtocolFile; import com.zfoo.protocol.registration.EnhanceUtils; import com.zfoo.protocol.registration.field.ArrayField; import com.zfoo.protocol.registration.field.IFieldRegistration; import com.zfoo.protocol.util.StringUtils; import java.lang.reflect.Field; /** * @author jaysunxiao * @version 3.0 */ public class EnhanceArraySerializer implements IEnhanceSerializer { @Override public void writeObject(StringBuilder builder, String objectStr, Field field, IFieldRegistration fieldRegistration) { var arrayField = (ArrayField) fieldRegistration; var arrayName = getArrayClassName(arrayField); // 直接在字节码里调用方法是为了减小生成字节码的体积,下面的代码去掉也不会有任何影响 switch (arrayName) { case "boolean": builder.append(StringUtils.format("{}.writeBooleanArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "Boolean": builder.append(StringUtils.format("{}.writeBooleanBoxArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "byte": builder.append(StringUtils.format("{}.writeByteArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "Byte": builder.append(StringUtils.format("{}.writeByteBoxArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "short": builder.append(StringUtils.format("{}.writeShortArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "Short": builder.append(StringUtils.format("{}.writeShortBoxArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "int": builder.append(StringUtils.format("{}.writeIntArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "Integer": builder.append(StringUtils.format("{}.writeIntBoxArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "long": builder.append(StringUtils.format("{}.writeLongArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "Long": builder.append(StringUtils.format("{}.writeLongBoxArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "float": builder.append(StringUtils.format("{}.writeFloatArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "Float": builder.append(StringUtils.format("{}.writeFloatBoxArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "double": builder.append(StringUtils.format("{}.writeDoubleArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "Double": builder.append(StringUtils.format("{}.writeDoubleBoxArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "String": builder.append(StringUtils.format("{}.writeStringArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "char": builder.append(StringUtils.format("{}.writeCharArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; case "Character": builder.append(StringUtils.format("{}.writeCharBoxArray($1, {});", EnhanceUtils.byteBufUtils, objectStr)); return; default: } var array = "array" + GenerateProtocolFile.index.getAndIncrement(); var length = "length" + GenerateProtocolFile.index.getAndIncrement(); builder.append(StringUtils.format("{}[] {} = {};", arrayName, array, objectStr)); builder.append(StringUtils.format("int {} = ArrayUtils.length({});", length, array)); builder.append(StringUtils.format("{}.writeInt($1,{});", EnhanceUtils.byteBufUtils, length)); var i = "i" + GenerateProtocolFile.index.getAndIncrement(); builder.append(StringUtils.format("for(int {}=0; {}<{}; {}++){", i, i, length, i)); var element = "element" + GenerateProtocolFile.index.getAndIncrement(); builder.append(StringUtils.format("{} {} = {}[{}];", arrayName, element, array, i)); EnhanceUtils.enhanceSerializer(arrayField.getArrayElementRegistration().serializer()) .writeObject(builder, element, arrayField.getField(), arrayField.getArrayElementRegistration()); builder.append("}"); } @Override public String readObject(StringBuilder builder, Field field, IFieldRegistration fieldRegistration) { var arrayField = (ArrayField) fieldRegistration; var arrayName = getArrayClassName(arrayField); var array = "array" + GenerateProtocolFile.index.getAndIncrement(); switch (arrayName) { case "boolean": builder.append(StringUtils.format("{}[] {} = {}.readBooleanArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "Boolean": builder.append(StringUtils.format("{}[] {} = {}.readBooleanBoxArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "byte": builder.append(StringUtils.format("{}[] {} = {}.readByteArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "Byte": builder.append(StringUtils.format("{}[] {} = {}.readByteBoxArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "short": builder.append(StringUtils.format("{}[] {} = {}.readShortArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "Short": builder.append(StringUtils.format("{}[] {} = {}.readShortBoxArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "int": builder.append(StringUtils.format("{}[] {} = {}.readIntArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "Integer": builder.append(StringUtils.format("{}[] {} = {}.readIntBoxArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "long": builder.append(StringUtils.format("{}[] {} = {}.readLongArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "Long": builder.append(StringUtils.format("{}[] {} = {}.readLongBoxArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "float": builder.append(StringUtils.format("{}[] {} = {}.readFloatArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "Float": builder.append(StringUtils.format("{}[] {} = {}.readFloatBoxArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "double": builder.append(StringUtils.format("{}[] {} = {}.readDoubleArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "Double": builder.append(StringUtils.format("{}[] {} = {}.readDoubleBoxArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "String": builder.append(StringUtils.format("{}[] {} = {}.readStringArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "char": builder.append(StringUtils.format("{}[] {} = {}.readCharArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; case "Character": builder.append(StringUtils.format("{}[] {} = {}.readCharBoxArray($1);", arrayName, array, EnhanceUtils.byteBufUtils)); return array; default: } var length = "length" + GenerateProtocolFile.index.getAndIncrement(); builder.append(StringUtils.format("int {} = {}.readInt($1);", length, EnhanceUtils.byteBufUtils)); builder.append(StringUtils.format("{}[] {} = new {}[{}];", arrayName, array, arrayName, length)); var i = "i" + GenerateProtocolFile.index.getAndIncrement(); builder.append(StringUtils.format("for(int {}=0; {} < {}; {}++){", i, i, length, i)); var readObject = EnhanceUtils.enhanceSerializer(arrayField.getArrayElementRegistration().serializer()) .readObject(builder, arrayField.getField(), arrayField.getArrayElementRegistration()); builder.append(StringUtils.format("{}[{}] = {};}", array, i, readObject)); return array; } private String getArrayClassName(ArrayField arrayField) { // 去掉包装类型的前缀java.lang return arrayField.getField().getType().getComponentType().getCanonicalName().replaceFirst("java.lang.", StringUtils.EMPTY); } }
52.356021
137
0.6052
f86c7727de3cf267578c2cdb689d07b361609ba2
3,570
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|org.apache.camel.component.nitrite.operation.common package|package name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|nitrite operator|. name|operation operator|. name|common package|; end_package begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|Exchange import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|nitrite operator|. name|NitriteConstants import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|nitrite operator|. name|NitriteEndpoint import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|nitrite operator|. name|operation operator|. name|AbstractPayloadAwareOperation import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|nitrite operator|. name|operation operator|. name|CommonOperation import|; end_import begin_comment comment|/** * Upsert (Insert or Update) document in collection or object in ObjectRepository. If parameter not specified, updates document from message body */ end_comment begin_class DECL|class|UpsertOperation specifier|public class|class name|UpsertOperation extends|extends name|AbstractPayloadAwareOperation implements|implements name|CommonOperation block|{ DECL|method|UpsertOperation (Object payload) specifier|public name|UpsertOperation parameter_list|( name|Object name|payload parameter_list|) block|{ name|super argument_list|( name|payload argument_list|) expr_stmt|; block|} DECL|method|UpsertOperation () specifier|public name|UpsertOperation parameter_list|() block|{ } annotation|@ name|Override DECL|method|execute (Exchange exchange, NitriteEndpoint endpoint) specifier|protected name|void name|execute parameter_list|( name|Exchange name|exchange parameter_list|, name|NitriteEndpoint name|endpoint parameter_list|) throws|throws name|Exception block|{ name|exchange operator|. name|getMessage argument_list|() operator|. name|setHeader argument_list|( name|NitriteConstants operator|. name|WRITE_RESULT argument_list|, name|endpoint operator|. name|getNitriteCollection argument_list|() operator|. name|update argument_list|( name|getPayload argument_list|( name|exchange argument_list|, name|endpoint argument_list|) argument_list|, literal|true argument_list|) argument_list|) expr_stmt|; block|} block|} end_class end_unit
18.888889
810
0.806443
6a7c302c99efcac0322f6985c21056d7f7e8ff42
359
package com.brayden.example; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemSword; public class CustomSword extends ItemSword { public CustomSword() { super(ExampleMod.myToolMaterial); this.setRegistryName("my_sword"); this.setUnlocalizedName("my_sword"); this.setCreativeTab(CreativeTabs.COMBAT); } }
23.933333
47
0.760446
c6847615e85cb35405789d44b71083b5cfb34bb1
232
package ilusr.textadventurecreator.error; public interface IEmailService { /** * Sends an email. * * @param parameters The @see EmailParameters to use to send this email. */ void sendEmail(EmailParameters parameters); }
21.090909
73
0.737069
4cbe0faf768445b95fd884ab3b8f77640fef5d1f
2,057
package net.haesleinhuepf.clij2.plugins; import net.haesleinhuepf.clij.clearcl.ClearCLBuffer; import net.haesleinhuepf.clij.coremem.enums.NativeTypeEnum; import net.haesleinhuepf.clij.macro.CLIJMacroPlugin; import net.haesleinhuepf.clij.macro.CLIJOpenCLProcessor; import net.haesleinhuepf.clij.macro.documentation.OffersDocumentation; import net.haesleinhuepf.clij2.AbstractCLIJ2Plugin; import net.haesleinhuepf.clij2.CLIJ2; import net.haesleinhuepf.clij2.utilities.HasClassifiedInputOutput; import net.haesleinhuepf.clij2.utilities.IsCategorized; import org.scijava.plugin.Plugin; @Plugin(type = CLIJMacroPlugin.class, name = "CLIJ2_reduceLabelsToLabelEdges") public class ReduceLabelsToLabelEdges extends AbstractCLIJ2Plugin implements CLIJMacroPlugin, CLIJOpenCLProcessor, OffersDocumentation, IsCategorized, HasClassifiedInputOutput { @Override public String getInputType() { return "Label Image"; } @Override public String getOutputType() { return "Label Image"; } @Override public String getParameterHelpText() { return "Image input_labels, ByRef Image destination_labels"; } @Override public boolean executeCL() { return reduceLabelsToLabelEdges(getCLIJ2(), (ClearCLBuffer) args[0], (ClearCLBuffer) args[1]); } public static boolean reduceLabelsToLabelEdges(CLIJ2 clij2, ClearCLBuffer input_labels, ClearCLBuffer destination_labels) { ClearCLBuffer label_edges = clij2.create(input_labels.getDimensions(), NativeTypeEnum.UnsignedByte); clij2.detectLabelEdges(input_labels, label_edges); clij2.mask(input_labels, label_edges, destination_labels); return true; } @Override public String getDescription() { return "Takes a label map and reduces all labels to their edges. Label IDs stay the same and background will be zero."; } @Override public String getAvailableForDimensions() { return "2D, 3D"; } @Override public String getCategories() { return "Label"; } }
35.465517
177
0.753038
ae18208bafbcf767eb6176117fb6cf9ba510cbe1
140
package com.anteoy.coreJava.nk; /** * Created by zhoudazhuang on 17-12-7. */ class Pub {//default and public allow } // class Pub1 { //}
14
38
0.657143
a4523991d18558195172a2af03b4e41e78a29519
1,977
/* * Copyright (c) 2018 superblaubeere27 * * 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 net.superblaubeere27.clientbase.command; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public abstract class Command { private String name; private String[] aliases; protected Command(String name, String... aliases) { this.name = name; this.aliases = aliases; } public abstract void run(String alias, String[] args); public abstract List<String> autocomplete(int arg, String[] args); boolean match(String name) { for (String alias : aliases) { if (alias.equalsIgnoreCase(name)) return true; } return this.name.equalsIgnoreCase(name); } @NotNull List<String> getNameAndAliases() { List<String> l = new ArrayList<>(); l.add(name); l.addAll(Arrays.asList(aliases)); return l; } }
41.1875
463
0.725341
ff9cd1795049330a5146e0705a46e3ed4d7f13ef
2,079
package tracing.backend; import tracing.backend.trace.TraceEvent; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.Semaphore; /** * Queue of trace events that allows a blocking peek operation. */ public class TraceQueue { private final Semaphore available = new Semaphore(0, false); private final BlockingQueue<TraceEvent> queue = new LinkedBlockingQueue<>(); /** * Retrieves, but does not remove, the head of this queue, or blocks if the queue is empty. * @return the head of this queue */ public TraceEvent blockingPeek() { try { // potentially block until at least one element is in the queue, counts semaphore down by one this.available.acquire(); // count back up because element is not yet removed this.available.release(); } catch (InterruptedException e) { e.printStackTrace(); return null; } return this.queue.peek(); } /** * Removes the head of the queue (oldest event in the trace of a specific target) */ public void remove() { try { // count down by one because element is removed. Should not block here, as blockingPeek() should have been called first this.available.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } // remove head of queue (oldest event in the trace of a specific target) this.queue.remove(); } /** * Inserts the specified event into this queue. * @param traceEvent the event to add */ public void add(TraceEvent traceEvent) { this.queue.add(traceEvent); // indicate that there is a an element in the queue, potentially unblocking a waiting thread this.available.release(); } /** * Returns the number of events in this queue. * @return the number of events in this queue */ public int size() { return this.queue.size(); } }
31.5
131
0.634921
18d2005d9a1d336b3a4cf11da8d16ec68c138f2d
450
package tictactoe; import java.util.ArrayList; import java.util.Random; public class AI { public int pickSpot(TicTacToe game) { ArrayList<Integer> choices = new ArrayList<Integer>(); for (int i = 0; i < 9; i++) { // if slot isn't taken add it as choice if (game.board[i] == '-') { choices.add(i + 1); } } Random rand = new Random(); int choice = choices.get(Math.abs(rand.nextInt() % choices.size())); return choice; } }
22.5
70
0.635556
b0b4ba0e3eac8206f893c48edd67c3b9ebf978b1
2,260
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ /* * Changes for SnappyData data platform. * * Portions Copyright (c) 2017-2019 TIBCO Software Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ package com.pivotal.gemfirexd.internal.shared.common; import java.util.Map; /** * * @author kneeraj * */ public class ClientListResolver extends AbstractClientResolver { private int typeId; private Map mapOfListValues; public ClientListResolver(int type, Map mapOfListValues) { this.typeId = type; this.mapOfListValues = mapOfListValues; } public Object getRoutingObject(RoutingObjectInfo rinfo, SingleHopInformation sinfo, boolean requiresSerializedHash) { assert rinfo instanceof ColumnRoutingObjectInfo; ColumnRoutingObjectInfo cRInfo = (ColumnRoutingObjectInfo)rinfo; Object value = cRInfo.getActualValue(); if (value != null) { Object robj = this.mapOfListValues.get(value); if (robj != null) { return robj; } } return cRInfo.computeHashCode(0, sinfo.getResolverByte(), false); } }
31.388889
76
0.733186
94817a8c94a8bf999d6ff1c0c70a166659e8fa81
696
package zadanie1; public class Solutions { static int[] solve(int a0, int a1, int a2, int b0, int b1, int b2) { int[] result = new int[2]; int[] a = {a0, a1, a2}; int[] b = {b0, b1, b2}; for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { if (a[i] > b[i]) { result[0]++; } else { result[1]++; } } } return result; } public static void main(String[] args) { int[] results = solve(5,5,5,5,5,5); for (int i = 0; i < results.length; i++) { System.out.print(results[i]+ " "); } } }
24.857143
72
0.387931
fa6e21ee4a90350bce98b233ec2eedf054b28d5c
2,552
/* * Copyright 2016 Intuit * * 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.intuit.data.autumn.metrics; import com.google.inject.Injector; import com.google.inject.Key; import org.junit.Test; import java.io.File; import java.net.URI; import java.util.Properties; import static com.google.common.primitives.Ints.tryParse; import static com.google.inject.Guice.createInjector; import static com.google.inject.name.Names.named; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static com.intuit.data.autumn.metrics.MetricsModule.PROPERTY_NAME; import static com.intuit.data.autumn.utils.PropertyFactory.create; public class MetricsModuleTest { @Test public void injector() throws Exception { Injector injector = createInjector(new MetricsModule()); Properties properties = create(PROPERTY_NAME); assertThat(injector.getInstance(new Key<File>(named("metrics.csv.directory")) { }), equalTo(new File(properties.getProperty("metrics.csv.directory")))); assertThat(injector.getInstance(new Key<Integer>(named("metrics.csv.interval.seconds")) { }), equalTo(tryParse(properties.getProperty("metrics.csv.interval.seconds")))); assertThat(injector.getInstance(new Key<URI>(named("metrics.graphite.service")) { }), equalTo(URI.create(properties.getProperty("metrics.graphite.service")))); assertThat(injector.getInstance(new Key<String>(named("metrics.graphite.service.prefix")) { }), equalTo(properties.getProperty("metrics.graphite.service.prefix"))); assertThat(injector.getInstance(new Key<Integer>(named("metrics.graphite.interval.seconds")) { }), equalTo(tryParse(properties.getProperty("metrics.graphite.interval.seconds")))); injector.getInstance(CsvMetricsService.class); injector.getInstance(HystrixMetricsService.class); injector.getInstance(GraphiteMetricsService.class); injector.getInstance(JmxMetricsService.class); } }
43.254237
102
0.746865
6f6a6e384b043e574df40e3e1a9fbb86c7d3fbad
3,487
package com.java110.common.listener.file; import com.alibaba.fastjson.JSONObject; import com.java110.common.dao.IFileRelServiceDao; import com.java110.entity.center.Business; import com.java110.event.service.AbstractBusinessServiceDataFlowListener; import com.java110.utils.constant.ResponseConstant; import com.java110.utils.constant.StatusConstant; import com.java110.utils.exception.ListenerExecuteException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 文件存放 服务侦听 父类 * Created by wuxw on 2018/7/4. */ public abstract class AbstractFileRelBusinessServiceDataFlowListener extends AbstractBusinessServiceDataFlowListener { private static Logger logger = LoggerFactory.getLogger(AbstractFileRelBusinessServiceDataFlowListener.class); /** * 获取 DAO工具类 * * @return */ public abstract IFileRelServiceDao getFileRelServiceDaoImpl(); /** * 刷新 businessFileRelInfo 数据 * 主要将 数据库 中字段和 接口传递字段建立关系 * * @param businessFileRelInfo */ protected void flushBusinessFileRelInfo(Map businessFileRelInfo, String statusCd) { businessFileRelInfo.put("newBId", businessFileRelInfo.get("b_id")); businessFileRelInfo.put("relTypeCd", businessFileRelInfo.get("rel_type_cd")); businessFileRelInfo.put("saveWay", businessFileRelInfo.get("save_way")); businessFileRelInfo.put("operate", businessFileRelInfo.get("operate")); businessFileRelInfo.put("fileRelId", businessFileRelInfo.get("file_rel_id")); businessFileRelInfo.put("fileRealName", businessFileRelInfo.get("file_real_name")); businessFileRelInfo.put("objId", businessFileRelInfo.get("obj_id")); businessFileRelInfo.put("fileSaveName", businessFileRelInfo.get("file_save_name")); businessFileRelInfo.remove("bId"); businessFileRelInfo.put("statusCd", statusCd); } /** * 当修改数据时,查询instance表中的数据 自动保存删除数据到business中 * * @param businessFileRel 文件存放信息 */ protected void autoSaveDelBusinessFileRel(Business business, JSONObject businessFileRel) { //自动插入DEL Map info = new HashMap(); info.put("fileRelId", businessFileRel.getString("fileRelId")); info.put("statusCd", StatusConstant.STATUS_CD_VALID); List<Map> currentFileRelInfos = getFileRelServiceDaoImpl().getFileRelInfo(info); if (currentFileRelInfos == null || currentFileRelInfos.size() != 1) { throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR, "未找到需要修改数据信息,入参错误或数据有问题,请检查" + info); } Map currentFileRelInfo = currentFileRelInfos.get(0); currentFileRelInfo.put("bId", business.getbId()); currentFileRelInfo.put("relTypeCd", currentFileRelInfo.get("rel_type_cd")); currentFileRelInfo.put("saveWay", currentFileRelInfo.get("save_way")); currentFileRelInfo.put("operate", currentFileRelInfo.get("operate")); currentFileRelInfo.put("fileRelId", currentFileRelInfo.get("file_rel_id")); currentFileRelInfo.put("fileRealName", currentFileRelInfo.get("file_real_name")); currentFileRelInfo.put("objId", currentFileRelInfo.get("obj_id")); currentFileRelInfo.put("fileSaveName", currentFileRelInfo.get("file_save_name")); currentFileRelInfo.put("operate", StatusConstant.OPERATE_DEL); getFileRelServiceDaoImpl().saveBusinessFileRelInfo(currentFileRelInfo); } }
40.546512
121
0.736736
ad5edee6f4c72bdd302a1fbebe986f02bbc082e5
2,602
package org.shirdrn.storm.analytics.calculators; import net.sf.json.JSONObject; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.shirdrn.storm.analytics.common.GenericIndicatorCalculator; import org.shirdrn.storm.analytics.common.KeyedResult; import org.shirdrn.storm.analytics.constants.Constants; import org.shirdrn.storm.analytics.constants.EventFields; import org.shirdrn.storm.analytics.constants.UserInfoKeys; import org.shirdrn.storm.api.CallbackHandler; import org.shirdrn.storm.commons.constants.StatIndicators; import redis.clients.jedis.Jedis; import redis.clients.jedis.Transaction; public class UserDeviceInfoCalculator extends GenericIndicatorCalculator<KeyedResult<JSONObject>, Jedis, JSONObject> { private static final long serialVersionUID = 1L; private static final Log LOG = LogFactory.getLog(UserDeviceInfoCalculator.class); public UserDeviceInfoCalculator() { super(StatIndicators.USER_DEVICE_INFO); } @SuppressWarnings("serial") @Override public KeyedResult<JSONObject> calculate(final Jedis connection, JSONObject event) { // install event String udid = event.getString(EventFields.UDID); final String appId = event.getString(EventFields.APP_ID); final String channel = event.getString(EventFields.CHANNEL); final String version = event.getString(EventFields.VERSION); final String osType = event.getString(EventFields.OS_TYPE); final String userKey = Constants.USER_INFO_KEY_PREFIX + udid; KeyedResult<JSONObject> keyedObj = new KeyedResult<JSONObject>(); keyedObj.setIndicator(indicator); keyedObj.setKey(userKey); // set callback handler for lazy computation keyedObj.setCallbackHandler(new CallbackHandler<Jedis>() { @Override public void callback(final Jedis client) throws Exception { Transaction tx = client.multi(); tx.hset(userKey, UserInfoKeys.APP_ID, appId); tx.hset(userKey, UserInfoKeys.CHANNEL, channel); tx.hset(userKey, UserInfoKeys.VERSION, version); tx.hset(userKey, UserInfoKeys.OS_TYPE, osType); tx.exec(); logRedisCmd(LOG, "MULTI"); logRedisCmd(LOG, "HSET " + userKey + " " + UserInfoKeys.APP_ID + " " + appId); logRedisCmd(LOG, "HSET " + userKey + " " + UserInfoKeys.CHANNEL + " " + channel); logRedisCmd(LOG, "HSET " + userKey + " " + UserInfoKeys.VERSION + " " + version); logRedisCmd(LOG, "HSET " + userKey + " " + UserInfoKeys.OS_TYPE + " " + osType); logRedisCmd(LOG, "EXEC"); } }); return keyedObj; } }
37.171429
119
0.73136
2950d0a70a8f0769ac060a443990549afd1fc94d
2,648
/* * 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.jackrabbit.jcr2spi.hierarchy; import org.apache.jackrabbit.spi.Name; import java.util.Collection; /** * <code>ChildPropertyEntries</code>... */ public interface ChildPropertyEntries { /** * Returns true if a property entry with the given name exists. * * @param propertyName * @return true if a property entry with the given name exists. */ public boolean contains(Name propertyName); /** * Return the PropertyEntry with the given <code>Name</code> or * <code>null</code>. * * @param propertyName * @return */ public PropertyEntry get(Name propertyName); /** * Returns an unmodifiable collection containing all <code>PropertyEntry</code> * objects present. * * @return Collection of all <code>PropertyEntry</code> objects present. */ public Collection<PropertyEntry> getPropertyEntries(); /** * Returns an unmodifiable collection containing all existing property names. * * @return Collection of <code>Name</code> */ public Collection<Name> getPropertyNames(); /** * Adds the new <code>PropertyEntry</code> to this <code>ChildPropertyEntries</code>. * * @param propertyEntry */ public void add(PropertyEntry propertyEntry); /** * Adds all <code>PropertyEntry</code>s from the given collection to this * <code>ChildPropertyEntries</code>. * * @param propertyEntries */ public void addAll(Collection<PropertyEntry> propertyEntries); /** * Remove the collection entry with the given <code>Name</code>. * * @param propertyEntry * @return true If this <code>ChildPropertyEntries</code> contained the * given entry. False otherwise. */ public boolean remove(PropertyEntry propertyEntry); }
31.903614
89
0.689199
a3cf49d7e2d7c82d7c22b47c7aececa91b076098
1,520
package net.minidev.json.writer; /* * Copyright 2011-2014 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import net.minidev.json.JSONArray; import net.minidev.json.JSONAwareEx; import net.minidev.json.JSONObject; /** * Simple Reader Class for generic Map * * @author uriel * * @param <T> */ public class DefaultMapper<T> extends JsonReaderI<T> { protected DefaultMapper(JsonReader base) { super(base); } @Override public JsonReaderI<JSONAwareEx> startObject(String key) { return base.DEFAULT; } @Override public JsonReaderI<JSONAwareEx> startArray(String key) { return base.DEFAULT; } @Override public Object createObject() { return new JSONObject(); } @Override public Object createArray() { return new JSONArray(); } @Override public void setValue(Object current, String key, Object value) { ((JSONObject) current).put(key, value); } @Override public void addValue(Object current, Object value) { ((JSONArray) current).add(value); } }
23.75
75
0.728947
18ddccf05b7a9ae72b284f25a03890a34b575014
2,245
/* * 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.axiom.ts.om.element; import javax.xml.namespace.QName; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMMetaFactory; import org.apache.axiom.ts.AxiomTestCase; public class TestChildReDeclaringGrandParentsDefaultNSWithPrefix extends AxiomTestCase { public TestChildReDeclaringGrandParentsDefaultNSWithPrefix(OMMetaFactory metaFactory) { super(metaFactory); } @Override protected void runTest() throws Throwable { OMFactory fac = metaFactory.getOMFactory(); OMElement elem = fac.createOMElement("RequestSecurityToken", fac.createOMNamespace("http://schemas.xmlsoap.org/ws/2005/02/trust", "")); fac.createOMElement(new QName("TokenType"), elem).setText("test"); fac.createOMElement(new QName("RequestType"), elem).setText("test1"); OMElement entElem = fac.createOMElement( new QName("http://schemas.xmlsoap.org/ws/2005/02/trust", "Entropy", "wst"), elem); OMElement binSecElem = fac.createOMElement( new QName("http://schemas.xmlsoap.org/ws/2005/02/trust", "Binarysecret", "wst"), entElem); binSecElem.setText("secret value"); String xml = elem.toString(); assertTrue("Binarysecret element should have \'wst\' ns prefix", xml.indexOf("<wst:Binarysecret") != -1); } }
42.358491
96
0.703786
576f9cd29c0c1126961850922d18f167f67a7815
3,142
/* * Copyright 2015 John "LuaMilkshake" Marion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.pktr.smartbackup; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.event.FMLServerStoppingEvent; import org.apache.logging.log4j.Logger; /** * Main SmartBackup mod class. */ @Mod(modid = SmartBackup.MOD_ID, name = SmartBackup.MOD_NAME, version = SmartBackup.VERSION, acceptableRemoteVersions = "*") public class SmartBackup { public static final String MOD_ID = "SmartBackup"; public static final String MOD_NAME = MOD_ID; // These are filled in by the build process. public static final String VERSION = "$VERSION$"; public static final String SOURCE_REVISION = "$SOURCE_REVISION$"; public static final String BUILD_TIMESTAMP = "$BUILD_TIMESTAMP$"; private static Logger logger = null; private BackupManager manager; private static BackupConfiguration config = null; private static Messenger messenger = null; @EventHandler public void preInitializationEvent(FMLPreInitializationEvent event) { logger = event.getModLog(); config = new BackupConfiguration(event.getSuggestedConfigurationFile()); messenger = new Messenger(); } @EventHandler public void initializationEvent(FMLInitializationEvent event) { manager = new BackupManager(); } @EventHandler public void serverStartingEvent(FMLServerStartingEvent event) { event.registerServerCommand(new BackupCommand(manager)); } @EventHandler public void serverStoppingEvent(FMLServerStoppingEvent event) { manager.interruptBackups(); try { manager.waitForBackups(); } catch (InterruptedException e) { return; } } /** * Returns the {@link BackupConfiguration} object providing config support. * * @return {@link BackupConfiguration} to get configuration values. */ public static BackupConfiguration getConfiguration() { return config; } /** * Returns the {@link Logger} handed to SmartBackup from FML initialization. * * @return {@link Logger} to use for mod-related logging. */ public static Logger getLogger() { return logger; } /** * Returns the {@link Messenger} to use when sending messages to command senders, players, and * the console. * * @return {@link Messenger} to send messages. */ public static Messenger getMessenger() { return messenger; } }
30.504854
96
0.734246
f311cb5a64e68f6d32e2966843fdd921a08a95fc
216
package com.zzq.util; public class ArrayUtils { public static boolean isNotEmpty(byte[] data) { if (data == null || data.length == 0) { return false; } return true; } }
16.615385
51
0.541667
a50d2a6b689b7759f7d88a7379cb68ce54661d4b
2,593
package com.webimapp.android.sdk.impl.items.delta; import com.google.gson.annotations.SerializedName; import com.webimapp.android.sdk.impl.items.ChatItem; import com.webimapp.android.sdk.impl.items.DepartmentItem; import com.webimapp.android.sdk.impl.items.SurveyItem; import java.util.List; public class DeltaFullUpdate { @SerializedName("authToken") private String authToken; @SerializedName("chat") private ChatItem chat; @SerializedName("departments") private List<DepartmentItem> departments; @SerializedName("hintsEnabled") private Boolean hintsEnabled; @SerializedName("historyRevision") private String historyRevision; @SerializedName("onlineStatus") private String onlineStatus; @SerializedName("pageId") private String pageId; @SerializedName("state") private String state; // WMInvitationState private String visitorJson; // Manual deserialization "visitor" @SerializedName("visitSessionId") private String visitSessionId; @SerializedName("showHelloMessage") private boolean showHelloMessage; @SerializedName("chatStartAfterMessage") private boolean chatStartAfterMessage; @SerializedName("helloMessageDescr") private String helloMessageDescr; @SerializedName("survey") private SurveyItem survey; public DeltaFullUpdate() { // Fix for gson; } public String getAuthToken() { return authToken; } public ChatItem getChat() { return chat; } public List<DepartmentItem> getDepartments() { return departments; } public Boolean getHintsEnabled() { return hintsEnabled; } public String getHistoryRevision() { return historyRevision; } public String getOnlineStatus() { return onlineStatus; } public String getPageId() { return pageId; } public String getState() { return state; } public String getVisitorJson() { return visitorJson; } public void setVisitorJson(String visitorJson) { this.visitorJson = visitorJson; } public String getVisitSessionId() { return visitSessionId; } public boolean getShowHelloMessage() { return showHelloMessage; } public boolean getChatStartAfterMessage() { return chatStartAfterMessage; } public String getHelloMessageDescr() { return helloMessageDescr; } public SurveyItem getSurvey() { return survey; } public boolean hasChat() { return chat != null; } }
24.009259
67
0.683378
330fc527c1d7f09890164ff92f1b653252d51ce0
323
package com.baoliang.spring.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface CompoentScan { String value(); }
23.071429
44
0.80805
a69f71f2d1d8886103df4fb2cb1852d3e21c3ffd
304
package com.example.cli.domain.search; import lombok.Data; /** * @author wjw */ @Data public class UserSearch extends BaseSearch { private String name; private String email; private String roleId; private Integer status; private String userName; private String phone; }
13.217391
44
0.697368
c63a896740a2074b58ec53e76ab2cba8735390eb
1,103
/** * */ public class Cake extends BakedItem { protected int layers; /** * */ public static final double BASE_RATE = 8.0; /** * @param nameIn creates the name of the object * @param flavorIn creates the flavor of the object * @param quantityIn creates the qunatity of the object * @param ingredientsIn creates the ingredients of the object * @param layersIn creates the layers for the object */ public Cake(String nameIn, String flavorIn, int quantityIn, int layersIn, String ... ingredientsIn) { super(nameIn, flavorIn, quantityIn, ingredientsIn); layers = layersIn; } /** * @return returns the number of layers */ public int getLayers() { return layers; } /** * @param layersIn sets the number of layers for the object */ public void setLayers(int layersIn) { this.layers = layersIn; } /** * @return returns the price of the object */ public double price() { return (BASE_RATE * layers) * quantity; } }
26.902439
66
0.599275
b4569c3a08aaee0b9f9c3c6a7946a5e9d0ffe66b
1,308
package top.wayneshen.slk.controller; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.web.bind.annotation.*; import top.wayneshen.slk.serivce.ShortLinkService; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; /** * 短链接controller * * @Author wayne * @Date 2020/6/2 11:02 */ @RestController @Slf4j public class ShortLinkController { @Resource private ShortLinkService shortLinkService; /** * 生成短链接 * * @param originLink 原始链接 * @param validTime 有效时间,单位分钟 * @return */ @GetMapping("/generate") @ResponseBody public String generateShortLink(@RequestParam String originLink, @RequestParam String validTime, HttpServletRequest request) { if (StringUtils.isBlank(originLink)) { return "原始链接不可为空"; } if (!StringUtils.isNumeric(validTime)) { return "validTime必须为整数"; } String linkCode = shortLinkService.generateShortLink(originLink, validTime); String requestUrl = request.getRequestURL().toString(); String newLink = requestUrl.substring(0, requestUrl.indexOf("/generate")) + "/s/" + linkCode; return "生成成功,短链接url:" + newLink; } }
26.16
101
0.666667
bd83c7da86001352c892f9691140088ad2ae0655
3,071
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.uniandes.theexceptions.nboletas.resources; import co.edu.uniandes.theexceptions.nboletas.dtos.ComentarioDetailDTO; import co.edu.uniandes.theexceptions.nboletas.ejb.BoletaLogic; import co.edu.uniandes.theexceptions.nboletas.entities.ComentarioEntity; import co.edu.uniandes.theexceptions.nboletas.exceptions.BusinessLogicException; import java.util.List; import javax.ejb.Stateless; import javax.inject.Inject; import javax.persistence.PersistenceException; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; /** * * @author am.valero10 */ @Path("/boletas/{idBoleta: \\d+}/comentarios") @Produces("application/json") @Consumes("application/json") @Stateless public class BoletaComentarioResource { @Inject BoletaLogic boletaLogic; @POST public ComentarioDetailDTO createBoletaComentario(@PathParam("idBoleta") Long idBoleta, ComentarioDetailDTO comentario) throws BusinessLogicException, PersistenceException { ComentarioEntity comentarioCreado = boletaLogic.createBoletaComentario(idBoleta, comentario.toEntity()); return new ComentarioDetailDTO(comentarioCreado); } @GET public List<ComentarioDetailDTO> getComentarios(@PathParam("idBoleta") Long idBoleta) throws BusinessLogicException, PersistenceException { List<ComentarioEntity> list = boletaLogic.findBoletaComentarios(idBoleta); return ComentarioDetailDTO.listComentarioEntity2ComentarioDetailDTO(list); } @GET @Path("{idComentario: \\d+}") public ComentarioDetailDTO getComentario(@PathParam("idBoleta") Long idBoleta, @PathParam("idComentario") Long idComentario) throws BusinessLogicException, PersistenceException { ComentarioEntity comentario = boletaLogic.findBoletaComentarios(idBoleta, idComentario); return new ComentarioDetailDTO(comentario); } @PUT @Path("{idComentario: \\d+}") public ComentarioDetailDTO updateBoletaComentario(@PathParam("idBoleta") Long idBoleta, @PathParam("idComentario") Long idComentario, ComentarioDetailDTO comentario) throws BusinessLogicException, PersistenceException { ComentarioEntity comentarioA = comentario.toEntity(); comentarioA.setId(idComentario); ComentarioEntity actual = boletaLogic.updateBoletaComentario(idBoleta, comentarioA); return new ComentarioDetailDTO(actual); } @DELETE @Path("{idComentario: \\d+}") public void deleteBoletaComenario(@PathParam("idBoleta") Long idBoleta, @PathParam("idComentario") Long idComentario) throws BusinessLogicException, PersistenceException { boletaLogic.deleteBoletaComentario(idBoleta, idComentario); } }
42.068493
224
0.756757
d582c7d0361d9ec7c1dab69f7d375641357595af
6,164
/* * Copyright 2008 Alin Dreghiciu. * * 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.ops4j.pax.exam.rbc.internal; import java.lang.reflect.InvocationTargetException; import java.rmi.Remote; import java.rmi.RemoteException; import org.ops4j.pax.exam.RelativeTimeout; import org.osgi.framework.BundleException; /** * Remote BundleContext like access. * <p> * TODO: this is probably somewhat too fluffy (too shaky interface) - improve here * * @author Alin Dreghiciu (adreghiciu@gmail.com) * @since 0.3.0, December 10, 2008 */ public interface RemoteBundleContext extends Remote { /** * Timeout specifing that there should be no waiting. */ long NO_WAIT = 0; /** * Timeout specifing that it should wait forever. */ long WAIT_FOREVER = Long.MAX_VALUE; /** * Makes a remote call on a service. * * @param serviceType * service class of the remote service * @param methodName * method name * @param methodParamTypes * method parameters types * @param filter * service filter * @param timeout * timeout for looking up the service * @param actualParams * actual parameters (must match the given method params) * @return remote call rsult * @throws NoSuchServiceException * - If a service of the specified type cannot be located * @throws NoSuchMethodException * - If the given method cannot be found * @throws IllegalAccessException * - Specified method cannot be accessed * @throws InvocationTargetException * - Wraps an eventual exception occured during method invocation * @throws RemoteException * - Remote communication related exception (mandatory by RMI) */ Object remoteCall(Class<?> serviceType, String methodName, Class<?>[] methodParamTypes, String filter, RelativeTimeout timeout, Object... actualParams) throws RemoteException, NoSuchServiceException, NoSuchMethodException, IllegalAccessException, InvocationTargetException; /** * Installs a bundle remotly. * * @param bundleUrl * url of the bundle to be installed. The url must be accessible from the remote OSGi * container. * @return bundle id of the installed bundle * @throws RemoteException * - Remote communication related exception (mandatory by RMI) * @throws BundleException * - Re-thrown from installing the bundle */ long installBundle(String bundleUrl) throws RemoteException, BundleException; /** * Installs a bundle remotly given the bundle content. * * @param bundleLocation * bundle location * @param bundle * bundle content as a byte array * @return bundle id of the installed bundle * @throws RemoteException * - Remote communication related exception (mandatory by RMI) * @throws BundleException * - Re-thrown from installing the bundle */ long installBundle(String bundleLocation, byte[] bundle) throws RemoteException, BundleException; /** * Starts a bundle. * * @param bundleId * id of the bundle to be started * @throws RemoteException * - Remote communication related exception (mandatory by RMI) * @throws BundleException * - Re-thrown from starting the bundle */ void startBundle(long bundleId) throws RemoteException, BundleException; /** * Stops a bundle. * * @param bundleId * id of the bundle to be stopped * @throws RemoteException * - Remote communication related exception (mandatory by RMI) * @throws BundleException * - Re-thrown from stopping the bundle */ void stopBundle(long bundleId) throws RemoteException, BundleException; /** * Sets bundle start level. * * @param bundleId * id of the bundle to which the start level should be set * @param startLevel * bundle start level * @throws RemoteException * - Remote communication related exception (mandatory by RMI) * @throws BundleException * - If bundle level cannot be set */ void setBundleStartLevel(long bundleId, int startLevel) throws RemoteException, BundleException; /** * Waits for a bundle to be in a certain state and returns. * * @param bundleId * bundle id * @param state * expected state * @param timeout * max time to wait for state * @throws RemoteException * - Remote communication related exception (mandatory by RMI) * @throws BundleException * - If bundle cannot be found * @throws org.ops4j.pax.exam.TimeoutException * - if timeout occured and expected state has not being reached */ void waitForState(long bundleId, int state, RelativeTimeout timeout) throws RemoteException, BundleException; /** * @param id * of bundle to uninstall * @throws RemoteException * - Remote communication related exception (mandatory by RMI) * @throws BundleException * - If bundle cannot be found */ void uninstallBundle(long id) throws RemoteException, BundleException; }
35.222857
100
0.631246
2dfe7fe46dc72fbcbe361e1b812b4dbe5e3b0f7a
676
package ru.job4j.array; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * class FindLoopTest - решение задачи "5.2. Перевернуть массив [#4441]" * @author Густинович Антон (anton14024@yandex.ru) */ public class TurnTest { @Test public void whenLengthIsEven() { Turn turner = new Turn(); int[] array = {1, 2, 3, 4}; int[] expect = {4, 3, 2, 1}; assertThat(turner.turn(array), is(expect)); } @Test public void whenLengthIsNotEven() { Turn turner = new Turn(); int[] array = {1, 2, 3, 4, 5}; int[] expect = {5, 4, 3, 2, 1}; assertThat(turner.turn(array), is(expect)); } }
27.04
72
0.636095
e03d3d6fa827affec96badf80320383a97bfc5a7
582
package com.sd.swipemenu; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2018/3/19. */ public class DataModel { public String name; public static List<DataModel> get(int count) { final List<DataModel> list = new ArrayList<>(); for (int i = 0; i < count; i++) { final DataModel model = new DataModel(); model.name = String.valueOf(i); list.add(model); } return list; } @Override public String toString() { return name; } }
18.774194
55
0.563574
2b47326b35e0cac753e7792433c479223a436523
1,730
package cn.enncy.scs.swing.component.panel; import cn.enncy.scs.swing.constant.NiceColors; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.util.Objects; /** * //TODO * <br/>Created in 14:07 2021/4/25 * * @author: enncy */ public class StatisticsCard extends AdaptivePanel{ public String imageUrl = ""; public String text = ""; public StatisticsCard(float percent, String statisticName) { super(percent); this.setSize(new Dimension(80,100)); this.reSize(this,percent); this.setBorder(new EmptyBorder(20,20,20,20)); this.setLayout(new BorderLayout()); //统计描述 JLabel jLabel = new JLabel(statisticName,JLabel.LEFT); jLabel.setFont(new Font("微软雅黑",0,14)); jLabel.setForeground(NiceColors.DARK_GRAY); this.add(jLabel,BorderLayout.NORTH); this.setBackground(NiceColors.WHITE); this.repaint(); } public String getImageUrl() { return imageUrl; } public String getText() { return text; } public void setImageLabel(String imageUrl,String text) { this.imageUrl = imageUrl; this.text = text; //图标和数据 JLabel iconLabel = new JLabel(); ImageIcon imageIcon = new ImageIcon(Objects.requireNonNull(getClass().getClassLoader().getResource(imageUrl)).getPath()); imageIcon.setImage(imageIcon.getImage().getScaledInstance(32, 32,Image.SCALE_AREA_AVERAGING )); iconLabel.setIcon(imageIcon); iconLabel.setBorder(new EmptyBorder(10,0,0,0)); iconLabel.setText(text); iconLabel.setFont(new Font("微软雅黑",0,24)); this.add(iconLabel,BorderLayout.CENTER); } }
27.460317
129
0.656647
04bdeb2d4cd772ca814969976349e632c09aef3d
2,915
package com.osfglobal.hybris.emarsys.resolvers; import com.osfglobal.hybris.emarsys.core.model.EmarsysPredictAvailabilityZoneModel; import com.osfglobal.hybris.emarsys.utils.EmarsysFormatterUtils; import com.osfglobal.hybris.emarsys.utils.EmarsysObjectUtils; import com.osfglobal.hybris.emarsys.utils.EmarsysStringUtils; import de.hybris.platform.site.BaseSiteService; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import java.util.Map; import java.util.Objects; public class EmarsysBaseResolver implements EmarsysResolver { public static final Logger LOGGER = LoggerFactory.getLogger(EmarsysBaseResolver.class); protected static final String PATH_SEPARATOR = "."; protected Map<String, EmarsysResolver> resolvers; protected EmarsysFormatterUtils emarsysFormatterUtils; protected BaseSiteService baseSiteService; protected Object getResolverModelInstance(String key, Object model) { if(StringUtils.countMatches(key, PATH_SEPARATOR) < 2){ return model; } String modelPath = getResolverModelPath(key); return EmarsysObjectUtils.getNestedProperty(model, modelPath); } protected String getResolverModelPath(String key) { String after = StringUtils.substringAfter(key, PATH_SEPARATOR); return StringUtils.substringBeforeLast(after, PATH_SEPARATOR); } protected EmarsysResolver findResolver(String path, Map<String, EmarsysResolver> resolvers) { String[] pathArray = path.split("\\."); EmarsysResolver resolver = null; int index = 0; while (index < pathArray.length) { resolver = resolvers.get(pathArray[index]); if (resolver == null) { if (index != pathArray.length - 1) { return null; } } else { resolvers = resolver.getResolvers(); } index++; } return resolver; } @Required public void setEmarsysFormatterUtils(EmarsysFormatterUtils emarsysFormatterUtils) { this.emarsysFormatterUtils = emarsysFormatterUtils; } @Required public void setBaseSiteService(BaseSiteService baseSiteService) { this.baseSiteService = baseSiteService; } @Required public void setResolvers(Map<String, EmarsysResolver> resolvers) { this.resolvers = resolvers; } @Override public String resolve(Object model, EmarsysPredictAvailabilityZoneModel availabilityZone) { return null; } @Override public String resolve(Object model) { return null; } @Override public Map<String, EmarsysResolver> getResolvers() { return resolvers; } }
33.895349
98
0.679931
cceb2d2761fe4a1915a19925a1646251c90dc3f4
5,181
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.server.devicepolicy; import com.google.android.collect.Lists; import com.google.android.collect.Sets; import android.content.Context; import android.os.Bundle; import android.os.FileUtils; import android.os.Parcel; import android.os.Parcelable; import android.test.AndroidTestCase; import android.util.Log; import android.util.Printer; import org.junit.Assert; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import junit.framework.AssertionFailedError; public class DpmTestUtils extends AndroidTestCase { public static void clearDir(File dir) { if (dir.exists()) { Assert.assertTrue("failed to delete dir", FileUtils.deleteContents(dir)); } dir.mkdirs(); Log.i(DpmTestBase.TAG, "Created " + dir); } public static int getListSizeAllowingNull(List<?> list) { return list == null ? 0 : list.size(); } public static Bundle newRestrictions(String... restrictions) { final Bundle ret = new Bundle(); for (String restriction : restrictions) { ret.putBoolean(restriction, true); } return ret; } public static void assertRestrictions(Bundle expected, Bundle actual) { final ArrayList<String> elist; if (expected == null) { elist = null; } else { elist = Lists.newArrayList(); for (String key : expected.keySet()) { if (expected.getBoolean(key)) { elist.add(key); } } Collections.sort(elist); } final ArrayList<String> alist; if (actual == null) { alist = null; } else { alist = Lists.newArrayList(); for (String key : actual.keySet()) { if (actual.getBoolean(key)) { alist.add(key); } } Collections.sort(alist); } assertEquals(elist, alist); } public static <T extends Parcelable> T cloneParcelable(T source) { Parcel p = Parcel.obtain(); p.writeParcelable(source, 0); p.setDataPosition(0); final T clone = p.readParcelable(DpmTestUtils.class.getClassLoader()); p.recycle(); return clone; } public static Printer LOG_PRINTER = new Printer() { @Override public void println(String x) { Log.i(DpmTestBase.TAG, x); } }; public static String readAsset(Context context, String assetPath) throws IOException { final StringBuilder sb = new StringBuilder(); try (BufferedReader br = new BufferedReader( new InputStreamReader( context.getResources().getAssets().open(assetPath)))) { String line; while ((line = br.readLine()) != null) { sb.append(line); sb.append(System.lineSeparator()); } } return sb.toString(); } public static void writeToFile(File path, String content) throws IOException { path.getParentFile().mkdirs(); try (FileWriter writer = new FileWriter(path)) { Log.i(DpmTestBase.TAG, "Writing to " + path); Log.i(DpmTestBase.TAG, content); writer.write(content); } } private static boolean checkAssertRestrictions(Bundle a, Bundle b) { try { assertRestrictions(a, b); return true; } catch (AssertionFailedError e) { return false; } } public void testAssertRestrictions() { final Bundle a = newRestrictions(); final Bundle b = newRestrictions("a"); final Bundle c = newRestrictions("a"); final Bundle d = newRestrictions("b", "c"); final Bundle e = newRestrictions("b", "c"); assertTrue(checkAssertRestrictions(null, null)); assertFalse(checkAssertRestrictions(null, a)); assertFalse(checkAssertRestrictions(a, null)); assertTrue(checkAssertRestrictions(a, a)); assertFalse(checkAssertRestrictions(a, b)); assertTrue(checkAssertRestrictions(b, c)); assertFalse(checkAssertRestrictions(c, d)); assertTrue(checkAssertRestrictions(d, e)); } }
31.023952
90
0.618027
b3852d6e846568cad8e41f7211249cd0a02b9387
83
package com.dummy.bookmyshow.enums; public enum TheaterType { IMAX, PVR, LOCAL }
13.833333
35
0.759036
869a0528e07671421ba8f516dcce8fbca19ec338
8,434
package org.apache.xmlgraphics.image.loader.impl; import java.awt.color.ColorSpace; import java.awt.color.ICC_Profile; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.util.Map; import javax.imageio.stream.ImageInputStream; import javax.xml.transform.Source; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.xmlgraphics.image.loader.Image; import org.apache.xmlgraphics.image.loader.ImageException; import org.apache.xmlgraphics.image.loader.ImageFlavor; import org.apache.xmlgraphics.image.loader.ImageInfo; import org.apache.xmlgraphics.image.loader.ImageSessionContext; import org.apache.xmlgraphics.image.loader.util.ImageUtil; import org.apache.xmlgraphics.java2d.color.DeviceCMYKColorSpace; public class ImageLoaderRawJPEG extends AbstractImageLoader implements JPEGConstants { protected static Log log; public ImageFlavor getTargetFlavor() { return ImageFlavor.RAW_JPEG; } public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { if (!"image/jpeg".equals(info.getMimeType())) { throw new IllegalArgumentException("ImageInfo must be from a image with MIME type: image/jpeg"); } else { ColorSpace colorSpace = null; boolean appeFound = false; int sofType = 0; ByteArrayOutputStream iccStream = null; Source src = session.needSource(info.getOriginalURI()); ImageInputStream in = ImageUtil.needImageInputStream(src); JPEGFile jpeg = new JPEGFile(in); in.mark(); try { label508: while(true) { int segID = jpeg.readMarkerSegment(); if (log.isTraceEnabled()) { log.trace("Seg Marker: " + Integer.toHexString(segID)); } int reclen; byte[] adobeHeader; switch(segID) { case 0: case 216: break; case 192: case 193: case 194: case 202: sofType = segID; if (log.isTraceEnabled()) { log.trace("SOF: " + Integer.toHexString(segID)); } in.mark(); try { reclen = jpeg.readSegmentLength(); in.skipBytes(1); in.skipBytes(2); in.skipBytes(2); int numComponents = in.readUnsignedByte(); if (numComponents == 1) { colorSpace = ColorSpace.getInstance(1003); } else if (numComponents == 3) { colorSpace = ColorSpace.getInstance(1004); } else { if (numComponents != 4) { throw new ImageException("Unsupported ColorSpace for image " + info + ". The number of components supported are 1, 3 and 4."); } colorSpace = DeviceCMYKColorSpace.getInstance(); } } finally { in.reset(); } in.skipBytes(reclen); break; case 217: log.trace("EOI found. Stopping."); break label508; case 218: log.trace("SOS found. Stopping early."); break label508; case 226: in.mark(); try { reclen = jpeg.readSegmentLength(); adobeHeader = new byte[11]; in.readFully(adobeHeader); in.skipBytes(1); if ("ICC_PROFILE".equals(new String(adobeHeader, "US-ASCII"))) { in.skipBytes(2); int payloadSize = reclen - 2 - 12 - 2; if (this.ignoreColorProfile(hints)) { log.debug("Ignoring ICC profile data in JPEG"); in.skipBytes(payloadSize); } else { byte[] buf = new byte[payloadSize]; in.readFully(buf); if (iccStream == null) { if (log.isDebugEnabled()) { log.debug("JPEG has an ICC profile"); DataInputStream din = new DataInputStream(new ByteArrayInputStream(buf)); log.debug("Declared ICC profile size: " + din.readInt()); } iccStream = new ByteArrayOutputStream(); } iccStream.write(buf); } } } finally { in.reset(); } in.skipBytes(reclen); break; case 238: in.mark(); try { reclen = jpeg.readSegmentLength(); adobeHeader = new byte[5]; in.readFully(adobeHeader); if ("Adobe".equals(new String(adobeHeader, "US-ASCII"))) { appeFound = true; } } finally { in.reset(); } in.skipBytes(reclen); break; default: jpeg.skipCurrentMarkerSegment(); } } } finally { in.reset(); } ICC_Profile iccProfile = this.buildICCProfile(info, (ColorSpace)colorSpace, iccStream); if (iccProfile == null && colorSpace == null) { throw new ImageException("ColorSpace could not be identified for JPEG image " + info); } else { boolean invertImage = false; if (appeFound && ((ColorSpace)colorSpace).getType() == 9) { if (log.isDebugEnabled()) { log.debug("JPEG has an Adobe APPE marker. Note: CMYK Image will be inverted. (" + info.getOriginalURI() + ")"); } invertImage = true; } ImageRawJPEG rawImage = new ImageRawJPEG(info, ImageUtil.needInputStream(src), sofType, (ColorSpace)colorSpace, iccProfile, invertImage); return rawImage; } } } private ICC_Profile buildICCProfile(ImageInfo info, ColorSpace colorSpace, ByteArrayOutputStream iccStream) throws IOException, ImageException { if (iccStream != null && iccStream.size() > 0) { if (log.isDebugEnabled()) { log.debug("Effective ICC profile size: " + iccStream.size()); } int alignment = true; int padding = (4 - iccStream.size() % 4) % 4; if (padding != 0) { try { iccStream.write(new byte[padding]); } catch (IOException var8) { throw new IOException("Error while aligning ICC stream: " + var8.getMessage()); } } ICC_Profile iccProfile = null; try { iccProfile = ICC_Profile.getInstance(iccStream.toByteArray()); if (log.isDebugEnabled()) { log.debug("JPEG has an ICC profile: " + iccProfile.toString()); } } catch (IllegalArgumentException var9) { log.warn("An ICC profile is present in the JPEG file but it is invalid (" + var9.getMessage() + "). The color profile will be ignored. (" + info.getOriginalURI() + ")"); return null; } if (iccProfile.getNumComponents() != colorSpace.getNumComponents()) { log.warn("The number of components of the ICC profile (" + iccProfile.getNumComponents() + ") doesn't match the image (" + colorSpace.getNumComponents() + "). Ignoring the ICC color profile."); return null; } else { return iccProfile; } } else { return null; } } static { log = LogFactory.getLog(ImageLoaderRawJPEG.class); } }
38.688073
205
0.509485
226034bbcc00559b78994d092ffede5fa1e44080
856
package com.ikouz.algorithm.leetcode; import java.util.List; /** * The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. * <p> * Given an integer n, return all distinct solutions to the n-queens puzzle. * <p> * Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a * queen and an empty space respectively. * <p> * Example: * <p> * Input: 4 * Output: [ * [".Q..", // Solution 1 * "...Q", * "Q...", * "..Q."], * <p> * ["..Q.", // Solution 2 * "Q...", * "...Q", * ".Q.."] * ] * Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above. */ public class Backtracking_51_NQueens { public List<List<String>> solveNQueens(int n) { // TODO return null; } }
23.777778
121
0.619159
060398da1ad1cb186a8e96812447f80452179121
3,051
package springproject.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import springproject.dao.BookDAO; import springproject.exeptions.BookNotFoundException; import springproject.model.Book; import java.util.List; /** * BookService contains all the business logic. * * @author Evgeniy Presnov */ @Service @Transactional public class BookServiceImpl implements BookService { @Autowired private BookDAO bookDAO; /** * The methods returns the list of books * * @return the list of books */ @Override public List<Book> allBooks() { return bookDAO.allBooks(); } /** * The method return the book by id * * @param id * @return Book */ @Override public Book getBookId(int id) { return bookDAO.getBookId(id); } /** * The method return book by author's name * * @param author * @return Book */ @Override public Book getBookByAuthor(String author) { return bookDAO.getBookByAuthor(author); } /** * The method of deleting book by id * * @param id */ @Override public void deleteBook(int id) { bookDAO.deleteBook(id); } /** * The method adds a new book to data base * * @param book */ @Override public void saveBook(Book book) { bookDAO.saveBook(book); } /** * The method updates data about book by id * * @param id * @param book */ @Override public void updateBook(int id, Book book) { bookDAO.updateBook(id, book); } /** * This method checks existing of book by id in data base and * throw a customer exception if it doesn't exist * * @param id * @return true or false * @throws BookNotFoundException if book doesn't exist in data base */ public boolean checkExistBook(int id) throws BookNotFoundException { Book searchBook = getBookId(id); String searchBookByAuthor = searchBook.getAuthor(); for (Book authors: allBooks()) { if (searchBookByAuthor.equals(authors.getAuthor())) { return true; } } return false; } /** * This method checks existing of book by author's name in data base and * throw a customer exception if it doesn't exist * * @param authorName * @return true or false * @throws BookNotFoundException if book doesn't exist in data base */ public boolean checkExistBookByAuthorName(String authorName) throws BookNotFoundException { Book searchBook = getBookByAuthor(authorName); String searchBookByAuthor = searchBook.getAuthor(); for (Book authors: allBooks()) { if (searchBookByAuthor.equals(authors.getAuthor())) { return true; } } return false; } }
24.214286
95
0.619469
8da8e6a5f67b4df2d0bdd54b7889155324564551
556
package unluac.parse; import java.util.Objects; public class LUpvalue extends BObject { public int instack; public int idx; public String name; public LString bname; public int kind; public boolean equals(Object obj) { if(obj instanceof LUpvalue) { LUpvalue upvalue = (LUpvalue) obj; if(!(instack == upvalue.instack && idx == upvalue.idx && kind == upvalue.kind)) { return false; } return Objects.equals(name, upvalue.name); } else { return false; } } }
20.592593
88
0.602518
17ef7a43f0d8f1fb6b68eae676af95cfd11d84bc
211
package com.nel.filmes.model; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class Filme { private Long codigo; private String titulo; private String descricao; }
14.066667
33
0.78673
30467ff63ce9a1934ea0f6049c75f01f23af50ec
4,322
// RobotBuilder Version: 2.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc5229.RobotBuilderTest.subsystems; import org.usfirst.frc5229.RobotBuilderTest.commands.*; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.PIDOutput; import edu.wpi.first.wpilibj.PIDSource; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS /** * */ public class ClawElevator extends Subsystem { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS private WPI_TalonSRX talonSRX1; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS private int timeoutMs = 10; private int pidIdx = 0; private int peakCurrent = 39; private int peakCurrentDur = 0; private int contCurrent = 37; private boolean raise = false; private boolean lower = false; public void raiseElevator(double speed, boolean button) { talonSRX1.set(1); } public void lowerElevator(double speed, boolean button) { talonSRX1.set(-1); } public void stop() { talonSRX1.set(0); } public void test(double speed) { talonSRX1.set(speed); } public ClawElevator() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS talonSRX1 = new WPI_TalonSRX(1); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS //Invert motor talonSRX1.setInverted(true); talonSRX1.setSensorPhase(true); //Init Encoders talonSRX1.configSelectedFeedbackSensor(com.ctre.phoenix.motorcontrol.FeedbackDevice.CTRE_MagEncoder_Relative, 0, 0); // Set the peak and nominal outputs, 12V means full talonSRX1.configNominalOutputForward(0, timeoutMs); //(double percentOut, int timeoutMs) talonSRX1.configNominalOutputReverse(0, timeoutMs); talonSRX1.configPeakOutputForward(1, timeoutMs); //(double percentOut, int timeoutMs) talonSRX1.configPeakOutputReverse(-1, timeoutMs); // Current Limiting talonSRX1.configPeakCurrentLimit(peakCurrent, timeoutMs); /* 39 A */ talonSRX1.configPeakCurrentDuration(peakCurrentDur, timeoutMs); /* 0ms */ talonSRX1.configContinuousCurrentLimit(contCurrent, timeoutMs); /* 37A */ talonSRX1.enableCurrentLimit(true); /* turn it on */ // Init Sensor to zero talonSRX1.setSelectedSensorPosition(0, pidIdx, timeoutMs); //(int sensorPos, int pidIdx, int timeoutMs) // PID controls talonSRX1.selectProfileSlot(0, pidIdx); //(int slotIdx, int pidIdx) pidIdx should be 0 talonSRX1.config_kF(0, 3, timeoutMs); //(int slotIdx, double value, int timeoutMs) talonSRX1.config_kP(0, 2, timeoutMs); talonSRX1.config_kI(0, 0.003, timeoutMs); talonSRX1.config_kD(0, 150, timeoutMs); talonSRX1.config_IntegralZone(0, 30, timeoutMs); } @Override public void initDefaultCommand() { setDefaultCommand(new Elevator()); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // Set the default command for a subsystem here. // setDefaultCommand(new MySpecialCommand()); } @Override public void periodic() { // Put code here to be run every loop } // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CMDPIDGETTERS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CMDPIDGETTERS // Put methods for controlling this subsystem // here. Call these from Commands. }
32.742424
124
0.705923
b97a7eab24c45ad20dbbfbb69947d800c0b3e58d
1,456
package com.mobgen.halo.android.auth.login; import android.support.annotation.NonNull; import com.mobgen.halo.android.auth.authenticator.AccountManagerHelper; import com.mobgen.halo.android.framework.toolbox.data.HaloResultV2; import com.mobgen.halo.android.framework.toolbox.data.HaloStatus; import com.mobgen.halo.android.sdk.api.Halo; import com.mobgen.halo.android.sdk.core.threading.HaloInteractorExecutor; /** * Logout deleting account and session */ public class LogoutInteractor implements HaloInteractorExecutor.Interactor<Boolean> { private AccountManagerHelper mAccountManagerHelper; /** * Constructor for the interactor. * * @param accountManagerHelper */ public LogoutInteractor(AccountManagerHelper accountManagerHelper) { mAccountManagerHelper = accountManagerHelper; } @NonNull @Override public HaloResultV2<Boolean> executeInteractor() throws Exception { HaloStatus.Builder status = HaloStatus.builder(); if(mAccountManagerHelper!=null && mAccountManagerHelper.recoverAccount()!=null) { mAccountManagerHelper.removeAccount(mAccountManagerHelper.recoverAccount()); Halo.core().flushSession(); return new HaloResultV2<Boolean>(status.build(),new Boolean(true)); } else { return new HaloResultV2<Boolean>(status.error(new Exception("Account doesnt exist")).build(),new Boolean(false)); } } }
34.666667
125
0.736951
c937aed558ab3d2d41b9de2176da4a90c43ec438
3,261
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.acceptance; import static com.google.common.collect.ImmutableList.toImmutableList; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.common.collect.Streams; import com.google.common.net.InetAddresses; import com.google.gerrit.common.Nullable; import com.google.gerrit.mail.Address; import com.google.gerrit.reviewdb.client.Account; import java.net.InetSocketAddress; import java.util.Arrays; import org.apache.http.client.utils.URIBuilder; import org.eclipse.jgit.lib.PersonIdent; @AutoValue public abstract class TestAccount { public static ImmutableList<Account.Id> ids(Iterable<TestAccount> accounts) { return Streams.stream(accounts).map(TestAccount::id).collect(toImmutableList()); } public static ImmutableList<String> names(Iterable<TestAccount> accounts) { return Streams.stream(accounts).map(TestAccount::fullName).collect(toImmutableList()); } public static ImmutableList<String> names(TestAccount... accounts) { return names(Arrays.asList(accounts)); } static TestAccount create( Account.Id id, @Nullable String username, @Nullable String email, @Nullable String fullName, @Nullable String httpPassword) { return new AutoValue_TestAccount(id, username, email, fullName, httpPassword); } public abstract Account.Id id(); @Nullable public abstract String username(); @Nullable public abstract String email(); @Nullable public abstract String fullName(); @Nullable public abstract String httpPassword(); public PersonIdent newIdent() { return new PersonIdent(fullName(), email()); } public String getHttpUrl(GerritServer server) { InetSocketAddress addr = server.getHttpAddress(); return new URIBuilder() .setScheme("http") .setUserInfo(username(), httpPassword()) .setHost(InetAddresses.toUriString(addr.getAddress())) .setPort(addr.getPort()) .toString(); } public Address getEmailAddress() { // Address is weird enough that it's safer and clearer to create a new instance in a // non-abstract method rather than, say, having an abstract emailAddress() as part of this // AutoValue class. Specifically: // * Email is not specified as @Nullable in Address, but it is nullable in this class. If this // is a problem, at least it's a problem only for users of TestAccount that actually call // emailAddress(). // * Address#equals only considers email, not name, whereas TestAccount#equals should include // name. return new Address(fullName(), email()); } }
34.691489
99
0.735051
7104fc3454fe3599bd50869dda77b6f1bedcfddc
1,854
package com.manulaiko.shinshinjiru.presenter; import com.manulaiko.shinshinjiru.ShinshinjiruApplication; import com.manulaiko.shinshinjiru.view.SceneManager; import com.manulaiko.shinshinjiru.view.event.ShowLoadingLabelEvent; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.geometry.Point2D; import javafx.scene.Group; import javafx.stage.Popup; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; /** * Main layout. * ============ * <p> * Presenter for the MainLayout scene. * * @author Manulaiko <manulaiko@gmail.com> */ @Controller @Slf4j public class MainLayout { @Autowired private SceneManager sceneManager; @FXML private Group avatarCol; private final Popup popup = new Popup(); @SneakyThrows @FXML public void initialize() { var grid = sceneManager.buildScene("avatarContextMenu.fxml"); popup.getContent().add(grid.getRoot()); popup.setAutoHide(true); avatarCol.setOnMouseClicked(e -> { if (popup.isShowing()) { popup.hide(); return; } Point2D point = avatarCol.localToScreen(0, 0); var x = point.getX(); var y = point.getY() + 100; popup.show(avatarCol, x, y); log.debug("AvatarCol shown at " + x + ":" + y); }); } @FXML public void onListButton() { Platform.runLater(() -> sceneManager.show("List.fxml")); } @FXML public void onBrowseButton() { ShinshinjiruApplication.publish(new ShowLoadingLabelEvent(this)); } @FXML public void onTorrentsButton() { ShinshinjiruApplication.publish(new ShowLoadingLabelEvent(this)); } }
25.054054
73
0.658037
6c94d343397f183ef36e6b796d1ece78defafe43
1,901
package com.baeldung.hibernate.oneToMany.config; import com.baeldung.hibernate.oneToMany.model.Cart; import com.baeldung.hibernate.oneToMany.model.CartOIO; import com.baeldung.hibernate.oneToMany.model.Item; import com.baeldung.hibernate.oneToMany.model.ItemOIO; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HibernateAnnotationUtil { private static final Logger LOGGER = LoggerFactory.getLogger(HibernateAnnotationUtil.class); private static SessionFactory sessionFactory; public static SessionFactory getSessionFactory() { if (sessionFactory == null) { sessionFactory = buildSessionFactory(); } return sessionFactory; } private static SessionFactory buildSessionFactory() { try { ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .configure("hibernate-annotation.cfg.xml") .build(); Metadata metadata = new MetadataSources(serviceRegistry) .addAnnotatedClass(Cart.class) .addAnnotatedClass(CartOIO.class) .addAnnotatedClass(Item.class) .addAnnotatedClass(ItemOIO.class) .getMetadataBuilder() .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE) .build(); return metadata.getSessionFactoryBuilder().build(); } catch (Throwable ex) { LOGGER.error("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); } } }
36.557692
96
0.716465
ebc32c5d86324782cf4b37179982e6b03a90d2ed
2,776
package io.phoos.api; import io.javalin.apibuilder.ApiBuilder; import io.javalin.http.Context; import org.jetbrains.annotations.NotNull; import java.util.function.Function; /** * @author evanwht1@gmail.com */ public class JsonApiBuilder extends ApiBuilder { /**** GET *****/ public static <T> void getJSON(@NotNull String path, NoParamHandler<T> noParam) { get(path, ctx -> ctx.json(noParam.call())); } public static <T> void getJSON(NoParamHandler<T> noParam) { get(ctx -> ctx.json(noParam.call())); } public static <T, U> void getJSON(@NotNull String path, ParamHandler<T, U> intParam, Function<Context, U> paramGetter) { get(path, ctx -> ctx.json(intParam.call(paramGetter.apply(ctx)))); } public static <T, U> void getJSON(ParamHandler<T, U> intParam, Function<Context, U> paramGetter) { get(ctx -> ctx.json(intParam.call(paramGetter.apply(ctx)))); } /**** POST ****/ public static <T> void postJSON(@NotNull String path, NoParamHandler<T> noParam) { post(path, ctx -> ctx.json(noParam.call())); } public static <T> void postJSON(NoParamHandler<T> noParam) { post(ctx -> ctx.json(noParam.call())); } public static <T, U> void postJSON(@NotNull String path, ParamHandler<T, U> intParam, Function<Context, U> paramGetter) { post(path, ctx -> ctx.json(intParam.call(paramGetter.apply(ctx)))); } public static <T, U> void postJSON(ParamHandler<T, U> intParam, Function<Context, U> paramGetter) { post(ctx -> ctx.json(intParam.call(paramGetter.apply(ctx)))); } /***** PUT ****/ public static <T> void putJSON(@NotNull String path, NoParamHandler<T> noParam) { put(path, ctx -> ctx.json(noParam.call())); } public static <T> void putJSON(NoParamHandler<T> noParam) { put(ctx -> ctx.json(noParam.call())); } public static <T, U> void putJSON(@NotNull String path, ParamHandler<T, U> intParam, Function<Context, U> paramGetter) { put(path, ctx -> ctx.json(intParam.call(paramGetter.apply(ctx)))); } public static <T, U> void putJSON(ParamHandler<T, U> intParam, Function<Context, U> paramGetter) { put(ctx -> ctx.json(intParam.call(paramGetter.apply(ctx)))); } /***** DELETE ****/ public static <T> void deleteJSON(@NotNull String path, NoParamHandler<T> noParam) { delete(path, ctx -> ctx.json(noParam.call())); } public static <T> void deleteJSON(NoParamHandler<T> noParam) { delete(ctx -> ctx.json(noParam.call())); } public static <T, U> void deleteJSON(@NotNull String path, ParamHandler<T, U> intParam, Function<Context, U> paramGetter) { delete(path, ctx -> ctx.json(intParam.call(paramGetter.apply(ctx)))); } public static <T, U> void deleteJSON(ParamHandler<T, U> intParam, Function<Context, U> paramGetter) { delete(ctx -> ctx.json(intParam.call(paramGetter.apply(ctx)))); } }
32.27907
124
0.694524
c8ea4cdb3ef5431191c317fb4f125de4c24f09e4
2,860
package com.edu.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.edu.domain.dto.SysMenuDto; import com.edu.domain.dto.user.UserDto; import com.edu.domain.entity.SysMenu; import com.edu.mapper.SysMenuMapper; import com.edu.util.BeanConvertor; import com.edu.util.UserContextUtils; import com.google.common.collect.Lists; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; @Service public class SysMenuService { @Resource private SysMenuMapper sysMenuMapper; @Resource private UserService userService; public List<SysMenuDto> listAllMenu(){ LambdaQueryWrapper<SysMenu> queryWrapper = Wrappers.lambdaQuery(); queryWrapper.eq(SysMenu::getDeleted, Boolean.FALSE); queryWrapper.eq(SysMenu::getDisable, Boolean.FALSE); queryWrapper.eq(SysMenu::getLayer, 1); List<SysMenu> sysMenus = sysMenuMapper.selectList(queryWrapper); List<Long> parentId = sysMenus.stream().map(SysMenu::getId).distinct().collect(Collectors.toList()); UserDto userDto = userService.queryUserById(UserContextUtils.getUserId()); // 教师角色只可以看到内容管理菜单 if (userDto.getRole() == 2){ sysMenus = sysMenus.stream().filter(sysMenu -> sysMenu.getId() == 3).collect(Collectors.toList()); parentId = Collections.singletonList(3L); } LambdaQueryWrapper<SysMenu> querySubWrapper = Wrappers.lambdaQuery(); querySubWrapper.eq(SysMenu::getDeleted, Boolean.FALSE); querySubWrapper.eq(SysMenu::getDisable, Boolean.FALSE); querySubWrapper.eq(SysMenu::getLayer, 2); querySubWrapper.in(SysMenu::getParentId, parentId); List<SysMenu> sysSubMenus = sysMenuMapper.selectList(querySubWrapper); Map<Long, List<SysMenu>> groupSub = sysSubMenus.stream().collect(Collectors.groupingBy(SysMenu::getParentId)); List<SysMenuDto> sysMenuDtoList = sysMenus.stream().map(sysMenu -> { SysMenuDto sysMenuDto = BeanConvertor.convert(sysMenu, SysMenuDto.class); sysMenuDto.setIndex(Long.toString(sysMenu.getId())); List<SysMenu> subMenus = Optional.ofNullable(groupSub.get(sysMenu.getId())).orElseGet(Lists::newArrayList); List<SysMenuDto> sysMenuDtos = BeanConvertor.convertCollection(subMenus, SysMenuDto.class); for (SysMenuDto menuDto : sysMenuDtos) { menuDto.setIndex(menuDto.getParentId() + "-" + menuDto.getId()); } sysMenuDto.setChildren(sysMenuDtos); return sysMenuDto; }).collect(Collectors.toList()); return sysMenuDtoList; } }
41.449275
119
0.712587
1a933365b383c03673c38ceed001467bfdc6c20a
4,373
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ahorcadoclient; import GUI.Espera; import GUI.VistaJuego; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.concurrent.Semaphore; /** * * @author diego */ public class Cliente { private int port = 1893; private Socket socket; private BufferedReader inReader; private PrintWriter outPrinter; private boolean conectado = false; private VistaJuego vista; private boolean hayEscuchaPartida = false; public Semaphore esperaDesconexion = new Semaphore(0); private int numLetras; private int vidas; private String nombre; public void setVista(VistaJuego vista){ this.vista = vista; } public boolean estaConectado(){ return conectado; } public int getNumLetras(){ return numLetras; } public int getVidas(){ return vidas; } public String getNombre(){ return nombre; } public boolean conectar(String host){ try{ socket = new Socket(host, port); inReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); outPrinter = new PrintWriter(socket.getOutputStream(), true); conectado = true; } catch (Exception e){ conectado = false; } return conectado; } public void iniciarPartida(){ Espera espera = new Espera(vista, false); espera.setVisible(true); esperarInicioPartida(); espera.dispose(); vista.nuevoJuego(); vista.setVisible(true); } public boolean solicitarNombre(String nombre){ String respuesta; try{ outPrinter.println("1100 NOMBRE " + nombre); respuesta = inReader.readLine(); } catch (IOException e){ conectado = false; return false; } if (respuesta.equals("300 OK")) this.nombre = nombre; return respuesta.equals("300 OK"); } public void esperarInicioPartida(){ String respuesta; try{ do{ respuesta = inReader.readLine(); } while(!respuesta.startsWith("202 START ")); numLetras = Integer.parseInt(respuesta.substring(10)); vidas = 6; } catch (IOException e){ conectado = false; } } /** * Inicia un hilo que escucha mensajes del servidor con las palabras * y letras que proponen otros jugadores y actualiza la vista de * juego correspondientemente. * * @param vista La vista de juego a actualizar. */ public void iniciarEscuchaPartida(VistaJuego vista){ EscuchaPartida escucha = new EscuchaPartida(this, inReader, outPrinter, vista); escucha.start(); } synchronized public void setHayEscuchaPartida(boolean hay){ hayEscuchaPartida = hay; } public void proponerLetra(String letra){ String respuesta; //try{ //do{ outPrinter.println("1200 LETRA " + letra.toLowerCase()); // respuesta = inReader.readLine(); //} while(!respuesta.startsWith("300 OK")); //} catch (IOException e){ // conectado = false; //} } public void proponerPalabra(String palabra){ String respuesta; //try{ //do{ outPrinter.println("1201 PALABRA " + palabra.toLowerCase()); // respuesta = inReader.readLine(); //} while(!respuesta.startsWith("300 OK")); //} catch (IOException e){ // conectado = false; //} } public void terminarPartida(){ // Enviar ENDOK outPrinter.println("1101 ENDOK"); // Iniciar la siguiente partida vista.setVisible(false); iniciarPartida(); } synchronized public void desconectarse(){ try{ if (conectado){ outPrinter.println("1893 LOGOUT"); if (!hayEscuchaPartida){ String respuesta; do{ respuesta = inReader.readLine(); } while (!respuesta.startsWith("201 HADIÓS")); } else{ // Esperar a que escucha partida lea el HADIÓS esperaDesconexion.acquire(); } socket.close(); } }catch (IOException e){ System.err.println("Error al desconectar"); }catch (InterruptedException e){ System.err.println("Error al desconectar por semáforo"); } conectado = false; } }
21.974874
82
0.651727
25b5b8eb5ac67af0d6080bfdcbc20578bdd5ed1b
315
package vip.huhailong.foodmenu.entity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; /** * @program: food-menu * @description: 响应实体类 **/ @Data @Builder public class Rs { private Boolean status; private Integer code; private String message; private Object data; }
16.578947
38
0.72381
39f83834c770d08716939af2ac65a5ef3198699c
948
package cn.offer2020.pbj.javabasis.java.basis1.string_4_5; public class StringDemo { public static void main(String[] args) { String stra = "hello"; String strb = new String("hello"); String strc = strb;//引用传递 // == 是属于数值相等比较,在String类型中比较的是内存地址 System.out.println(stra==strb);//false System.out.println(stra == strc);//false System.out.println(strb == strc);//true System.out.println(); //equals方法收集专门进行字符串内容的比较 System.out.println(stra.equals(strb));//true System.out.println(stra.equals(strc));//true System.out.println(strb.equals(strc));//true /* * String实例化的两种方法区别 * 直接赋值:String str = "字符串"; ;只开辟一块堆内存空间,并且不会产生空间垃圾,并且自动保存在对象池中重复使用 * 构造方法:String str = new String ("字符串");:开辟两块内存空间,其中一块会变为垃圾, * 并且不会自动入池,但是用户可以使用intern()方法手工入池 * String类型字符串内容不可变 */ String str1 = "abc"; String str2 = new String ("cba"); String str3 = new String("abc").intern(); System.out.println(str1==str3);//true } }
28.727273
68
0.690928
4a4a77dd64b5775be2cbdc1b00d17a568c02e2ef
189
/** * Contains all the code needed to process and render chunks * <p>There's a good chance this won't have a lot. All well</p> * * @author ddubois */ package com.continuum.nova.chunks;
27
63
0.698413
535534b72a6b4ec49bad9a69e918067bca8ddf43
2,787
package com.intuit.cg.backendtechassessment.dto; import java.time.OffsetDateTime; import javax.validation.constraints.Future; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import org.apache.commons.lang3.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModelProperty; public class ProjectDTO { @ApiModelProperty(notes = "Project identifier (populated by database)") private Long id; @ApiModelProperty(notes = "Detailed description for the project") @NotBlank(message = "Project's description cannot be blank") private String description; @ApiModelProperty(notes = "Maximum allowed bid in dollars") @Min(value = 1, message = "Maximum budget must be greater than zero") private Long maximumBudget; @ApiModelProperty(notes = "Deadline for submitting bids") @Future(message = "Deadline cannot be in the past") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX") private OffsetDateTime deadline; @ApiModelProperty(notes = "Identifier for the project's seller") @NotNull(message = "Project must have a seller") private Long sellerId; @ApiModelProperty(notes = "Lowest bid amount for the project (if any)") private Long lowestBidAmount; @ApiModelProperty(notes = "Identifier for the winning bidder (if deadline has passed)") private Long winningBidderId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getMaximumBudget() { return maximumBudget; } public void setMaximumBudget(Long maximumBudget) { this.maximumBudget = maximumBudget; } public OffsetDateTime getDeadline() { return deadline; } public void setDeadline(OffsetDateTime deadline) { this.deadline = deadline; } public Long getLowestBidAmount() { return lowestBidAmount; } public void setLowestBidAmount(Long lowestBidAmount) { this.lowestBidAmount = lowestBidAmount; } public Long getSellerId() { return sellerId; } public void setSellerId(Long sellerId) { this.sellerId = sellerId; } public Long getWinningBidderId() { return winningBidderId; } public void setWinningBidderId(Long winningBidderId) { this.winningBidderId = winningBidderId; } public String toString() { return ToStringBuilder.reflectionToString(this); } }
26.542857
91
0.700036
dff46377c309d4aaa858def5f33dc8d93874e965
3,791
package pl.kskowronski.security; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import pl.kskowronski.data.Role; import pl.kskowronski.data.entity.admin.User; import pl.kskowronski.data.entity.global.NapUser; import pl.kskowronski.data.service.UserRepository; import pl.kskowronski.data.service.global.NapUserRepo; @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepo; @Autowired private NapUserRepo napUserRepo; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Optional<User> user = null; try { user = Optional.ofNullable(userRepo.findByUsername(username)); user.get().setPassword(getMd5(user.get().getPassword())); if (user.get().getPrcDgKodEk().equals("EK04")) {// check, maybe he is in EK04 user.get().setPassword(""); } } catch (Exception ex){ Optional<NapUser> napUser = napUserRepo.findByUsername(username); if (napUser.isPresent()) { user = userRepo.findById(napUser.get().getPrcId()); user.get().setPassword(napUser.get().getPassword()); } } if (user.get() == null) { throw new UsernameNotFoundException("Could not find user with this username and pass"); } user.get().setRoles(Collections.singleton(Role.USER)); if (user.get().getPrcId() == 115442 || user.get().getPrcId() == 279069 || user.get().getPrcId() == 340372 ) { user.get().setRoles(Collections.singleton(Role.ADMIN)); } //return new MyUserDetails(user.get()); return new org.springframework.security.core.userdetails.User(user.get().getUsername(), user.get().getPassword(), getAuthorities(user.get())); } private static List<GrantedAuthority> getAuthorities(User user) { return user.getRoles().stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRoleName())) .collect(Collectors.toList()); } private static String getMd5(String input) { try { // Static getInstance method is called with hashing SHA MessageDigest md = MessageDigest.getInstance("MD5"); // digest() method called // to calculate message digest of an input // and return array of byte byte[] messageDigest = md.digest(input.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashtext = no.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } return hashtext; } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown" + " for incorrect algorithm: " + e); return null; } } }
36.104762
121
0.659984
2e24ac997a501990c594dafa61489e5256b6ec6a
3,864
/********************************************************************************** * Copyright 2008-2009 Sakai 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/ECL-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.sakaiproject.mailsender.tool.producers; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.sakaiproject.authz.api.PermissionsHelper; import org.sakaiproject.mailsender.logic.ExternalLogic; import org.sakaiproject.tool.api.SessionManager; import org.sakaiproject.tool.api.ToolSession; import uk.ac.cam.caret.sakai.rsf.helper.HelperViewParameters; import uk.org.ponder.messageutil.MessageLocator; import uk.org.ponder.rsf.components.UICommand; import uk.org.ponder.rsf.components.UIContainer; import uk.org.ponder.rsf.components.UIOutput; import uk.org.ponder.rsf.flow.jsfnav.NavigationCase; import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter; import uk.org.ponder.rsf.view.ComponentChecker; import uk.org.ponder.rsf.view.ViewComponentProducer; import uk.org.ponder.rsf.viewstate.SimpleViewParameters; import uk.org.ponder.rsf.viewstate.ViewParameters; import uk.org.ponder.rsf.viewstate.ViewParamsReporter; public class PermissionsProducer implements ViewComponentProducer, ViewParamsReporter, NavigationCaseReporter { public static final String VIEW_ID = "permissions"; public String getViewID() { return VIEW_ID; } // Injection private SessionManager sessionManager; private ExternalLogic externalLogic; private MessageLocator messageLocator; private static final String HELPER = "sakai.permissions.helper"; public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { String locationId = externalLogic.getCurrentLocationId(); ToolSession session = sessionManager.getCurrentToolSession(); session.setAttribute(PermissionsHelper.TARGET_REF, locationId); session.setAttribute(PermissionsHelper.DESCRIPTION, messageLocator.getMessage( "mailsender.permissions.header", externalLogic.getCurrentSiteTitle())); session.setAttribute(PermissionsHelper.PREFIX, "mailtool."); List<String> perms = externalLogic.getPermissionKeys(); HashMap<String, String> pRbValues = new HashMap<String, String>(); for (int i = 0; i < perms.size(); i++) { String perm = perms.get(i); String descr = messageLocator.getMessage("desc-" + perm); pRbValues.put("desc-" + perm, descr); } session.setAttribute("permissionDescriptions", pRbValues); UIOutput.make(tofill, HelperViewParameters.HELPER_ID, HELPER); UICommand.make(tofill, HelperViewParameters.POST_HELPER_BINDING, "", null); } public ViewParameters getViewParameters() { return new HelperViewParameters(); } public List<NavigationCase> reportNavigationCases() { List<NavigationCase> l = new ArrayList<NavigationCase>(); // default navigation case l.add(new NavigationCase(null, new SimpleViewParameters(ComposeProducer.VIEW_ID))); return l; } public void setMessageLocator(MessageLocator messageLocator) { this.messageLocator = messageLocator; } public void setSessionManager(SessionManager sessionManager) { this.sessionManager = sessionManager; } public void setExternalLogic(ExternalLogic externalLogic) { this.externalLogic = externalLogic; } }
34.5
86
0.755435
ed2dd6c77064700d39caf0d314fab0823cca1193
666
package Lev04; /* Гадание на долларовый счет Вывести на экран квадрат из 10х10 букв S используя цикл while. Буквы в каждой строке не разделять. Пример вывода на экран: SSSSSSSSSS SSSSSSSSSS SSSSSSSSSS SSSSSSSSSS SSSSSSSSSS SSSSSSSSSS SSSSSSSSSS SSSSSSSSSS SSSSSSSSSS SSSSSSSSSS Требования: 1. Программа не должна считывать текст c клавиатуры. 2. Программа должна выводить текст на экран. 3. Программа должна выводить квадрат из 10х10 букв S 4. В программе должен использоваться цикл while. */ public class StrokaTenRaz { public static void main(String[] args) { int i = 1; while(i<= 10){ System.out.println("SSSSSSSSSS"); i++; } } }
18.5
62
0.749249
a984a3aa5a5e2c5f20d17be4ed78402e136c1302
231
package sirshadow.adventurebags.client.inventory.ender; import net.minecraft.entity.player.EntityPlayer; /** * Created by sirshadow on 6/26/17. */ public interface IBagContainer { void saveInventory(EntityPlayer player); }
21
55
0.774892
473eda6e8e9bb2401b11442ef84b1da8bd182136
2,500
package jp.android.test.recycleviewtest; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.ArrayList; /** * Created by jakaria on 10/6/2016. */ public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.PhotoHolder> { private ArrayList<Photo> mPhotos; //1 public static class PhotoHolder extends RecyclerView.ViewHolder implements View.OnClickListener { //2 private ImageView mItemImage; private TextView mItemDate; private TextView mItemDescription; private Photo mPhoto; //3 private static final String PHOTO_KEY = "PHOTO"; //4 public PhotoHolder(View v) { super(v); mItemImage = (ImageView) v.findViewById(R.id.item_image); mItemDate = (TextView) v.findViewById(R.id.item_date); mItemDescription = (TextView) v.findViewById(R.id.item_description); v.setOnClickListener(this); } //5 @Override public void onClick(View v) { Context context = itemView.getContext(); /*Intent showPhotoIntent = new Intent(context, PhotoActivity.class); showPhotoIntent.putExtra(PHOTO_KEY, mPhoto); context.startActivity(showPhotoIntent);*/ } public void bindPhoto(Photo photo) { mPhoto = photo; Picasso.with(mItemImage.getContext()).load(photo.getUrl()).into(mItemImage); mItemDate.setText(photo.getHumanDate()); mItemDescription.setText(photo.getExplanation()); } } public RecycleViewAdapter(ArrayList<Photo> photos) { mPhotos = photos; } @Override public RecycleViewAdapter.PhotoHolder onCreateViewHolder(ViewGroup parent, int viewType) { View inflatedView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.recyclerview_item_row, parent, false); return new PhotoHolder(inflatedView); } @Override public void onBindViewHolder(RecycleViewAdapter.PhotoHolder holder, int position) { Photo itemPhoto = mPhotos.get(position); holder.bindPhoto(itemPhoto); } @Override public int getItemCount() { return mPhotos.size(); } }
30.120482
101
0.6668
a4ee3d7016b7c6fa131d1aa0de143108c9ed1e57
6,222
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at psd2@adorsys.com. */ package de.adorsys.xs2a.adapter.verlag; import de.adorsys.xs2a.adapter.api.AccountInformationService; import de.adorsys.xs2a.adapter.api.RequestParams; import de.adorsys.xs2a.adapter.api.Response; import de.adorsys.xs2a.adapter.api.model.*; import de.adorsys.xs2a.adapter.test.ServiceWireMockTest; import de.adorsys.xs2a.adapter.test.TestRequestResponse; import org.junit.jupiter.api.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; @ServiceWireMockTest(TestVerlagServiceProvider.class) class VerlagAccountInformationServiceWireMockTest { private static final String CONSENT_ID = "cWpVQSW1X4peDA49LYWH3BnqXgDPkAdbTUf4flwrBcBGfRJPXJzpBFL-ZNGkNtYmeTllIL2aPmJr5erBhdvaj_SdMWF3876hAweK_n7HJlg=_=_psGLvQpt9Q"; private static final String AUTHORISATION_ID = "356e6d7d-9242-4264-8cb5-892e0758d69c"; private static final String ACCOUNT_ID = "3a4c851658957bc30d767425679769fc380120315d6da67faa52f016723ec9a2"; private final AccountInformationService service; VerlagAccountInformationServiceWireMockTest(AccountInformationService service) { this.service = service; } @Test void createConsent() throws Exception { TestRequestResponse requestResponse = new TestRequestResponse("ais/create-consent.json"); Response<ConsentsResponse201> response = service.createConsent(requestResponse.requestHeaders(), RequestParams.empty(), requestResponse.requestBody(Consents.class)); assertThat(response.getBody()).isEqualTo(requestResponse.responseBody(ConsentsResponse201.class)); } @Test void authenticatePsu() throws Exception { TestRequestResponse requestResponse = new TestRequestResponse("ais/authenticate-psu.json"); Response<StartScaprocessResponse> response = service.startConsentAuthorisation(CONSENT_ID, requestResponse.requestHeaders(), RequestParams.empty(), requestResponse.requestBody(UpdatePsuAuthentication.class)); assertThat(response.getBody()).isEqualTo(requestResponse.responseBody(StartScaprocessResponse.class)); } @Test void selectScaMethod() throws Exception { TestRequestResponse requestResponse = new TestRequestResponse("ais/select-sca-method.json"); Response<SelectPsuAuthenticationMethodResponse> response = service.updateConsentsPsuData(CONSENT_ID, AUTHORISATION_ID, requestResponse.requestHeaders(), RequestParams.empty(), requestResponse.requestBody(SelectPsuAuthenticationMethod.class)); assertThat(response.getBody()) .isEqualTo(requestResponse.responseBody(SelectPsuAuthenticationMethodResponse.class)); } @Test void authoriseTransaction() throws Exception { TestRequestResponse requestResponse = new TestRequestResponse("ais/authorise-transaction.json"); Response<ScaStatusResponse> response = service.updateConsentsPsuData(CONSENT_ID, AUTHORISATION_ID, requestResponse.requestHeaders(), RequestParams.empty(), requestResponse.requestBody(TransactionAuthorisation.class)); assertThat(response.getBody()).isEqualTo(requestResponse.responseBody(ScaStatusResponse.class)); } @Test void getAccounts() throws Exception { TestRequestResponse requestResponse = new TestRequestResponse("ais/get-accounts.json"); Response<AccountList> response = service.getAccountList(requestResponse.requestHeaders(), requestResponse.requestParams()); assertThat(response.getBody()).isEqualTo(requestResponse.responseBody(AccountList.class)); } @Test void getTransactions() throws Exception { TestRequestResponse requestResponse = new TestRequestResponse("ais/get-transactions.json"); Response<String> response = service.getTransactionListAsString(ACCOUNT_ID, requestResponse.requestHeaders(), requestResponse.requestParams()); assertThat(response.getBody()).isEqualTo(requestResponse.responseBody()); } @Test void getBalances() throws IOException { TestRequestResponse requestResponse = new TestRequestResponse("ais/get-balances.json"); Response<ReadAccountBalanceResponse200> response = service.getBalances(ACCOUNT_ID, requestResponse.requestHeaders(), RequestParams.empty()); assertThat(response.getBody()).isEqualTo(requestResponse.responseBody(ReadAccountBalanceResponse200.class)); } @Test void getConsentStatus() throws Exception { TestRequestResponse requestResponse = new TestRequestResponse("ais/get-consent-status.json"); Response<ConsentStatusResponse200> response = service.getConsentStatus(CONSENT_ID, requestResponse.requestHeaders(), RequestParams.empty()); assertThat(response.getBody()).isEqualTo(requestResponse.responseBody(ConsentStatusResponse200.class)); } @Test void deleteConsent() throws Exception { TestRequestResponse requestResponse = new TestRequestResponse("ais/delete-consent.json"); Response<Void> response = service.deleteConsent(CONSENT_ID, requestResponse.requestHeaders(), RequestParams.empty()); assertThat(response.getStatusCode()).isEqualTo(204); } }
41.758389
169
0.743973
4911f914759929fff4b472e4eb14b87b3d16af5d
3,478
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.act.entity.engine; import org.hibernate.validator.constraints.Length; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import com.thinkgem.jeesite.common.persistence.DataEntity; /** * act_hi_procinstEntity * @author xiaohelong * @version 2017-11-08 * * email:xiaohelong2005@126.com * xiaohelong2005@gmail.com * twitter.com/xiaohelong */ public class ActHiProcinst extends DataEntity<ActHiProcinst> { private static final long serialVersionUID = 1L; private String procInstId; // proc_inst_id_ private String businessKey; // business_key_ private String procDefId; // proc_def_id_ private Date startTime; // start_time_ private Date endTime; // end_time_ private Long duration; // duration_ private String startUserId; // start_user_id_ private String startActId; // start_act_id_ private String endActId; // end_act_id_ private String superProcessInstanceId; // super_process_instance_id_ private String deleteReason; // delete_reason_ private String tenantId; // tenant_id_ private String name; // name_ public ActHiProcinst() { super(); } public ActHiProcinst(String id){ super(id); } @Length(min=0, max=192, message="proc_inst_id_长度必须介于 0 和 192 之间") public String getProcInstId() { return procInstId; } public void setProcInstId(String procInstId) { this.procInstId = procInstId; } public String getBusinessKey() { return businessKey; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } @Length(min=0, max=192, message="proc_def_id_长度必须介于 0 和 192 之间") public String getProcDefId() { return procDefId; } public void setProcDefId(String procDefId) { this.procDefId = procDefId; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public Long getDuration() { return duration; } public void setDuration(Long duration) { this.duration = duration; } public String getStartUserId() { return startUserId; } public void setStartUserId(String startUserId) { this.startUserId = startUserId; } public String getStartActId() { return startActId; } public void setStartActId(String startActId) { this.startActId = startActId; } public String getEndActId() { return endActId; } public void setEndActId(String endActId) { this.endActId = endActId; } @Length(min=0, max=192, message="super_process_instance_id_长度必须介于 0 和 192 之间") public String getSuperProcessInstanceId() { return superProcessInstanceId; } public void setSuperProcessInstanceId(String superProcessInstanceId) { this.superProcessInstanceId = superProcessInstanceId; } public String getDeleteReason() { return deleteReason; } public void setDeleteReason(String deleteReason) { this.deleteReason = deleteReason; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
22.584416
108
0.736918
8a4ae0acc99d2305052b12c088f893008f0afa0c
221
package com.epgpbot.epgpbot.schema; //IMPORTANT: DO NOT RE-ORDER (stored in DB). public enum PermissionType { VIEW_EPGP, MODIFY_EPGP, MODIFY_PERMISSIONS, IMPORT_EPGP, ARMORY_SYNC, AUDIT_EPGP, DECAY_EPGP, }
17
44
0.746606
6fa5b2c6b5816dadd0a98ea06e868c5dbd9c17a4
817
package com.marckregio.providers.database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by eCopy on 10/6/2017. */ public class SQLHelper extends SQLiteOpenHelper{ static String DATABASE = "Beehive.db"; static int VERSION = 1; public SQLHelper(Context context) { super(context, DATABASE, null, VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { //TODO : add tables here sqLiteDatabase.execSQL(ContentContract.CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + ContentContract.TABLE); } }
25.53125
81
0.686659
0c3777741172e551cff8e224ace7f666df11f67f
12,884
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package imrcp; import imrcp.store.FileWrapper; import imrcp.system.Scheduling; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; /** * * @author Federal Highway Administration */ public abstract class FileCache extends BaseBlock { protected ArrayList<FileWrapper> m_oCache; protected boolean m_bFilesAppendable; protected int m_nPeriod; protected int m_nOffset; protected int m_nMaxForecast; protected int m_nFileFrequency; protected FileWrapper m_oSearch; protected long m_lLastFileMissingTime = 0; protected int m_nTimeout; protected FilenameFormatter[] m_oFormatters; protected int m_nLimit; private static int[] EMPTYARRAY = new int[0]; /** * Array of obs type ids that the block has data for */ public int[] m_nSubObsTypes; public static int VALID = 0; public static int START = 2; public static int END = 1; public static Comparator<String> REFTIMECOMP = (String o1, String o2) -> { int nIndex1 = o1.lastIndexOf("_") + 1; String s1 = o1.substring(nIndex1, o1.indexOf(".", nIndex1)); int nIndex2 = o2.lastIndexOf("_") + 1; String s2 = o2.substring(nIndex2, o2.indexOf(".", nIndex2)); int nReturn = s2.compareTo(s1); if (nReturn == 0) { nIndex1 = o1.lastIndexOf("_", nIndex1 - 2); nIndex1 = o1.lastIndexOf("_", nIndex1 - 1) + 1; s1 = o1.substring(nIndex1, o1.indexOf("_", nIndex1)); nIndex2 = o2.lastIndexOf("_", nIndex2 - 2); nIndex2 = o1.lastIndexOf("_", nIndex2 - 1) + 1; s2 = o2.substring(nIndex2, o2.indexOf("_", nIndex2)); nReturn = s1.compareTo(s2); } return nReturn; }; protected abstract FileWrapper getNewFileWrapper(); @Override public void reset() { m_oCache = new ArrayList(); m_oSearch = getNewFileWrapper(); m_bFilesAppendable = Boolean.parseBoolean(m_oConfig.getString("append", "False")); m_nPeriod = m_oConfig.getInt("period", 300); m_nOffset = m_oConfig.getInt("offset", 0); m_nMaxForecast = m_oConfig.getInt("maxfcst", 0); m_nFileFrequency = m_oConfig.getInt("freq", 0); m_nTimeout = m_oConfig.getInt("timeout", 300000); String[] sFormatters = m_oConfig.getStringArray("format", ""); m_oFormatters = new FilenameFormatter[sFormatters.length]; for (int i = 0; i < sFormatters.length; i++) m_oFormatters[i] = new FilenameFormatter(sFormatters[i]); m_nLimit = m_oConfig.getInt("limit", 24); String[] sObsTypes = m_oConfig.getStringArray("subobs", null); //get the obstypes this block subscribes for if (sObsTypes.length == 0) m_nSubObsTypes = EMPTYARRAY; else m_nSubObsTypes = new int[sObsTypes.length]; //convert String[] to int[] for (int j = 0; j < sObsTypes.length; j++) m_nSubObsTypes[j] = Integer.valueOf(sObsTypes[j], 36); } /** * This method runs when the block gets a notification. * * @param oNotification the notification from the collector */ @Override public void process(String[] sMessage) { if (sMessage[MESSAGE].compareTo("file download") == 0) // handle new files downloaded { ArrayList<String> oFiles = new ArrayList(); for (int i = 2; i < sMessage.length; i++) { String sFile = sMessage[i]; if ((searchCache(sFile) < 0 || m_bFilesAppendable) && loadFileToMemory(sFile, m_oFormatters[0])) oFiles.add(sFile); } if (oFiles.isEmpty()) return; long lStartTime = Long.MAX_VALUE; long lEndTime = Long.MIN_VALUE; long[] lTimes = new long[3]; for (String sFile : oFiles) { m_oFormatters[0].parse(sFile, lTimes); if (lTimes[START] < lStartTime) lStartTime = lTimes[START]; if (lTimes[END] > lEndTime) lEndTime = lTimes[END]; } String[] sNotification = new String[2 + m_nSubObsTypes.length]; int nIndex = 0; sNotification[nIndex++] = Long.toString(lStartTime); sNotification[nIndex++] = Long.toString(lEndTime); for (int nObsType : m_nSubObsTypes) sNotification[nIndex++] = Integer.toString(nObsType); notify("new data", sNotification); } } @Override public boolean start() throws Exception { int nInitFiles = m_oConfig.getInt("initfiles", 0); String sDir = m_oFormatters[0].format(System.currentTimeMillis(), 0, 0); String sExt = m_oFormatters[0].getExtension(); sDir = sDir.substring(0, sDir.lastIndexOf("/") + 1); File oDir = new File(sDir); String[] sFiles = oDir.list(); if (sFiles != null) // can be null if the directory doesn't exist { ArrayList<String> oFiles = new ArrayList(); for (String sFile : sFiles) { if (sFile.endsWith(sExt)) oFiles.add(sFile); } Collections.sort(oFiles, REFTIMECOMP); int nLimit = Math.min(nInitFiles, oFiles.size()); for (int i = 0; i < nLimit; i++) loadFileToMemory(sDir + oFiles.get(i), m_oFormatters[0]); } m_nSchedId = Scheduling.getInstance().createSched(this, m_nOffset, m_nPeriod); return true; } public FileWrapper getFile(long lTimestamp, long lRefTime) { if (loadFileToCache(lTimestamp, lRefTime)) { synchronized (m_oCache) { Iterator<FileWrapper> oIt = m_oCache.iterator(); while (oIt.hasNext()) // files are sorted by valid time descending, then start time ascending, then endtime ascending { FileWrapper oTempFile = oIt.next(); if (matches(oTempFile, lTimestamp, lRefTime)) // so the first file match the request should be the "best" forecast we have return oTempFile; } } } return null; } /** * Finds the most recent file based off of the reftime that is valid for the * given timestamp * * @param lTimestamp query timestamp * @param lRefTime reference time * @return true if a file is loaded into memory or if the most recent file * is already in the LRU, false if no file was found that matches the * timestamp and reftime */ protected boolean loadFileToCache(long lTimestamp, long lRefTime) { for (FilenameFormatter oFormatter : m_oFormatters) { ArrayList<String> oDirs = new ArrayList(4); // determine which directories need to be checked, add them in order from most recent, to earliest addDirForTime(lRefTime, oDirs, oFormatter); // always add the ref time first if (m_nMaxForecast > m_nFileFrequency) { int nFiles = m_nMaxForecast / m_nFileFrequency + 1; // add one since it is integer division for (int i = 1; i <= nFiles; i++) addDirForTime(lRefTime - (m_nFileFrequency * i), oDirs, oFormatter); addDirForTime(lTimestamp, oDirs, oFormatter); for (int i = 1; i <= nFiles; i++) addDirForTime(lTimestamp - (m_nFileFrequency * i), oDirs, oFormatter); } else { addDirForTime(lRefTime - m_nMaxForecast, oDirs, oFormatter); addDirForTime(lTimestamp, oDirs, oFormatter); addDirForTime(lTimestamp - m_nMaxForecast, oDirs, oFormatter); } long[] lTimes = new long[3]; String sExt = oFormatter.getExtension(); for (String sDir : oDirs) { File oDir = new File(sDir); String[] sFiles = oDir.list(); if (sFiles == null) continue; ArrayList<String> oFiles = new ArrayList(); for (String sFile : sFiles) { if (sFile.endsWith(sExt)) oFiles.add(sFile); else if (sFile.endsWith(".gz") && sFile.substring(0, sFile.lastIndexOf(".gz")).endsWith(sExt)) oFiles.add(sFile); } Collections.sort(oFiles, REFTIMECOMP); // sort by valid time then start for (String sFile : oFiles) { oFormatter.parse(sFile, lTimes); if (lTimes[VALID] > lRefTime || lTimes[START] > lTimestamp || lTimes[END] <= lTimestamp) continue; int nIndex = searchCache(lTimes[VALID], lTimes[START], lTimes[END]); if (nIndex >= 0) return true; if (loadFileToMemory(sDir + sFile, oFormatter)) return true; } } } return false; } public void addDirForTime(long lTimestamp, ArrayList<String> oDirs, FilenameFormatter oFormatter) { String sDir = oFormatter.format(lTimestamp, 0, 0); sDir = sDir.substring(0, sDir.lastIndexOf("/") + 1); // include the / boolean bAdd = true; for (String sExistingDir : oDirs) { if (sDir.compareTo(sExistingDir) == 0) { bAdd = false; break; } } if (bAdd) oDirs.add(sDir); } public boolean loadFileToMemory(String sFullPath, FilenameFormatter oFormatter) { int nStatus = (int)status()[0]; if (nStatus == STOPPING || nStatus == STOPPED || nStatus == ERROR) return false; File oFile = new File(sFullPath); try { if (!oFile.exists()) { File oGz = new File(sFullPath + ".gz"); if (!oGz.exists()) { if (m_lLastFileMissingTime + m_nFileFrequency < System.currentTimeMillis()) { m_oLogger.error("File does not exist: " + sFullPath); m_lLastFileMissingTime = System.currentTimeMillis(); } return false; } } FileWrapper oFileWrapper = getNewFileWrapper(); boolean bNewWrapper = true; boolean bLoad = true; long[] lTimes = new long[3]; int nContribId = oFormatter.parse(sFullPath, lTimes); synchronized (m_oCache) { int nIndex = searchCache(lTimes[VALID], lTimes[START], lTimes[END]); if (m_bFilesAppendable && nIndex >= 0) { oFileWrapper = m_oCache.get(nIndex); bNewWrapper = false; } else if (nIndex >= 0) // file is already in cache bLoad = false; if (bLoad) { m_oLogger.info("Loading " + sFullPath + " into cache"); try { oFileWrapper.load(lTimes[START], lTimes[END], lTimes[VALID], sFullPath, nContribId); } catch (Exception oException) { if (oFile.exists() && oFile.isFile()) { m_oLogger.info("Deleting invalid file: " + sFullPath); oFileWrapper.deleteFile(oFile); } throw oException; } if (bNewWrapper) addToCache(oFileWrapper); oFileWrapper.m_lLastUsed = System.currentTimeMillis(); m_oLogger.info("Finished loading " + sFullPath); } } return true; } catch (Exception oException) { m_oLogger.error(oException, oException); } return false; } @Override public void execute() { if (m_oCache.size() < m_nLimit) // do nothing if the cache has not reached its limit return; m_oLogger.info("Clearing cache"); long lTimeout = System.currentTimeMillis() - m_nTimeout; ArrayList<FileWrapper> oFilesToCleanup = new ArrayList(); synchronized (m_oCache) { int nIndex = m_oCache.size(); while (nIndex-- > 0) { FileWrapper oTemp = m_oCache.get(nIndex); if (oTemp.m_lLastUsed < lTimeout) { m_oCache.remove(nIndex); oFilesToCleanup.add(oTemp); // collect removed files to cleanup outside of synchronized block to prevent long lock on cache } } } for (FileWrapper oFile : oFilesToCleanup) oFile.cleanup(true); m_oLogger.info(String.format("Removed %d files", oFilesToCleanup.size())); } public synchronized int searchCache(FileWrapper oFile) { if (m_oCache.isEmpty()) return -1; if (m_oCache.get(0).compareTo(oFile) == 0) // always check the first file because most searches will be for the most recent file return 0; return Collections.binarySearch(m_oCache, oFile); } public synchronized int searchCache(long lValid, long lStart, long lEnd) { if (m_oCache.isEmpty()) return -1; m_oSearch.setTimes(lValid, lStart, lEnd); if (m_oCache.get(0).compareTo(m_oSearch) == 0) // always check the first file because most searches will be for the most recent file return 0; return Collections.binarySearch(m_oCache, m_oSearch); } public synchronized int searchCache(String sFilename) { if (m_oCache.isEmpty()) return -1; long[] lTimes = new long[3]; m_oFormatters[0].parse(sFilename, lTimes); // this only gets the times so it doesn't matter which formatter is used m_oSearch.setTimes(lTimes[VALID], lTimes[START], lTimes[END]); return Collections.binarySearch(m_oCache, m_oSearch); } public synchronized boolean addToCache(FileWrapper oFile) { int nIndex = searchCache(oFile); if (nIndex < 0) { m_oCache.add(~nIndex, oFile); return true; } return false; } public boolean matches(FileWrapper oFile, long lTimestamp, long lRefTime) { return lRefTime >= oFile.m_lValidTime && lTimestamp < oFile.m_lEndTime && lTimestamp >= oFile.m_lStartTime; } public synchronized void clearCache() { int nIndex = m_oCache.size(); while (nIndex-- > 0) { FileWrapper oWrapper = m_oCache.get(nIndex); oWrapper.cleanup(true); m_oCache.remove(nIndex); } } @Override public boolean stop() { int nIndex = m_oCache.size(); while (nIndex-- > 0) { FileWrapper oWrapper = m_oCache.get(nIndex); oWrapper.cleanup(true); m_oCache.remove(nIndex); } return true; } }
28.887892
145
0.675722
713bd182e3cc97015af50e948f076ad57de3c0af
2,437
/* * 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.camel.component.aws2.ddb; import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.support.DefaultExchange; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputDescription; import software.amazon.awssdk.services.dynamodb.model.TableStatus; import static org.junit.jupiter.api.Assertions.assertEquals; public class DeleteTableCommandTest { private DeleteTableCommand command; private AmazonDDBClientMock ddbClient; private Ddb2Configuration configuration; private Exchange exchange; @BeforeEach public void setUp() { ddbClient = new AmazonDDBClientMock(); configuration = new Ddb2Configuration(); configuration.setTableName("DOMAIN1"); exchange = new DefaultExchange(new DefaultCamelContext()); command = new DeleteTableCommand(ddbClient, configuration, exchange); } @Test public void testExecute() { command.execute(); assertEquals("DOMAIN1", ddbClient.deleteTableRequest.tableName()); assertEquals(ProvisionedThroughputDescription.builder().build(), exchange.getIn().getHeader(Ddb2Constants.PROVISIONED_THROUGHPUT)); assertEquals(Long.valueOf(10L), exchange.getIn().getHeader(Ddb2Constants.ITEM_COUNT, Long.class)); assertEquals(Long.valueOf(20L), exchange.getIn().getHeader(Ddb2Constants.TABLE_SIZE, Long.class)); assertEquals(TableStatus.ACTIVE, exchange.getIn().getHeader(Ddb2Constants.TABLE_STATUS, TableStatus.class)); } }
42.754386
139
0.760771
b45780edcef367b254794939901bac159b3b1ecd
2,604
/* * Copyright 2015-2021 Micro Focus or one of its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hpe.caf.worker.testing; /** * This should be called TestInstanceInfo.... */ public class TestCaseInfo { private String associatedTickets; private String comments; private String description; private String testCaseId; /** * Getter for property 'testCaseId'. * * @return Value for property 'testCaseId'. */ public String getTestCaseId() { return testCaseId; } /** * Setter for property 'testCaseId'. * * @param testCaseId Value to set for property 'testCaseId'. */ public void setTestCaseId(String testCaseId) { this.testCaseId = testCaseId; } /** * Getter for property 'associatedTickets'. * * @return Value for property 'associatedTickets'. */ public String getAssociatedTickets() { return associatedTickets; } /** * Setter for property 'associatedTickets'. * * @param associatedTickets Value to set for property 'associatedTickets'. */ public void setAssociatedTickets(String associatedTickets) { this.associatedTickets = associatedTickets; } /** * Getter for property 'comments'. * * @return Value for property 'comments'. */ public String getComments() { return comments; } /** * Setter for property 'comments'. * * @param comments Value to set for property 'comments'. */ public void setComments(String comments) { this.comments = comments; } /** * Getter for property 'description'. * * @return Value for property 'description'. */ public String getDescription() { return description; } /** * Setter for property 'description'. * * @param description Value to set for property 'description'. */ public void setDescription(String description) { this.description = description; } }
24.111111
78
0.636329
e2f5b38d37e6c921d3c55d7fb30c33ccf97865f3
1,315
package de.uni_stuttgart.informatik.sopra.sopraapp.feature.map.bottomsheet; import android.content.Context; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.CoordinatorLayout; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; /** * https://stackoverflow.com/a/36775907/8596346 * * @param <V> */ @SuppressWarnings("unused") public class LockableBottomSheetBehaviour<V extends View> extends BottomSheetBehavior<V> { private boolean isLocked = true; public LockableBottomSheetBehaviour() { super(); } public LockableBottomSheetBehaviour(Context context, AttributeSet attrs) { super(context, attrs); } public static <V extends View> LockableBottomSheetBehaviour from(V view) { ViewGroup.LayoutParams params = view.getLayoutParams(); return LockableBottomSheetBehaviour.class.cast(((CoordinatorLayout.LayoutParams) params).getBehavior()); } public void allowUserSwipe(boolean enabled) { this.isLocked = !enabled; } @Override public boolean onInterceptTouchEvent(CoordinatorLayout parent, V child, MotionEvent event) { return !isLocked && super.onInterceptTouchEvent(parent, child, event); } }
31.309524
112
0.747529
9c5489b8a4012f1f7da2edba24f1d4caa089dc09
10,556
package com.hedera.hashgraph.sdk; import com.hedera.hashgraph.sdk.account.CryptoTransferTransaction; import com.hederahashgraph.api.proto.java.Query; import com.hederahashgraph.api.proto.java.QueryHeader; import com.hederahashgraph.api.proto.java.Response; import com.hederahashgraph.api.proto.java.ResponseCodeEnum; import com.hederahashgraph.api.proto.java.ResponseHeader; import com.hederahashgraph.api.proto.java.ResponseType; import java.util.Objects; import java.util.function.Consumer; import javax.annotation.Nullable; import io.grpc.Channel; import io.grpc.MethodDescriptor; public abstract class QueryBuilder<Resp, T extends QueryBuilder<Resp, T>> extends HederaCall<Query, Response, Resp, T> { protected final Query.Builder inner = Query.newBuilder(); @Nullable protected final Client client; @Nullable private Node pickedNode; protected QueryBuilder(@Nullable Client client) { this.client = client; } protected abstract QueryHeader.Builder getHeaderBuilder(); @Override protected Channel getChannel() { return getNode().getChannel(); } protected Client requireClient() { return Objects.requireNonNull(client, "QueryBuilder.client must be non-null in regular use"); } private Node getNode() { if (pickedNode == null) { pickedNode = requireClient().pickNode(); } return pickedNode; } @Override public final Query toProto() { setPaymentDefault(); validate(); return inner.build(); } @SuppressWarnings("unchecked") public T setPayment(Transaction transaction) { getHeaderBuilder().setPayment(transaction.toProto()); return (T) this; } /** * Explicitly specify that the operator account is paying for the query and set payment. * <p> * Only takes effect if payment is required, has not been set yet, and an operator ID * was provided to the {@link Client} used to construct this instance. * * @return {@code this} for fluent usage. * @deprecated query cost should be calculated by requesting it from the node so this function's * signature is insufficient to abstract over that operation. */ @Deprecated(forRemoval = true) public T setPaymentDefault() { return setPaymentDefault(100_000); } /** * Explicitly specify that the operator account is paying for the query and set payment * with the given amount. * <p> * Only takes effect if payment is required, has not been set yet, and an operator ID * was provided to the {@link Client} used to construct this instance. * * @return {@code this} for fluent usage. */ public T setPaymentDefault(long paymentAmount) { if (client != null && isPaymentRequired() && !getHeaderBuilder().hasPayment() && client.getOperatorId() != null) { var operatorId = client.getOperatorId(); var nodeId = getNode().accountId; var txPayment = new CryptoTransferTransaction(client) .setNodeAccountId(nodeId) .setTransactionId(new TransactionId(operatorId)) .addSender(operatorId, paymentAmount) .addRecipient(nodeId, paymentAmount) .build(); setPayment(txPayment); } //noinspection unchecked return (T) this; } public final long requestCost() throws HederaException, HederaNetworkException { return new CostQuery().execute(); } public final void requestCostAsync(Consumer<Long> withCost, Consumer<HederaThrowable> onError) { new CostQuery().executeAsync(withCost, onError); } @Override protected void onPreExecute() throws HederaException, HederaNetworkException { final var maxQueryPayment = requireClient().getMaxQueryPayment(); if (!getHeaderBuilder().hasPayment() && isPaymentRequired() && maxQueryPayment > 0) { final var cost = requestCost(); if (cost > maxQueryPayment) { throw new MaxPaymentExceededException(this, cost, maxQueryPayment); } setPaymentDefault(requestCost()); } } @Override protected void onPreExecuteAsync(Runnable onSuccess, Consumer<HederaThrowable> onError) { final var maxQueryPayment = requireClient().getMaxQueryPayment(); if (!getHeaderBuilder().hasPayment() && isPaymentRequired() && maxQueryPayment > 0) { requestCostAsync(cost -> { if (cost > maxQueryPayment) { onError.accept(new MaxPaymentExceededException(this, cost, maxQueryPayment)); return; } setPaymentDefault(cost); onSuccess.run(); }, onError); } else { onSuccess.run(); } } protected abstract void doValidate(); protected boolean isPaymentRequired() { return true; } /** * Check that the query was built properly, throwing an exception on any errors. */ @Override public final void validate() { if (isPaymentRequired()) { require(getHeaderBuilder().hasPayment(), ".setPayment() required"); } doValidate(); checkValidationErrors("query builder failed validation"); } private static ResponseHeader getResponseHeader(Response raw) { switch (raw.getResponseCase()) { case GETBYKEY: return raw.getGetByKey().getHeader(); case GETBYSOLIDITYID: return raw.getGetBySolidityID().getHeader(); case CONTRACTCALLLOCAL: return raw.getContractCallLocal().getHeader(); case CONTRACTGETBYTECODERESPONSE: return raw.getContractGetBytecodeResponse().getHeader(); case CONTRACTGETINFO: return raw.getContractGetInfo().getHeader(); case CONTRACTGETRECORDSRESPONSE: return raw.getContractGetRecordsResponse().getHeader(); case CRYPTOGETACCOUNTBALANCE: return raw.getCryptogetAccountBalance().getHeader(); case CRYPTOGETACCOUNTRECORDS: return raw.getCryptoGetAccountRecords().getHeader(); case CRYPTOGETINFO: return raw.getCryptoGetInfo().getHeader(); case CRYPTOGETCLAIM: return raw.getCryptoGetClaim().getHeader(); case CRYPTOGETPROXYSTAKERS: return raw.getCryptoGetProxyStakers().getHeader(); case FILEGETCONTENTS: return raw.getFileGetContents().getHeader(); case FILEGETINFO: return raw.getFileGetInfo().getHeader(); case TRANSACTIONGETRECEIPT: return raw.getTransactionGetReceipt().getHeader(); case TRANSACTIONGETRECORD: return raw.getTransactionGetRecord().getHeader(); case RESPONSE_NOT_SET: throw new IllegalStateException("Response not set"); default: // NOTE: TRANSACTIONGETFASTRECORD shouldn't be handled as we don't expose that query throw new RuntimeException("Unhandled response case"); } } @Override protected final Resp mapResponse(Response raw) throws HederaException { final ResponseCodeEnum precheckCode = getResponseHeader(raw).getNodeTransactionPrecheckCode(); final var responseCase = raw.getResponseCase(); var unknownIsExceptional = false; switch (responseCase) { case TRANSACTIONGETRECEIPT: case TRANSACTIONGETRECORD: break; default: unknownIsExceptional = true; } HederaException.throwIfExceptional(precheckCode, unknownIsExceptional); return fromResponse(raw); } protected abstract Resp fromResponse(Response raw); private final class CostQuery extends HederaCall<Query, Response, Long, CostQuery> { @Override protected MethodDescriptor<Query, Response> getMethod() { return QueryBuilder.this.getMethod(); } @Override public Query toProto() { final var header = getHeaderBuilder(); final var origPayment = header.hasPayment() ? header.getPayment() : null; final var origResponseType = header.getResponseType(); final var nodeAccountId = getNode().accountId; final var operatorId = Objects.requireNonNull( requireClient().getOperatorId(), "COST_ANSWER requires an operator ID to be set"); // COST_ANSWER requires a payment to pass validation but doesn't actually process it final var fakePayment = new CryptoTransferTransaction(client) .addRecipient(nodeAccountId, 0) .addSender(operatorId, 0) .build() .toProto(); // set our fake values, build and then reset header.setPayment(fakePayment); header.setResponseType(ResponseType.COST_ANSWER); final var built = inner.build(); if (origPayment != null) { header.setPayment(origPayment); } else { header.clearPayment(); } header.setResponseType(origResponseType); return built; } @Override protected Channel getChannel() { return QueryBuilder.this.getChannel(); } @Override protected Long mapResponse(Response raw) throws HederaException { return getResponseHeader(raw).getCost(); } @Override public void validate() { // skip payment validation doValidate(); QueryBuilder.this.checkValidationErrors("cannot get cost for incomplete query"); } } public static final class MaxPaymentExceededException extends RuntimeException implements HederaThrowable { private MaxPaymentExceededException(QueryBuilder builder, long cost, long maxQueryPayment) { super(String.format( "cost of %s (%d) without explicit payment is greater than " + "Client.maxQueryPayment (%d)", builder.getClass().getSimpleName(), cost, maxQueryPayment)); } } }
34.953642
120
0.625047
217a693c40349abc17f34ecc949e2f2abc8785a9
3,017
package com.dengjintian.maven; import org.fusesource.jansi.Ansi; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Before content are sent to ansi, we do some extra filtering here. <br /> * User: jintian, Date: 31/12/12 */ public class FilterMavenOutputStream extends FilterOutputStream { private static int buffer_size = 1024; private static byte[] buffer = new byte[buffer_size]; private static int index = 0; public FilterMavenOutputStream(OutputStream outputStream){ super(outputStream); } public void write(int i) throws IOException { if (i == '\n' || i == '\r') { // wait until we get the whole line buffer[index++] = (byte) i; String line = new String(buffer); out.write(getColourfulByteForLine(line)); resetBuffer(); } else { buffer[index++] = (byte) i; if (index >= buffer_size) { enlargeBuffer(); } } } private byte[] getColourfulByteForLine(String line) { Ansi ansi = Ansi.ansi().reset(); if (line.startsWith("[INFO] -------") || (line.startsWith("[INFO] Building") && !line.contains(":")) || line.startsWith("[INFO] task-segment") || line.startsWith("[INFO] Total time:") || line.startsWith("[INFO] Finished at:") || line.startsWith("[INFO] Final Memory:")) { ansi.fgBright(Ansi.Color.MAGENTA); } else if (line.startsWith("[INFO] [")) { ansi.fg(Ansi.Color.CYAN).bold(); } else if (line.startsWith("[INFO] BUILD SUCCESSFUL")) { ansi.fgBright(Ansi.Color.GREEN).bold(); } else if (line.startsWith("[WARNING]")) { ansi.fgBright(Ansi.Color.YELLOW).bold(); } else if (line.startsWith("[ERROR]")) { ansi.fgBright(Ansi.Color.RED).bold(); } else if (line.startsWith("Tests run:")) { String[] tokens = line.split(":|,"); if (tokens.length == 8) { // be conservative ansi.fg(Ansi.Color.GREEN).a(tokens[0] + ":" + tokens[1]).reset().a(","); ansi.fg(Ansi.Color.GREEN).a(tokens[2] + ":").fg(Ansi.Color.RED).bold().a(tokens[3]).reset().a(",").reset(); ansi.fg(Ansi.Color.GREEN).a(tokens[4] + ":").fg(Ansi.Color.RED).bold().a(tokens[5]).reset().a(",").reset(); ansi.fg(Ansi.Color.GREEN).a(tokens[6] + ":").fg(Ansi.Color.YELLOW).bold().a(tokens[7]).reset(); line = ""; } } ansi.a(line).reset(); return ansi.toString().getBytes(); } private void resetBuffer() { buffer_size = 1024; index = 0; buffer = new byte[buffer_size]; } public void enlargeBuffer() { buffer_size = 2 * buffer_size; byte[] tmp = new byte[buffer_size]; System.arraycopy(buffer, 0, tmp, 0, buffer.length); buffer = tmp; } }
37.246914
123
0.552204
0767951babd837f82e490398dcca883ea89c3b49
7,628
package io.cresco.agent.controller.globalscheduler; import io.cresco.agent.controller.core.ControllerEngine; import io.cresco.library.app.gNode; import io.cresco.library.app.gPayload; import io.cresco.library.messaging.MsgEvent; import io.cresco.library.plugin.PluginBuilder; import io.cresco.library.utilities.CLogger; import java.util.ArrayList; import java.util.List; public class PollRemovePipeline implements Runnable { private ControllerEngine controllerEngine; private PluginBuilder plugin; private CLogger logger; private List<gNode> pipelineNodes; private String pipelineId; private gPayload gpay; public PollRemovePipeline(ControllerEngine controllerEngine, String pipelineId) { this.controllerEngine = controllerEngine; this.plugin = controllerEngine.getPluginBuilder(); this.logger = plugin.getLogger(PollRemovePipeline.class.getName(),CLogger.Level.Info); this.pipelineId = pipelineId; } public void run() { try { int pipelineStatus = controllerEngine.getGDB().getPipelineStatusCode(pipelineId); //if((pipelineStatus >= 10) && (pipelineStatus < 19)) { controllerEngine.getGDB().setPipelineStatus(pipelineId, "9", "Pipeline Scheduled for Removal"); gpay = controllerEngine.getGDB().getPipelineObj(pipelineId); if (pipelineId.equals(gpay.pipeline_id)) { pipelineNodes = new ArrayList<>(gpay.nodes); for (gNode gnode : pipelineNodes) { int statusCode = controllerEngine.getGDB().getINodeStatus(gnode.node_id); //if((statusCode >= 10) && (statusCode < 19)) { //running somewhere MsgEvent me = plugin.getGlobalControllerMsgEvent(MsgEvent.Type.CONFIG); me.setParam("globalcmd", "removeplugin"); me.setParam("inode_id", gnode.node_id); me.setParam("resource_id", pipelineId); controllerEngine.getGDB().setINodeStatusCode(gnode.node_id,9,"iNode Pipeline Scheduled for Removal"); //controllerEngine.getResourceScheduleQueue().add(me); controllerEngine.getResourceScheduler().incomingMessage(me); //} //else if(statusCode > 19) { // controllerEngine.getGDB().setINodeStatusCode(gnode.node_id,8,"iNode Disabled"); //} } //start watch loop List<gNode> errorList = new ArrayList<>(); boolean isScheduling = true; while(isScheduling) { List<gNode> checkList = new ArrayList<>(pipelineNodes); /* status_code = 3; //agentcontroller init status_code = 7; //Plugin instance could not be started status_code = 8; //agentcontroller disabled status_code = 9; //Plugin Bundle could not be installed or started status_code = 10; //started and working status_code = 40; //WATCHDOG check STALE status_code = 41; //Missing status parameter status_code = 50; //WATCHDOG check LOST status_code = 80; //failed to start status_code = 90; //Exception on timeout shutdown status_code = 91; //Exception on timeout verification to confirm down status_code = 92; //timeout on disable verification */ if(checkList.isEmpty()) { isScheduling = false; } for(gNode gnode : checkList) { int statusCode = controllerEngine.getGDB().getINodeStatus(gnode.node_id); if (statusCode != 9) { if(statusCode == 8) { logger.debug("8 PollRemovePipeline thread " + Thread.currentThread().getId() + " : " + gnode.node_id + " status_code: " + statusCode); pipelineNodes.remove(gnode); } else if(statusCode > 19) { errorList.add(gnode); pipelineNodes.remove(gnode); logger.error("19 PollRemovePipeline thread " + Thread.currentThread().getId() + " : " + gnode.node_id + " status_code: " + statusCode); } else { logger.error("Other PollRemovePipeline thread " + Thread.currentThread().getId() + " : " + gnode.node_id + " status_code: " + statusCode); pipelineNodes.remove(gnode); } } } /* for(gNode gnode : checkList) { int statusCode = controllerEngine.getGDB().getINodeStatus(gnode.node_id); if (statusCode != 10) { if(statusCode == 8) { logger.info("Info PollRemovePipeline thread " + Thread.currentThread().getId() + " : " + gnode.node_id + " status_code: " + statusCode); pipelineNodes.remove(gnode); } else { errorList.add(gnode); pipelineNodes.remove(gnode); logger.error("error PollRemovePipeline thread " + Thread.currentThread().getId() + " : " + gnode.node_id + " status_code: " + statusCode); } } else { logger.error("Status Code for Inode = " + gnode.node_id); } } */ Thread.sleep(500); } //end watch loop controllerEngine.getGDB().removePipeline(pipelineId); logger.debug("pipelineid " + pipelineId + " removed!"); /* if(errorList.isEmpty()) { controllerEngine.getGDB().removePipeline(pipelineId); logger.debug("pipelineid " + pipelineId + " removed!"); } else { controllerEngine.getGDB().setPipelineStatus(pipelineId, "80", "Pipeline Failed Removal"); logger.error("PipelineID: " + pipelineId + " Removal Failed!"); } */ } //} } catch(Exception ex) { logger.error("PollAddPipeline : " + ex.getMessage()); controllerEngine.getGDB().setPipelineStatus(pipelineId, "90", "Pipeline Failed Removal"); logger.error("PipelineID: " + pipelineId + " Removal Schedule Failed!"); } } }
48.278481
178
0.480205
5ae33d798dcab79a481578c3daf987fb9f9b9df7
288
package com.bloomhousemc.terrafabricraft.common.registry; import com.bloomhousemc.terrafabricraft.common.config.ModuleConfig; public final class TfcBiomes { public static void init() { //Not empty anymore ;)) if (ModuleConfig.getValue("world")) { } } }
22.153846
67
0.6875
9e0a8ca5dd4b8b03f13998a379cb9eb16bb6a5fd
6,174
package fr.guddy.androidstarteralt.mvp.repoList; import android.content.Context; import android.support.annotation.NonNull; import android.text.TextUtils; import com.birbit.android.jobqueue.JobManager; import com.hannesdorfmann.mosby.mvp.MvpBasePresenter; import com.novoda.merlin.MerlinsBeard; import com.orhanobut.hawk.Hawk; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import javax.inject.Inject; import autodagger.AutoInjector; import fr.guddy.androidstarteralt.ApplicationAndroidStarter; import fr.guddy.androidstarteralt.persistence.Preferences; import fr.guddy.androidstarteralt.persistence.entities.RepoEntity; import fr.guddy.androidstarteralt.rest.queries.QueryGetRepos; import hugo.weaving.DebugLog; import io.requery.Persistable; import io.requery.rx.SingleEntityStore; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; @AutoInjector(ApplicationAndroidStarter.class) public class PresenterRepoList extends MvpBasePresenter<RepoListMvp.View> implements RepoListMvp.Presenter { //region Injected fields @Inject Context context; @Inject EventBus eventBus; @Inject SingleEntityStore<Persistable> dataStore; @Inject MerlinsBeard merlinsBeard; @Inject JobManager jobManager; @Inject Preferences preferences; //endregion //region Fields private Subscription mSubscriptionGetRepos; //endregion //region Constructor public PresenterRepoList() { ApplicationAndroidStarter.sharedApplication().componentApplication().inject(this); } //endregion //region Overridden methods @Override public void attachView(final RepoListMvp.View poView) { super.attachView(poView); eventBus.register(this); } @Override public void detachView(final boolean pbRetainInstance) { super.detachView(pbRetainInstance); if (!pbRetainInstance) { unsubscribe(); } eventBus.unregister(this); } //endregion //region Specific job private void unsubscribe() { if (mSubscriptionGetRepos != null && !mSubscriptionGetRepos.isUnsubscribed()) { mSubscriptionGetRepos.unsubscribe(); } mSubscriptionGetRepos = null; } //endregion //region RepoListMvp.Presenter @Override public void loadRepos(final boolean pbPullToRefresh) { startQueryGetRepos(pbPullToRefresh); } //endregion //region Network job private void startQueryGetRepos(final boolean pbPullToRefresh) { final RepoListMvp.View loView = getView(); if (isViewAttached() && loView != null) { loView.showLoading(pbPullToRefresh); } // "standard" preferences if (TextUtils.isEmpty(preferences.getUsername())) { preferences.setUsername("RoRoche"); } // vs. Hawk if (!Hawk.contains("key_username")) { Hawk.put("key_username", "RoRoche"); } //final QueryGetRepos loQuery = new QueryGetRepos(preferences.getUsername(), pbPullToRefresh); final QueryGetRepos loQuery = new QueryGetRepos(Hawk.get("key_username"), pbPullToRefresh); // If query requires network, and if network is unreachable, and if the query must not persist if (loQuery.requiresNetwork() && !merlinsBeard.isConnected() && !loQuery.isPersistent()) { // then, we post an event to notify the job could not be done because of network connectivity loQuery.inject(); loQuery.postEventQueryFinishedNoNetwork(); } else { // otherwise, we can add the job jobManager.addJobInBackground(loQuery); } } //endregion //region Event management @DebugLog @Subscribe(threadMode = ThreadMode.MAIN) public void onEventQueryGetRepos(@NonNull final QueryGetRepos.EventQueryGetReposDidFinish poEvent) { if (poEvent.success) { getRepos(poEvent.pullToRefresh); } else { final RepoListMvp.View loView = getView(); if (isViewAttached() && loView != null) { loView.showError(poEvent.throwable, poEvent.pullToRefresh); } } } //endregion //region Reactive job private void getRepos(final boolean pbPullToRefresh) { unsubscribe(); final RepoListMvp.View loView = getView(); if (loView == null) { return; } final ArrayList<RepoEntity> lloRepos = new ArrayList<>(); mSubscriptionGetRepos = dataStore.select(RepoEntity.class) .get() .toObservable() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( // onNext (final RepoEntity poRepo) -> lloRepos.add(poRepo), // onError (final Throwable poException) -> { if (isViewAttached()) { loView.showError(poException, pbPullToRefresh); } unsubscribe(); }, // onCompleted () -> { if (isViewAttached()) { loView.setData(new RepoListMvp.Model(lloRepos)); if (lloRepos.isEmpty()) { loView.showEmpty(); } else { loView.showContent(); } } unsubscribe(); } ); } //endregion }
33.372973
109
0.588921
5ae150fd65ae5608caaee45cd4b423e8aca8bed2
125
package io.github.shirohoo.racing.app.domain; @FunctionalInterface public interface ForwardCondition { boolean get(); }
17.857143
45
0.784
926b576e38b3d2d6bb8879e8e7774cc5a8e9650d
4,487
/* * Copyright 2016-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.roadm; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.ImmutableSet; import org.onlab.osgi.ServiceDirectory; import org.onosproject.mastership.MastershipService; import org.onosproject.net.AnnotationKeys; import org.onosproject.net.Device; import org.onosproject.net.DeviceId; import org.onosproject.net.device.DeviceService; import org.onosproject.ui.RequestHandler; import org.onosproject.ui.UiConnection; import org.onosproject.ui.UiMessageHandler; import org.onosproject.ui.table.TableModel; import org.onosproject.ui.table.TableRequestHandler; import java.util.Collection; import static org.onosproject.net.Device.Type; /** * Table-View message handler for ROADM device view. */ public class RoadmDeviceViewMessageHandler extends UiMessageHandler { private static final String ROADM_DEVICE_DATA_REQ = "roadmDeviceDataRequest"; private static final String ROADM_DEVICE_DATA_RESP = "roadmDeviceDataResponse"; private static final String ROADM_DEVICES = "roadmDevices"; private static final String ID = "id"; private static final String NAME = "name"; private static final String TYPE = "type"; private static final String MASTER = "master"; private static final String PORTS = "ports"; private static final String VENDOR = "vendor"; private static final String HW_VERSION = "hwVersion"; private static final String SW_VERSION = "swVersion"; private static final String PROTOCOL = "protocol"; private static final String[] COLUMN_IDS = { ID, NAME, TYPE, MASTER, PORTS, VENDOR, HW_VERSION, SW_VERSION, PROTOCOL }; private DeviceService deviceService; private MastershipService mastershipService; @Override public void init(UiConnection connection, ServiceDirectory directory) { super.init(connection, directory); deviceService = get(DeviceService.class); mastershipService = get(MastershipService.class); } @Override protected Collection<RequestHandler> createRequestHandlers() { return ImmutableSet.of(new DeviceTableDataRequestHandler()); } // Handler for sample table requests private final class DeviceTableDataRequestHandler extends TableRequestHandler { private DeviceTableDataRequestHandler() { super(ROADM_DEVICE_DATA_REQ, ROADM_DEVICE_DATA_RESP, ROADM_DEVICES); } @Override protected String[] getColumnIds() { return COLUMN_IDS; } @Override protected String noRowsMessage(ObjectNode payload) { return RoadmUtil.NO_ROWS_MESSAGE; } @Override protected void populateTable(TableModel tm, ObjectNode payload) { for (Device device : deviceService.getDevices()) { Type type = device.type(); if (type == Type.ROADM || type == Type.OPTICAL_AMPLIFIER || type == Type.FIBER_SWITCH) { populateRow(tm.addRow(), device); } } } private void populateRow(TableModel.Row row, Device device) { DeviceId devId = device.id(); String id = devId.toString(); row.cell(ID, id) .cell(NAME, RoadmUtil.getAnnotation(device.annotations(), AnnotationKeys.NAME, id)) .cell(TYPE, RoadmUtil.objectToString(device.type(), RoadmUtil.UNKNOWN)) .cell(MASTER, mastershipService.getMasterFor(devId)) .cell(PORTS, deviceService.getPorts(devId).size()) .cell(VENDOR, device.manufacturer()) .cell(HW_VERSION, device.hwVersion()) .cell(SW_VERSION, device.swVersion()) .cell(PROTOCOL, RoadmUtil.getAnnotation(device.annotations(), PROTOCOL)); } } }
38.681034
104
0.691108
26a90f3a975e9644ce63f9655136938a9e61686f
741
package com.atlassian.plugin.connect.modules.beans.builder; import com.atlassian.plugin.connect.modules.beans.nested.VendorBean; /** * @since 1.0 */ @SuppressWarnings("unchecked") public class VendorBeanBuilder { private String name; private String url; public VendorBeanBuilder() { } public VendorBeanBuilder(VendorBean defaultBean) { this.name = defaultBean.getName(); this.url = defaultBean.getUrl(); } public VendorBeanBuilder withName(String name) { this.name = name; return this; } public VendorBeanBuilder withUrl(String url) { this.url = url; return this; } public VendorBean build() { return new VendorBean(this); } }
20.583333
68
0.65587
aabfa6e6df57433afc8ecad015eee5da35964c21
639
package com.menros.echoplus.services.mongodbService.repository; import com.menros.echoplus.services.mongodbService.collection.DBProject; import com.menros.echoplus.services.mongodbService.repositoryCustom.DBProjectRepositoryCustom; import org.bson.types.ObjectId; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import java.util.List; public interface DBProjectRepository extends MongoRepository<DBProject, ObjectId>, DBProjectRepositoryCustom { @Query(value = "{ 'refPackage' : ?0 }") public List<DBProject> findByRefPackage(ObjectId refPackage); }
42.6
110
0.832551
55e31b62030b6027b24a279dd602f82fc19ab9f9
1,475
package io.ebean.xtest.base; import io.ebean.OrderBy; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class PropertyTest { @Test public void equals() throws Exception { Assertions.assertEquals(prop("foo", true), prop("foo", true)); } @Test public void diff_basic() throws Exception { Assertions.assertNotEquals(prop("foo", true), prop("bar", true)); Assertions.assertNotEquals(prop("foo", true), prop("foo", false)); Assertions.assertNotEquals(prop("foo", false), prop("foo", true)); } @Test public void diff_nulls() throws Exception { Assertions.assertEquals(prop("foo", true, "nulls", "high"), prop("foo", true, "nulls", "high")); Assertions.assertEquals(prop("foo", true, "nulls", "low"), prop("foo", true, "nulls", "low")); Assertions.assertNotEquals(prop("foo", true), prop("foo", true, "nulls", "high")); Assertions.assertNotEquals(prop("foo", true, "nulls", "high"), prop("foo", true)); Assertions.assertNotEquals(prop("foo", true, "nulls", "high"), prop("foo", true, "nulls", "low")); Assertions.assertNotEquals(prop("foo", true, "nulls", "low"), prop("foo", true, "nulls", "high")); } private OrderBy.Property prop(String name, boolean asc) { return new OrderBy.Property(name, asc, null, null); } private OrderBy.Property prop(String name, boolean asc, String nulls, String highLow) { return new OrderBy.Property(name, asc, nulls, highLow); } }
33.522727
102
0.669831
55cf93a5f39069f14b42fbea5d73be1231e4772d
1,254
package me.loveshare; import lombok.extern.slf4j.Slf4j; import me.loveshare.gateway.gateway.AccessFilter; import org.springframework.boot.SpringApplication; import org.springframework.cloud.client.SpringCloudApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; /** * Created by Tony on 2017/3/10. * * @EnableZuulProxy注解激活zuul。 该注解整合了@EnableCircuitBreaker、@EnableDiscoveryClient,是个组合注解,目的是简化配置。 */ @Slf4j @EnableZuulProxy @SpringCloudApplication public class ServiceGatewayApplication { @Bean public AccessFilter accessFilter() { return new AccessFilter(); } // http://192.168.1.119:1304/api-a/member/list2.json //log: access token is empty // http://192.168.1.119:1304/api-a/member/list2.json?accessToken=token //log: access token ok // http://192.168.1.119:1304/api-a/member/list2.json?code=KWY987654&name=%E5%8D%A1%E5%93%87%E4%BC%8A&id=123&accessToken=token //加载的数据 public static void main(String[] args) { SpringApplication.run(ServiceGatewayApplication.class, args); log.info("\n--------------------------------Spring cloud microservices gateway start successful.--------------------------------\n"); } }
36.882353
141
0.712121
74eea765dc3244f88613554839edebf4529bfb8f
1,127
package cn.ffcs.external.share.entity; import java.io.Serializable; import android.graphics.Bitmap; /** * <p>Title: 分享实体 </p> * <p>Description: * * </p> * <p>@author: Leo </p> * <p>Copyright: Copyright (c) 2013 </p> * <p>Company: FFCS Co., Ltd. </p> * <p>Create Time: 2013-11-18 </p> * <p>Update Time: </p> * <p>Updater: </p> * <p>Update Comments: </p> */ public class CustomSocialShareEntity implements Serializable { public static final long serialVersionUID = 1L; public String shareTitle;//分享标题:微信和易信的标题 public String shareComment;//分享描述:微信和易信的内容 public String shareSource;// 分享来源,作用:可以表示友盟分享的来源,也可以表示摄像头名字 public String shareUrl;// 分享地址 public String shareContent;// 分享内容 public byte[] imageByte;// 分享图片 public Bitmap imageBitmap;//分享图片 public String imagePath;// 图片地址,随手拍截图的全地址 public String imageUrl; public String shareType;// 分享类型,1:路况;2:景点 public String cityCode;// 城市编号 public String mobile;//手机号码 public boolean isShowPhoto;//是否显示,用于关闭随手拍分享入口 public String spreadCode;//邀请码 }
29.657895
62
0.647737
f2e237dc11798954254c08e759332852826f413f
444
package be.degreyt.libra.rules; import be.degreyt.libra.parsers.BankAccountNumber; import be.degreyt.libra.time.Day; import java.math.BigDecimal; import java.util.Currency; public interface BankTransactionData { String transactionNumber(); Day executionDay(); Day currencyDay(); BigDecimal amount(); Currency currency(); String otherParty(); String details(); BankAccountNumber bankAccountNumber(); }
16.444444
50
0.72973
3716943a8e36afb99e08b357130084fbe104618b
2,564
package game_objects.territories; /* * csc413-tankgame-Belmeurrr * Created by Daniel * Created on 7/13/2019 2019 @ 9:52 PM */ import game_objects.Constants; import game_objects.continents.Asia; import java.awt.*; import java.util.ArrayList; public class Mongolia extends Territory { @Override public ArrayList getConnectedTerritories() { return connectedTerritories; } @Override public void setReigon() { polygon.addPoint(1697, 308); polygon.addPoint(1684, 311); polygon.addPoint(1680, 306); polygon.addPoint(1667, 310); polygon.addPoint(1663, 306); polygon.addPoint(1655, 307); polygon.addPoint(1654, 304); polygon.addPoint(1636, 304); polygon.addPoint(1616, 295); polygon.addPoint(1604, 277); polygon.addPoint(1604, 273); polygon.addPoint(1595, 267); polygon.addPoint(1602, 266); polygon.addPoint(1603, 235); polygon.addPoint(1616, 237); polygon.addPoint(1629, 238); polygon.addPoint(1652, 241); polygon.addPoint(1659, 238); polygon.addPoint(1663, 238); polygon.addPoint(1667, 233); polygon.addPoint(1673, 238); polygon.addPoint(1681, 232); polygon.addPoint(1680, 225); polygon.addPoint(1682, 220); polygon.addPoint(1683, 210); polygon.addPoint(1702, 209); polygon.addPoint(1703, 214); polygon.addPoint(1720, 231); polygon.addPoint(1728, 232); polygon.addPoint(1726, 242); polygon.addPoint(1748, 261); polygon.addPoint(1744, 282); polygon.addPoint(1758, 297); polygon.addPoint(1744, 310); polygon.addPoint(1744, 300); polygon.addPoint(1735, 300); polygon.addPoint(1721, 315); //System.out.println("Polygon Created"); } @Override public void setConnectedTerritories() { connectedTerritories.add(Constants.territoriesArrayList.get(23)); //China connectedTerritories.add(Constants.territoriesArrayList.get(16)); //Siberia connectedTerritories.add(Constants.territoriesArrayList.get(21)); //Irkutsk connectedTerritories.add(Constants.territoriesArrayList.get(19)); //Kamchatka connectedTerritories.add(Constants.territoriesArrayList.get(20)); //Japan } @Override public Polygon getPolygon() { return polygon; } @Override public void setContinent() { homeContinent = Constants.continentArrayList.get(1); } }
30.164706
87
0.640796
fff992923d6d4f69bf8ddc5c55e9f15597f4d960
1,509
package com.bn.Sample7_6; import javax.vecmath.Vector3f; import com.bulletphysics.collision.shapes.CollisionShape; import com.bulletphysics.dynamics.DiscreteDynamicsWorld; import com.bulletphysics.dynamics.RigidBody; import com.bulletphysics.dynamics.RigidBodyConstructionInfo; import com.bulletphysics.linearmath.DefaultMotionState; import com.bulletphysics.linearmath.Transform; public class RigidBodyHelper { RigidBody body; boolean noGravity; public RigidBodyHelper(CollisionShape shape,float mass,DiscreteDynamicsWorld dynamicsWorld, float restitution,float friction,Vector3f origin,boolean noGravity){ this.noGravity=noGravity; boolean isDynamic = (mass!=0); Vector3f localInertia = new Vector3f(0,0,0); if(isDynamic){ shape.calculateLocalInertia(mass, localInertia); } //创建刚体的初始变换对象 Transform groundTransform = new Transform(); groundTransform.setIdentity(); groundTransform.origin.set(origin); //创建刚体的运动状态对象 DefaultMotionState myMotionState = new DefaultMotionState(groundTransform); //创建刚体信息对象 RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia); //创建刚体 body = new RigidBody(rbInfo); //设置反弹系数 body.setRestitution(restitution); //设置摩擦系数 body.setFriction(friction); //将刚体添加进物理世界 //bullet是在add刚体的时候为刚体设置其重力的 dynamicsWorld.addRigidBody(body); //一定要在add刚体之后再从新设置重力才能将原重力覆盖 if(noGravity){ body.setGravity(new Vector3f(0,0,0)); } } }
32.106383
110
0.770046
4381308e8c3474a108dc44d6c0ce2da4d3b52775
7,516
package com.fasterxml.jackson.databind.jsontype; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Objects; // For [databind#2978] public class TestDoubleJsonCreator extends BaseMapTest { static final class UnionExample { private final Base value; @JsonCreator(mode = JsonCreator.Mode.DELEGATING) private UnionExample(Base value) { this.value = value; } @JsonValue private Base getValue() { return value; } public static UnionExample double_(AliasDouble value) { return new UnionExample(new DoubleWrapper(value)); } public <T> T accept(Visitor<T> visitor) { return value.accept(visitor); } @Override public boolean equals(Object other) { return this == other || (other instanceof UnionExample && equalTo((UnionExample) other)); } private boolean equalTo(UnionExample other) { return this.value.equals(other.value); } @Override public int hashCode() { return Objects.hashCode(this.value); } @Override public String toString() { return "UnionExample{value: " + value + '}'; } public interface Visitor<T> { T visitDouble(AliasDouble value); T visitUnknown(String unknownType); } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", visible = true, defaultImpl = UnknownWrapper.class) @JsonSubTypes(@JsonSubTypes.Type(UnionExample.DoubleWrapper.class)) @JsonIgnoreProperties(ignoreUnknown = true) private interface Base { <T> T accept(Visitor<T> visitor); } @JsonTypeName("double") private static final class DoubleWrapper implements Base { private final AliasDouble value; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) DoubleWrapper(@JsonSetter("double") AliasDouble value) { Objects.requireNonNull(value, "double cannot be null"); this.value = value; } @JsonProperty("double") private AliasDouble getValue() { return value; } @Override public <T> T accept(Visitor<T> visitor) { return visitor.visitDouble(value); } @Override public boolean equals(Object other) { return this == other || (other instanceof DoubleWrapper && equalTo((DoubleWrapper) other)); } private boolean equalTo(DoubleWrapper other) { return this.value.equals(other.value); } @Override public int hashCode() { return Objects.hashCode(this.value); } @Override public String toString() { return "DoubleWrapper{value: " + value + '}'; } } @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type", visible = true) private static final class UnknownWrapper implements Base { private final String type; private final Map<String, Object> value; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) private UnknownWrapper(@JsonProperty("type") String type) { this(type, new HashMap<String, Object>()); } private UnknownWrapper(String type, Map<String, Object> value) { Objects.requireNonNull(type, "type cannot be null"); Objects.requireNonNull(value, "value cannot be null"); this.type = type; this.value = value; } @JsonProperty private String getType() { return type; } @JsonAnyGetter private Map<String, Object> getValue() { return value; } @JsonAnySetter private void put(String key, Object val) { value.put(key, val); } @Override public <T> T accept(Visitor<T> visitor) { return visitor.visitUnknown(type); } @Override public boolean equals(Object other) { return this == other || (other instanceof UnknownWrapper && equalTo((UnknownWrapper) other)); } private boolean equalTo(UnknownWrapper other) { return this.type.equals(other.type) && this.value.equals(other.value); } @Override public int hashCode() { return Objects.hash(this.type, this.value); } @Override public String toString() { return "UnknownWrapper{type: " + type + ", value: " + value + '}'; } } } static final class AliasDouble { private final double value; private AliasDouble(double value) { this.value = value; } @JsonValue public double get() { return value; } @Override public String toString() { return String.valueOf(value); } @Override public boolean equals(Object other) { return this == other || (other instanceof AliasDouble && Double.doubleToLongBits(this.value) == Double.doubleToLongBits(((AliasDouble) other).value)); } @Override public int hashCode() { return Objects.hashCode(value); } @JsonCreator(mode = JsonCreator.Mode.DELEGATING) public static AliasDouble of(double value) { return new AliasDouble(value); } } private final ObjectMapper MAPPER = newJsonMapper(); // [databind#2978] public void testDeserializationTypeFieldLast() throws IOException { UnionExample expected = UnionExample.double_(AliasDouble.of(2.0D)); UnionExample actual = MAPPER.readValue( a2q("{'double': 2.0,'type':'double'}"), new TypeReference<UnionExample>() {}); assertEquals(expected, actual); } // [databind#2978] public void testDeserializationTypeFieldFirst() throws IOException { UnionExample expected = UnionExample.double_(AliasDouble.of(2.0D)); UnionExample actual = MAPPER.readValue( a2q("{'type':'double','double': 2.0}"), new TypeReference<UnionExample>() {}); assertEquals(expected, actual); } }
31.847458
120
0.581293
365212d9b265844c66bb3873c8ba9e92f3cbbbe9
815
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.db; import javax.inject.Inject; import javax.inject.Singleton; import javax.sql.DataSource; import play.Configuration; /** * Default delegating implementation of the connection pool API. */ @Singleton public class DefaultConnectionPool implements ConnectionPool { private final play.api.db.ConnectionPool cp; @Inject public DefaultConnectionPool(play.api.db.ConnectionPool connectionPool) { this.cp = connectionPool; } public DataSource create(String name, Configuration configuration, ClassLoader classLoader) { return cp.create(name, configuration.getWrappedConfiguration(), classLoader); } public void close(DataSource dataSource) { cp.close(dataSource); } }
23.970588
97
0.733742
4652420323473ae3481224fe8a67722492c02a81
4,710
package alien4cloud.paas.wf.util; import java.util.Map; import alien4cloud.model.components.Interface; import alien4cloud.paas.model.PaaSNodeTemplate; import alien4cloud.paas.wf.AbstractStep; import alien4cloud.paas.wf.NodeActivityStep; import alien4cloud.paas.wf.SetStateActivity; import alien4cloud.paas.wf.Workflow; import alien4cloud.tosca.normative.NormativeComputeConstants; public class WorkflowUtils { private static final String NETWORK_TYPE = "tosca.nodes.Network"; public static Interface getNodeInterface(PaaSNodeTemplate nodeTemplate, String interfaceName) { Interface interfaz = getInterface(interfaceName, nodeTemplate.getIndexedToscaElement().getInterfaces()); if (interfaz == null) { throw new IllegalArgumentException("Plan cannot be generated as required interface <" + interfaceName + "> has not been found on node <" + nodeTemplate.getNodeTemplate().getName() + "> from type <" + nodeTemplate.getNodeTemplate().getType() + ">."); } return interfaz; } public static Interface getInterface(String interfaceName, Map<String, Interface> interfaces) { return interfaces == null ? null : interfaces.get(interfaceName); } public static boolean isCompute(PaaSNodeTemplate paaSNodeTemplate) { return isOfType(paaSNodeTemplate, NormativeComputeConstants.COMPUTE_TYPE); } public static boolean isNetwork(PaaSNodeTemplate paaSNodeTemplate) { return isOfType(paaSNodeTemplate, NETWORK_TYPE); } private static boolean isOfType(PaaSNodeTemplate paaSNodeTemplate, String type) { return paaSNodeTemplate.getIndexedToscaElement().getElementId().equals(type) || paaSNodeTemplate.getIndexedToscaElement().getDerivedFrom() != null && paaSNodeTemplate.getIndexedToscaElement().getDerivedFrom().contains(type); } public static void linkSteps(AbstractStep from, AbstractStep to) { if (from != null && to != null) { from.addFollowing(to.getName()); to.addPreceding(from.getName()); } } public static String buildStepName(Workflow wf, NodeActivityStep step, int increment) { StringBuilder nameBuilder = new StringBuilder(step.getStepAsString()); if (increment > 0) { nameBuilder.append("_").append(increment); } String name = nameBuilder.toString(); if (wf.getSteps().containsKey(name)) { return buildStepName(wf, step, ++increment); } else { return name; } } public static boolean isStateStep(AbstractStep step) { return (step instanceof NodeActivityStep) && ((NodeActivityStep) step).getActivity() instanceof SetStateActivity; } public static String debugWorkflow(Workflow wf) { StringBuilder stringBuilder = new StringBuilder("\n ======> Paste the folowing graph in http://www.webgraphviz.com/ !!\n"); int subgraphCount = 0; stringBuilder.append("\ndigraph ").append(wf.getName()).append(" {"); stringBuilder.append("\n node [shape=box];"); for (String host : wf.getHosts()) { stringBuilder.append("\n subgraph cluster_").append(++subgraphCount).append(" {"); stringBuilder.append("\n label = \"").append(host).append("\";\n color=blue;"); for (AbstractStep step : wf.getSteps().values()) { if (step instanceof NodeActivityStep && host.equals(((NodeActivityStep) step).getHostId())) { stringBuilder.append("\n \"").append(step.getName()).append("\";"); } } stringBuilder.append("\n }\n"); } for (AbstractStep step : wf.getSteps().values()) { if (step.getFollowingSteps() != null) { for (String following : step.getFollowingSteps()) { stringBuilder.append("\n \"").append(step.getName()).append("\" -> \"").append(following).append("\";"); } } if (step.getFollowingSteps() == null || step.getFollowingSteps().isEmpty()) { stringBuilder.append("\n \"").append(step.getName()).append("\" -> end;"); } if (step.getPrecedingSteps() == null || step.getPrecedingSteps().isEmpty()) { stringBuilder.append("\n start -> \"").append(step.getName()).append("\";"); } } stringBuilder.append("\n start [shape=doublecircle];\n"); stringBuilder.append(" end [shape=circle];\n"); stringBuilder.append("}\n"); stringBuilder.append("======================\n"); return stringBuilder.toString(); } }
45.288462
154
0.634395
67bec4652b7ca0db32a08ef010e41b878a5bb434
1,021
package ru.stqa.pft.test.pages; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.Wait; import org.openqa.selenium.support.ui.WebDriverWait; public class Page { protected WebDriver driver; protected WebDriverWait wait; public Page(WebDriver driver) { this.driver = driver; wait = new WebDriverWait(driver, 10); } public boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } } public void select(By locator, String name, By xpath) { new Select(driver.findElement(locator)).selectByVisibleText(name); click(xpath); } public void click(By locator) { driver.findElement(locator).click(); } }
27.594595
74
0.680705
3852ec38a36785d85a9a371f968fa864e8b53b17
1,118
/* * configuration * * Copyright (c) 2021 Synopsys, Inc. * * Use subject to the terms and conditions of the Synopsys End User Software License and Maintenance Agreement. All rights reserved worldwide. */ package com.synopsys.integration.configuration.config.resolution; import org.jetbrains.annotations.NotNull; import org.springframework.util.Assert; public class PropertyResolutionInfo { @NotNull private String source; @NotNull private String origin; @NotNull private String raw; public PropertyResolutionInfo(@NotNull final String source, @NotNull final String origin, @NotNull final String raw) { Assert.notNull(source, "Source cannot be null."); Assert.notNull(origin, "Origin cannot be null."); Assert.notNull(raw, "Raw cannot be null."); this.source = source; this.origin = origin; this.raw = raw; } @NotNull public String getSource() { return source; } @NotNull public String getOrigin() { return origin; } @NotNull public String getRaw() { return raw; } }
24.844444
142
0.669946
9c668a9f7efcea6402db381abedd6126f8926b25
11,816
package com.github.groupon.monsoon.tcp; import com.groupon.lex.metrics.GroupName; import com.groupon.lex.metrics.MetricGroup; import com.groupon.lex.metrics.MetricName; import com.groupon.lex.metrics.MetricValue; import com.groupon.lex.metrics.SimpleGroupPath; import com.groupon.lex.metrics.Tags; import java.io.IOException; import java.net.BindException; import java.net.ConnectException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NoRouteToHostException; import java.net.PortUnreachableException; import java.net.ProtocolException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.net.UnknownServiceException; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Collection; import static java.util.Collections.singletonMap; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasProperty; import org.junit.After; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import static org.mockito.Mockito.times; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class TcpCollectorTest { private static final GroupName GROUP = GroupName.valueOf(SimpleGroupPath.valueOf("test"), Tags.valueOf(singletonMap("foo", MetricValue.fromStrValue("bar")))); private ServerSocketChannel dstSocket; private InetSocketAddress dstAddress; private ExecutorService acceptor; @Mock private SocketChannel mockSocket; @Before public void setup() throws Exception { dstSocket = ServerSocketChannel.open(); dstSocket.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 1); dstAddress = (InetSocketAddress) dstSocket.getLocalAddress(); acceptor = Executors.newSingleThreadExecutor(); } @After public void cleanup() throws Exception { dstSocket.close(); acceptor.shutdown(); } @Test(timeout = 20000) public void connectOk() throws Exception { CompletableFuture<SocketChannel> accepted = new CompletableFuture<>(); acceptor.submit(() -> { try { accepted.complete(dstSocket.accept()); } catch (Exception ex) { accepted.completeExceptionally(ex); } }); final Collection<MetricGroup> collected; try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) { collected = tcpCollector.getGroups(new CompletableFuture<>()); } assertThat(collected, contains( allOf( hasProperty("name", equalTo(GROUP)), hasProperty("metrics", arrayContainingInAnyOrder( allOf(hasProperty("name", equalTo(MetricName.valueOf("up"))), hasProperty("value", equalTo(MetricValue.TRUE))), allOf(hasProperty("name", equalTo(MetricName.valueOf("latency")))), allOf(hasProperty("name", equalTo(MetricName.valueOf("error", "msg"))), hasProperty("value", equalTo(MetricValue.EMPTY))), allOf(hasProperty("name", equalTo(MetricName.valueOf("error", "type"))), hasProperty("value", equalTo(MetricValue.fromStrValue(TcpCollector.ConnectResult.OK.toString())))), allOf(hasProperty("name", equalTo(MetricName.valueOf("error", "timed_out"))), hasProperty("value", equalTo(MetricValue.FALSE))), allOf(hasProperty("name", equalTo(MetricName.valueOf("error", "no_route_to_host"))), hasProperty("value", equalTo(MetricValue.FALSE))), allOf(hasProperty("name", equalTo(MetricName.valueOf("error", "port_unreachable"))), hasProperty("value", equalTo(MetricValue.FALSE))), allOf(hasProperty("name", equalTo(MetricName.valueOf("error", "unknown_host"))), hasProperty("value", equalTo(MetricValue.FALSE))), allOf(hasProperty("name", equalTo(MetricName.valueOf("error", "unknown_service"))), hasProperty("value", equalTo(MetricValue.FALSE))), allOf(hasProperty("name", equalTo(MetricName.valueOf("error", "connect_failed"))), hasProperty("value", equalTo(MetricValue.FALSE))), allOf(hasProperty("name", equalTo(MetricName.valueOf("error", "protocol_error"))), hasProperty("value", equalTo(MetricValue.FALSE))), allOf(hasProperty("name", equalTo(MetricName.valueOf("error", "bind_failed"))), hasProperty("value", equalTo(MetricValue.FALSE))), allOf(hasProperty("name", equalTo(MetricName.valueOf("error", "io_error"))), hasProperty("value", equalTo(MetricValue.FALSE))) )) ))); assertTrue(accepted.get().isOpen()); accepted.get().close(); } @Test public void connectTimeout() throws Exception { Mockito.doThrow(new SocketTimeoutException()).when(mockSocket).connect(Mockito.any()); final TcpCollector.ConnectDatum result; try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) { result = tcpCollector.tryConnect(mockSocket); } assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.TIMED_OUT)); Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress)); Mockito.verifyNoMoreInteractions(mockSocket); } @Test public void connectNoRouteToHost() throws Exception { Mockito.doThrow(new NoRouteToHostException()).when(mockSocket).connect(Mockito.any()); final TcpCollector.ConnectDatum result; try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) { result = tcpCollector.tryConnect(mockSocket); } assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.NO_ROUTE_TO_HOST)); Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress)); Mockito.verifyNoMoreInteractions(mockSocket); } @Test public void connectPortUnreachable() throws Exception { Mockito.doThrow(new PortUnreachableException()).when(mockSocket).connect(Mockito.any()); final TcpCollector.ConnectDatum result; try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) { result = tcpCollector.tryConnect(mockSocket); } assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.PORT_UNREACHABLE)); Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress)); Mockito.verifyNoMoreInteractions(mockSocket); } @Test public void connectUnknownHost() throws Exception { Mockito.doThrow(new UnknownHostException()).when(mockSocket).connect(Mockito.any()); final TcpCollector.ConnectDatum result; try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) { result = tcpCollector.tryConnect(mockSocket); } assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.UNKNOWN_HOST)); Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress)); Mockito.verifyNoMoreInteractions(mockSocket); } @Test public void connectServiceError() throws Exception { Mockito.doThrow(new UnknownServiceException()).when(mockSocket).connect(Mockito.any()); final TcpCollector.ConnectDatum result; try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) { result = tcpCollector.tryConnect(mockSocket); } assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.UNKNOWN_SERVICE)); Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress)); Mockito.verifyNoMoreInteractions(mockSocket); } @Test public void connectProtocolError() throws Exception { Mockito.doThrow(new ProtocolException()).when(mockSocket).connect(Mockito.any()); final TcpCollector.ConnectDatum result; try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) { result = tcpCollector.tryConnect(mockSocket); } assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.PROTOCOL_ERROR)); Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress)); Mockito.verifyNoMoreInteractions(mockSocket); } @Test public void connectBindFailed() throws Exception { Mockito.doThrow(new BindException()).when(mockSocket).connect(Mockito.any()); final TcpCollector.ConnectDatum result; try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) { result = tcpCollector.tryConnect(mockSocket); } assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.BIND_FAILED)); Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress)); Mockito.verifyNoMoreInteractions(mockSocket); } @Test public void connectFailed_withSocketException() throws Exception { Mockito.doThrow(new SocketException()).when(mockSocket).connect(Mockito.any()); final TcpCollector.ConnectDatum result; try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) { result = tcpCollector.tryConnect(mockSocket); } assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.CONNECT_FAILED)); Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress)); Mockito.verifyNoMoreInteractions(mockSocket); } @Test public void connectFailed_withConnectException() throws Exception { Mockito.doThrow(new ConnectException()).when(mockSocket).connect(Mockito.any()); final TcpCollector.ConnectDatum result; try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) { result = tcpCollector.tryConnect(mockSocket); } assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.CONNECT_FAILED)); Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress)); Mockito.verifyNoMoreInteractions(mockSocket); } @Test public void anythingWeMissed() throws Exception { Mockito.doThrow(new IOException()).when(mockSocket).connect(Mockito.any()); final TcpCollector.ConnectDatum result; try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) { result = tcpCollector.tryConnect(mockSocket); } assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.IO_ERROR)); Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress)); Mockito.verifyNoMoreInteractions(mockSocket); } }
45.621622
162
0.663676
072cdd63f767cbdfdedd04019fbbe7b2c6c61f2c
130
package net.qldarch.hibernate; import org.hibernate.Session; public interface HVoidWork { public void run(Session session); }
16.25
35
0.784615
35a0cd7a85a41be6ec03e81bc71d659b365d89ed
2,085
/* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ package com.amazon.dataprepper.plugins.source.compression; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.ResponseInputStream; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.UUID; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import static org.hamcrest.CoreMatchers.instanceOf; import static org.mockito.Mockito.mock; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; class GZipCompressionEngineTest { private CompressionEngine compressionEngine; private ResponseInputStream<GetObjectResponse> responseInputStream; private String s3Key; @BeforeEach void setUp() { s3Key = UUID.randomUUID().toString(); responseInputStream = mock(ResponseInputStream.class); } @Test void createInputStream_with_gzip_should_return_instance_of_GZIPInputStream() throws IOException { compressionEngine = new GZipCompressionEngine(); final String testString = UUID.randomUUID().toString(); final byte[] testStringBytes = testString.getBytes(StandardCharsets.UTF_8); final ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); final GZIPOutputStream gzipOut = new GZIPOutputStream(byteOut); gzipOut.write(testStringBytes, 0, testStringBytes.length); gzipOut.close(); final byte[] bites = byteOut.toByteArray(); final ByteArrayInputStream byteInStream = new ByteArrayInputStream(bites); final InputStream inputStream = compressionEngine.createInputStream(s3Key, byteInStream); assertThat(inputStream, instanceOf(GZIPInputStream.class)); assertThat(inputStream.readAllBytes(), equalTo(testStringBytes)); } }
35.948276
101
0.772182
3646426df5cc983571c3203636968220e734a91a
1,657
package org.infinispan.server.functional; import static org.infinispan.commons.test.Eventually.eventually; import static org.infinispan.server.functional.ShutdownRestIT.isServerShutdown; import static org.infinispan.server.test.core.Common.sync; import java.util.concurrent.CompletionStage; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.server.test.junit4.InfinispanServerRule; import org.infinispan.server.test.junit4.InfinispanServerRuleBuilder; import org.infinispan.server.test.junit4.InfinispanServerTestMethodRule; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; /** * @since 10.1 */ public class ConcurrentShutdownRestIT { @ClassRule public static final InfinispanServerRule SERVER = InfinispanServerRuleBuilder.config("configuration/ClusteredServerTest.xml") .numServers(2) .build(); @Rule public InfinispanServerTestMethodRule SERVER_TEST = new InfinispanServerTestMethodRule(SERVER); @Test public void testShutDown() { RestClient client0 = SERVER_TEST.rest().create(); RestClient client1 = SERVER_TEST.rest().get(1); CompletionStage<RestResponse> stop0 = client0.server().stop(); CompletionStage<RestResponse> stop1 = client1.server().stop(); sync(stop0); sync(stop1); eventually(() -> isServerShutdown(client0)); eventually(() -> isServerShutdown(client1)); eventually(() -> !SERVER.getServerDriver().isRunning(0)); eventually(() -> !SERVER.getServerDriver().isRunning(1)); } }
35.255319
98
0.727218
5a7b82981f3b39ba54f752e0564756dcf9109255
1,004
package com.test.assignment.model; import javax.persistence.*; @Entity @Table(name = "car") public class Car { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "model") private String model; @Column(name = "license_plate") private String licensePlate; @Column(name = "passenger_num") private Integer passengerNum; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getLicensePlate() { return licensePlate; } public void setLicensePlate(String licensePlate) { this.licensePlate = licensePlate; } public Integer getPassengerNum() { return passengerNum; } public void setPassengerNum(Integer passengerNum) { this.passengerNum = passengerNum; } }
18.943396
55
0.629482
f4ee94e86496941fabb97aa19699abbabb10b70f
6,393
package eco.ui; import eco.game.Main; import eco.game.SaveTask; import eco.game.ThreadManager; import eco.game.World; import eco.render.Camera; import eco.render.Render; import eco.render.RenderUtil; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; /** * A collection of various implementations of IInputManager * * @author phil */ public final class InputManager { public static final IInputManager gameInput = new IInputManager() { @Override public void run(int keycode) { switch (keycode){ case Keyboard.KEY_Q: Render.camera = new Camera(-World.mapsize / 2f * Render.tilesize, -4f, World.mapsize / 2f * Render.tilesize); Log.info("Reset camera to default location"); break; case Keyboard.KEY_GRAVE: case Keyboard.KEY_TAB: IGConsole.consoleLoop(); break; case Keyboard.KEY_ESCAPE: Main.paused ^= true; if (Main.paused) { ThreadManager.addJob(new SaveTask()); } break; case Keyboard.KEY_F10: RenderUtil.takeScreenshot(); break; case Keyboard.KEY_O: Render.overhead ^= true; break; } } @Override public void update(){ final float moveSpeed = 0.1f; if (Keyboard.isKeyDown(Keyboard.KEY_R)) { Render.camera.yaw -= 0.5f; } if (Keyboard.isKeyDown(Keyboard.KEY_F)) { Render.camera.yaw += 0.5f; } if (Keyboard.isKeyDown(Keyboard.KEY_W)) { Render.camera.moveForward(moveSpeed); } if (Keyboard.isKeyDown(Keyboard.KEY_A)) { Render.camera.moveRight(moveSpeed); } if (Keyboard.isKeyDown(Keyboard.KEY_S)) { Render.camera.moveBack(moveSpeed); } if (Keyboard.isKeyDown(Keyboard.KEY_D)) { Render.camera.moveLeft(moveSpeed); } if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) { Render.camera.moveDown(moveSpeed); } if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) { Render.camera.moveUp(moveSpeed); } while (Mouse.next()) { if (Mouse.getEventButton() > -1) { if (Mouse.getEventButtonState()) { UIManager.click(Mouse.getX(), Display.getHeight() - Mouse.getY()); } } } } }; public static final IInputManager consoleInput = new IInputManager() { @Override public void update() { IGConsole.adjustOffset(Mouse.getDWheel() / 100); } @Override public void run(int keycode) { switch (keycode) { case Keyboard.KEY_GRAVE: case Keyboard.KEY_TAB: IGConsole.running = false; break; case Keyboard.KEY_RETURN: IGConsole.buffer = IGConsole.buffer.replace(Typer.blinkCharacter, " "); IGConsole.logCommand(IGConsole.buffer); Command.onCommand(IGConsole.buffer); IGConsole.clear = "|"; break; case Keyboard.KEY_F10: RenderUtil.takeScreenshot(); break; case Keyboard.KEY_UP: IGConsole.adjustCommandOffset(1); break; case Keyboard.KEY_DOWN: IGConsole.adjustCommandOffset(-1); break; } } }; public static final IInputManager menuInput = new IInputManager() { @Override public void update() { while (Mouse.next()) { if (Mouse.getEventButton() > -1) { if (Mouse.getEventButtonState()) { UIManager.clickMenu(Mouse.getX(), Display.getHeight() - Mouse.getY()); } } } } @Override public void run(int keycode) { switch (keycode) { case Keyboard.KEY_GRAVE: case Keyboard.KEY_TAB: IGConsole.consoleLoop(); break; case Keyboard.KEY_F10: RenderUtil.takeScreenshot(); break; } } }; public static final IInputManager pausedInput = new IInputManager() { @Override public void update() { while (Mouse.next()) { if (Mouse.getEventButton() > -1) { if (Mouse.getEventButtonState()) { UIManager.clickPause(Mouse.getX(), Display.getHeight() - Mouse.getY()); } } } } @Override public void run(int keycode) { switch (keycode) { case Keyboard.KEY_F10: RenderUtil.takeScreenshot(); break; case Keyboard.KEY_ESCAPE: Main.paused ^= true; break; } } }; public static final IInputManager gameOverInput = new IInputManager() { @Override public void update() { while (Mouse.next()) { if (Mouse.getEventButton() > -1) { if (Mouse.getEventButtonState()) { UIManager.clickGameOver(Mouse.getX(), Display.getHeight() - Mouse.getY()); } } } } @Override public void run(int keycode) { switch (keycode) { case Keyboard.KEY_F10: RenderUtil.takeScreenshot(); break; } } }; }
32.125628
91
0.461286
89cea05851ea332dd8d72541ba0a66c8299984cb
395
package com.example.exception; public class AppBusinessException extends RuntimeException { private static final long serialVersionUID = 5686002958837120448L; public AppBusinessException(String errorMessage) { super(errorMessage); } public AppBusinessException(String errorMessage, String message) { super(errorMessage.concat(" ").concat(message)); } }
23.235294
70
0.739241
5ab05aa04d77df919f971e8da2237778990ae143
778
package com.paulek.core.common; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class PermissionsUtil { public static boolean checkPermission(String string, Player player) { return player.hasPermission("cloudcore." + string); } public static boolean checkCommandPermission(String string, Player player) { return player.hasPermission("cloudcore.command." + string); } public static boolean checkPermission(String string, CommandSender commandSender) { return commandSender.hasPermission("cloudcore." + string); } public static boolean checkCommandPermission(String string, CommandSender commandSender) { return commandSender.hasPermission("cloudcore.command." + string); } }
31.12
94
0.74036
da10d65e0a0f778d3f58fff2b69347b60acc0ea3
518
/** * */ package com.thinkgem.jeesite.modules.wlpt.dao.base; import com.thinkgem.jeesite.common.persistence.CrudDao; import java.util.List; import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao; import com.thinkgem.jeesite.modules.wlpt.entity.base.BscMessage; /** * 消息通知DAO接口 * @author fjc * @version 2017-11-15 */ @MyBatisDao public interface BscMessageDao extends CrudDao<BscMessage> { /** * 统计未读消息数 * @return */ public BscMessage sumUnRead(BscMessage bscMessage); }
20.72
69
0.72973
9956f655e664cae7422c13a6fcdf35ef52ad05fe
4,932
package ca.uwaterloo.jrefactoring.node; import ca.uwaterloo.jrefactoring.template.RFTemplate; import ca.uwaterloo.jrefactoring.utility.FileLogger; import ca.uwaterloo.jrefactoring.visitor.RFVisitor; import gr.uom.java.ast.decomposition.StatementType; import org.eclipse.jdt.core.dom.Statement; import org.slf4j.Logger; import java.util.ArrayList; import java.util.List; public abstract class RFStatement implements RFEntity { private static Logger log = FileLogger.getLogger(RFStatement.class); RFStatement parent; List<RFStatement> children; StatementType statementType; Statement statement1; Statement statement2; List<RFNodeDifference> nodeDifferences; RFTemplate template; public RFStatement(RFTemplate template) { parent = null; statementType = null; statement1 = null; statement2 = null; this.template = template; nodeDifferences = new ArrayList<>(); children = new ArrayList<>(); } public RFStatement(StatementType statementType, Statement statement1, Statement statement2, List<RFNodeDifference> nodeDifferences, RFTemplate template) { this.parent = null; this.statementType = statementType; this.statement1 = statement1; this.statement2 = statement2; this.nodeDifferences = nodeDifferences; this.template = template; this.children = new ArrayList<>(); for (RFNodeDifference diff : this.nodeDifferences) { diff.setRfStatement(this); } } @Override public void accept(RFVisitor visitor) { if (visitor == null) { throw new IllegalArgumentException(); } // begin with the generic pre-visit if (visitor.preVisit2(this)) { // dynamic dispatch to internal method for type-specific visit/endVisit accept0(visitor); } // end with the generic post-visit visitor.postVisit(this); } abstract void accept0(RFVisitor visitor); public void setParent(RFStatement parent) { this.parent = parent; } public void addChild(RFStatement child) { if (child == null) { throw new IllegalArgumentException(); } children.add(child); } public boolean isRoot() { return this.parent == null; } public StatementType getStatementType() { return statementType; } public String getStatementTypeString() { if (isRoot()) { return "root"; } else { return statementType == null ? "else" : statementType.toString(); } } public RFStatement getParent() { return parent; } public boolean isTopStmt() { return parent != null && parent.isRoot(); } public Statement getStatement1() { return statement1; } public Statement getStatement2() { return statement2; } public List<RFNodeDifference> getNodeDifferences() { return nodeDifferences; } public RFTemplate getTemplate() { return template; } public void setStatementType(StatementType statementType) { this.statementType = statementType; } public void setStatement1(Statement statement1) { this.statement1 = statement1; } public void setStatement2(Statement statement2) { this.statement2 = statement2; } public void setNodeDifferences(List<RFNodeDifference> nodeDifferences) { this.nodeDifferences = nodeDifferences; } public void setTemplate(RFTemplate template) { this.template = template; } public void describe() { System.out.println("-----------------------------------------------------------"); describeStatements(); describeDifference(); System.out.println(); } private void describeStatements() { System.out.println("Describing RFStatement [Type: " + getStatementTypeString() + "]:"); System.out.println("\t\tStatement1: " + (statement1 == null ? "null" : statement1.toString())); System.out.println("\t\tStatement2: " + (statement2 == null ? "null" : statement2.toString())); } private void describeDifference() { if (nodeDifferences.size() > 0) { System.out.println("Describing RFStatement differences: "); System.out.println("\tDifferences: "); for (RFNodeDifference difference : nodeDifferences) { System.out.println("\t\t" + difference); } } else { System.out.println("Current RFStatement has no difference"); } } public boolean hasChildren() { return children.size() > 0; } public boolean hasDifference() { return nodeDifferences.size() > 0; } }
28.022727
103
0.615166