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 |
|---|---|---|---|---|---|
8338597fb07cabc76cc7756e15437ca3ff83be2e | 5,987 | package org.wushujames.connect.mysql;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.source.SourceRecord;
import org.apache.kafka.connect.source.SourceTaskContext;
import org.apache.kafka.connect.storage.OffsetStorageReader;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.powermock.api.easymock.PowerMock;
public class MySqlSourceTaskTest {
private Map<String, String> config;
private MySqlSourceTask task;
private OffsetStorageReader offsetStorageReader;
private SourceTaskContext context;
private boolean verifyMocks = false;
private Connection connection;
@Before
public void setup() throws IOException, SQLException {
String mysqlHost = "10.100.172.86";
connection = DriverManager.getConnection("jdbc:mysql://" + mysqlHost + ":3306/mysql", "root", "passwd");
config = new HashMap<>();
config.put(MySqlSourceConnector.USER_CONFIG, "maxwell");
config.put(MySqlSourceConnector.PASSWORD_CONFIG, "XXXXXX");
config.put(MySqlSourceConnector.PORT_CONFIG, "3306");
config.put(MySqlSourceConnector.HOST_CONFIG, mysqlHost);
task = new MySqlSourceTask();
offsetStorageReader = PowerMock.createMock(OffsetStorageReader.class);
context = PowerMock.createMock(SourceTaskContext.class);
task.initialize(context);
runSql("drop table if exists test.users");
runSql("drop database if exists test");
}
@After
public void teardown() {
if (verifyMocks)
PowerMock.verifyAll();
}
private void replay() {
PowerMock.replayAll();
verifyMocks = true;
}
@Test
public void testChar() throws InterruptedException, IOException, SQLException {
String insertSql = "insert into test.users (name) values (\"James\");";
testSchemaType("name", "char(128)", Schema.STRING_SCHEMA, "James", insertSql);
}
@Test
public void testTinyInt() throws InterruptedException, IOException, SQLException {
String insertSql = "insert into test.users (tinyintcol) values (1);";
testSchemaType("tinyintcol", "tinyint", Schema.INT16_SCHEMA, (short) 1, insertSql);
// add tests for signed, unsigned
// boundary tests -127 to 128, 0 to 255
// http://dev.mysql.com/doc/refman/5.7/en/integer-types.html
}
@Test
public void testBigint() throws InterruptedException, IOException, SQLException {
// add tests for boundary conditions
// add tests for signed, unsigned
// http://dev.mysql.com/doc/refman/5.7/en/integer-types.html
String insertSql = "insert into test.users (bigintcol) values (1844674407370955160);";
testSchemaType("bigintcol", "bigint", Schema.INT64_SCHEMA, 1844674407370955160L, insertSql);
}
private void testSchemaType(String sqlFieldName, String sqlFieldType, Schema expectedValueSchema,
Object expectedValue, String insertSql) throws SQLException, InterruptedException {
expectOffsetLookupReturnNone();
replay();
task.start(config);
runSql("create database test");
runSql("create table test.users (userId int auto_increment primary key)");
runSql(String.format("alter table test.users add column %s %s",
sqlFieldName,
sqlFieldType
));
runSql(insertSql);
List<SourceRecord> records = pollUntilRows();
assertEquals(1, records.size());
SourceRecord james = records.get(0);
// check key schema
Schema keySchema = james.keySchema();
assertEquals(1, keySchema.fields().size());
assertNotNull(keySchema.field("userid"));
assertEquals(Schema.INT32_SCHEMA, keySchema.field("userid").schema());
// check key
Object keyObject = james.key();
assertTrue(keyObject instanceof Struct);
Struct key = (Struct) keyObject;
assertEquals(1, key.get("userid"));
// check value schema
Schema valueSchema = james.valueSchema();
assertEquals(2, valueSchema.fields().size());
assertNotNull(valueSchema.field("userid"));
assertEquals(Schema.INT32_SCHEMA, valueSchema.field("userid").schema());
assertNotNull(valueSchema.field(sqlFieldName));
assertEquals(expectedValueSchema, valueSchema.field(sqlFieldName).schema());
// check value
Object valueObject = james.value();
assertTrue(valueObject instanceof Struct);
Struct value = (Struct) valueObject;
assertEquals(1, value.get("userid"));
assertEquals(expectedValue, value.get(sqlFieldName));
}
private void expectOffsetLookupReturnNone() {
EasyMock.expect(context.offsetStorageReader()).andReturn(offsetStorageReader);
EasyMock.expect(offsetStorageReader.offset(EasyMock.anyObject(Map.class))).andReturn(null);
}
private void runSql(String statement) throws SQLException {
connection.createStatement().executeUpdate(statement);
}
private List<SourceRecord> pollUntilRows() throws InterruptedException {
List<SourceRecord> records = null;
while (true) {
records = task.poll();
if (records.size() > 0) {
break;
} else {
System.out.println("poll returned no records");
}
}
return records;
}
}
| 36.506098 | 112 | 0.663939 |
173745b30cf73ce5b72f8b0757525fb9be7bbaf0 | 3,467 | /*
* Copyright 2020 The 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.yanncebron.m68kplugin.parser;
import com.intellij.testFramework.TestDataPath;
import java.io.IOException;
@TestDataPath("$PROJECT_ROOT/testData/parser/mulDivInstructions")
public class MulDivInstructionsParsingTest extends M68kParsingTestCase {
public MulDivInstructionsParsingTest() {
super("mulDivInstructions");
}
public void testMulsInstructionMissingSource() throws IOException {
doCodeTest(" muls ");
}
public void testMulsInstructionMissingDestination() throws IOException {
doCodeTest(" muls d0,");
}
public void testMulsInstructionDrd() throws IOException {
doCodeTest(" muls d0,d1");
}
public void testMulsInstructionDataSizeDrd() throws IOException {
doCodeTest(" muls.w d0,d1");
}
public void testMulsInstructionAbs() throws IOException {
doCodeTest(" muls label,d1");
}
public void testMulsInstructionImm() throws IOException {
doCodeTest(" muls #42,d1");
}
public void testMuluInstructionMissingSource() throws IOException {
doCodeTest(" mulu ");
}
public void testMuluInstructionMissingDestination() throws IOException {
doCodeTest(" mulu d0,");
}
public void testMuluInstructionDrd() throws IOException {
doCodeTest(" mulu d0,d1");
}
public void testMuluInstructionDataSizeDrd() throws IOException {
doCodeTest(" mulu.w d0,d1");
}
public void testMuluInstructionAbs() throws IOException {
doCodeTest(" mulu label,d1");
}
public void testMuluInstructionImm() throws IOException {
doCodeTest(" mulu #42,d1");
}
public void testDivsInstructionMissingSource() throws IOException {
doCodeTest(" divs ");
}
public void testDivsInstructionMissingDestination() throws IOException {
doCodeTest(" divs d0,");
}
public void testDivsInstructionDrd() throws IOException {
doCodeTest(" divs d0,d1");
}
public void testDivsInstructionDataSizeDrd() throws IOException {
doCodeTest(" divs.w d0,d1");
}
public void testDivsInstructionAbs() throws IOException {
doCodeTest(" divs label,d1");
}
public void testDivsInstructionImm() throws IOException {
doCodeTest(" divs #42,d1");
}
public void testDivuInstructionMissingSource() throws IOException {
doCodeTest(" divu ");
}
public void testDivuInstructionMissingDestination() throws IOException {
doCodeTest(" divu d0,");
}
public void testDivuInstructionDrd() throws IOException {
doCodeTest(" divu d0,d1");
}
public void testDivuInstructionDataSizeDrd() throws IOException {
doCodeTest(" divu.w d0,d1");
}
public void testDivuInstructionAbs() throws IOException {
doCodeTest(" divu label,d1");
}
public void testDivuInstructionImm() throws IOException {
doCodeTest(" divu #42,d1");
}
public void testDivuInstructionPcd() throws IOException {
doCodeTest(" divu 42(pc),d1");
}
} | 26.669231 | 75 | 0.727142 |
192746e9599ce39ee0425a42d26529de44ab16bd | 1,049 | package es.urjc.dad.devNest.Database.Repositories;
import es.urjc.dad.devNest.Database.Entities.GamejamEntity;
import java.util.Optional;
import javax.persistence.QueryHint;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.QueryHints;
public interface GamejamRepository extends JpaRepository<GamejamEntity, Long> {
@Cacheable(value = "gamejams", key = "#id")
@Override
@QueryHints({@QueryHint(name = "org.hibernate.cacheable", value = "true")})
Optional<GamejamEntity> findById(Long id);
@CachePut(value = "gamejams", key = "#gamejamEntity.id")
@Override
@QueryHints({@QueryHint(name = "org.hibernate.cacheable", value = "true")})
GamejamEntity save(GamejamEntity gamejamEntity);
@CacheEvict(value = "gamejams", key = "#entity.id")
void delete(GamejamEntity entity);
}
| 36.172414 | 79 | 0.756911 |
580b97c1c0ffa9e3bd4842d31685665584a2a12a | 2,973 | /*
* 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 Report;
import Connection.ConnectionManager;
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
/**
* FXML Controller class
*
* @author ASUS
*/
public class AddEmployeController implements Initializable {
/**
* Initializes the controller class.
*/
@FXML
private TextField tfUserName;
@FXML
private TextField tfFullName;
@FXML
private TextField tfEmail;
@FXML
private TextField tfPhone;
@FXML
private TextField tfSalary;
@FXML
private TextField tfPassword;
@FXML
private TextArea taAddress;
@FXML
private TextField tfRole;
private ConnectionManager connectionManager = new ConnectionManager();
@FXML
private void addNewEmployee(ActionEvent event) {
String UserName = tfUserName.getText();
String FullName = tfFullName.getText();
String Phone = tfPhone.getText().toString();
String Salary = tfSalary.getText();
String Password = tfPassword.getText();
String Address = taAddress.getText();
String Role = tfRole.getText();
String Email = tfEmail.getText();
try {
String query = String.format("INSERT INTO mydb.user"
+ " values('%s','%s', '%s', '%s', '%s', '%s','%s', '%s', '%s')",0, UserName, FullName, Email, Phone, Salary, Password, Role,Address);
connectionManager.connect();
connectionManager.execute(query);
connectionManager.close();
ShowInfoMessage("Add Employee Status", "Added Employee Successfully");
} catch (SQLException sqlException) {
System.err.println(sqlException);
//sqlException.printStackTrace();
ShowInfoMessage("Add Employee Status", "Adding Employee Failed, Please Try again");
} catch (Exception e) {
System.err.println(e);
ShowInfoMessage("Add Employee Status", "Adding Employee Failed, Please Try again");
}
}
private void ShowInfoMessage(String title, String message) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle(title);
//alert.setHeaderText("Look, an Information Dialog");
alert.setContentText(message);
alert.showAndWait();
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
| 30.96875 | 154 | 0.637403 |
f86dcc0f58703cd0a2a9db2e493b668f041a999c | 5,322 | /**
* $URL$
* $Id$
*
* Copyright (c) 2006-2009 The 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.sitestats.test.data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.sakaiproject.sitestats.api.StatsManager;
import org.sakaiproject.sitestats.api.event.EventInfo;
import org.sakaiproject.sitestats.api.event.ToolInfo;
import org.sakaiproject.sitestats.api.parser.EventParserTip;
public class FakeData {
// SITEs
public final static String SITE_A_ID = "site-a-id";
public final static String SITE_A_REF = "/site/site-a-id";
public final static String SITE_A_ALIAS = "site-a-alias";
public final static String SITE_A_TARGET = SITE_A_REF;
public final static String SITE_B_ID = "site-b-id";
public final static String SITE_B_REF = "/site/site-b-id";
public final static String SITE_C_ID = "site-c-id";
public final static String SITE_C_REF = "/site/site-c-id";
public final static int SITE_C_USER_COUNT = 2002;
// USERs
public final static String USER_A_ID = "user-a";
public final static String USER_B_ID = "user-b";
public final static String USER_ID_PREFIX = "user-";
// TOOLs & EVENTs
public final static String TOOL_CHAT = "sakai.chat";
public final static String EVENT_CHATNEW = "chat.new";
public final static String EVENT_CONTENTNEW = "content.new";
public final static String EVENT_CONTENTREV = "content.revise";
public final static String EVENT_CONTENTREAD = "content.read";
// anonymous events
public final static String EVENT_CONTENTDEL = "content.delete";
// EVENT LIST & EVENT MAP
public final static Set<String> EVENTIDS = new HashSet<String>();
public final static List<ToolInfo> EVENT_REGISTRY = new ArrayList<ToolInfo>();
public final static List<ToolInfo> EVENT_REGISTRY_RES = new ArrayList<ToolInfo>();
public final static List<ToolInfo> EVENT_REGISTRY_CHAT = new ArrayList<ToolInfo>();
static{
EVENTIDS.add(EVENT_CHATNEW);
EVENTIDS.add(EVENT_CONTENTNEW);
EVENTIDS.add(EVENT_CONTENTREAD);
EVENTIDS.add(EVENT_CONTENTREV);
EVENTIDS.add(EVENT_CONTENTDEL);
EVENTIDS.add(StatsManager.SITEVISIT_EVENTID);
};
public final static Map<String, ToolInfo> EVENTID_TOOL_MAP = new HashMap<String, ToolInfo>();
static{
ToolInfo chat = new ToolInfo("sakai.chat");
chat.addEvent(new EventInfo(EVENT_CHATNEW));
chat.setEventParserTip(new EventParserTip("contextId", "/", "3"));
EVENTID_TOOL_MAP.put(EVENT_CHATNEW, chat);
EVENT_REGISTRY.add(chat);
EVENT_REGISTRY_CHAT.add(chat);
ToolInfo resources = new ToolInfo(StatsManager.RESOURCES_TOOLID);
resources.addEvent(new EventInfo(EVENT_CONTENTNEW));
resources.addEvent(new EventInfo(EVENT_CONTENTREAD));
resources.addEvent(new EventInfo(EVENT_CONTENTREV));
resources.addEvent(new EventInfo(EVENT_CONTENTDEL));
resources.setEventParserTip(new EventParserTip("contextId", "/", "3"));
EVENTID_TOOL_MAP.put(EVENT_CONTENTNEW, resources);
EVENTID_TOOL_MAP.put(EVENT_CONTENTREAD, resources);
EVENTID_TOOL_MAP.put(EVENT_CONTENTREV, resources);
EVENTID_TOOL_MAP.put(EVENT_CONTENTDEL, resources);
EVENT_REGISTRY.add(resources);
EVENT_REGISTRY_RES.add(resources);
}
// RESOURCEs
public final static String RES_MYWORKSPACE_A = "/content/user/"+USER_A_ID+"/";
public final static String RES_MYWORKSPACE_B_F = "/content/user/"+USER_B_ID+"/resource1";
public final static String RES_MYWORKSPACE_NO_F= "/content/user/no_user/resource1";
public final static String RES_ATTACH_SITE = "/content/attachment/"+SITE_A_ID;
public final static String RES_ATTACH = "/content/attachment/"+SITE_A_ID+"/Discussion/resource3";
public final static String RES_ATTACH_OLD = "/content/attachment/"+SITE_A_ID+"/Choose File/resource3";
public final static String RES_ATTACH_OLD2 = "/content/attachment/"+SITE_A_ID+"/Choose File/Assignments/resource3";
public final static String RES_ROOT_SITE_A = "/content/group/"+SITE_A_ID+"/";
public final static String RES_FILE_SITE_A = "/content/group/"+SITE_A_ID+"/resource1";
public final static String RES_FOLDER_SITE_A = "/content/group/"+SITE_A_ID+"/folder/";
public final static String RES_FILE2_SITE_A = "/content/group/"+SITE_A_ID+"/folder/res2";
public final static String RES_DROPBOX_SITE_A = "/content/group-user/"+SITE_A_ID+"/";
public final static String RES_DROPBOX_SITE_A_USER_A = "/content/group-user/"+SITE_A_ID+"/"+USER_A_ID+"/";
public final static String RES_DROPBOX_SITE_A_USER_A_FILE = "/content/group-user/"+SITE_A_ID+"/"+USER_A_ID+"/resource1";
}
| 46.684211 | 125 | 0.744081 |
eb09b6dffa88463dca1e1b47fd0041e8969bad2d | 1,546 | package org.ssunion.cloudschedule.telegram.pushbot.menus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.ssunion.cloudschedule.domain.telegram.pushbot.User;
import org.ssunion.cloudschedule.telegram.pushbot.PushBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
/**
* @author kasad0r
*/
@Component
public class UserStatusMenu {
private final PushBot pushBot;
@Autowired
public UserStatusMenu(PushBot pushBot) {
this.pushBot = pushBot;
}
public void execute(User user) {
SendMessage sendMessage = new SendMessage().setChatId(user.getUserToken());
sendMessage.setParseMode("html");
sendMessage.setText("<b>Статус:</b>\n" +
"<i>ID: </i>" + user.getUserToken() +
"\n<i>UserName: </i>" + user.getUsername() +
"\n<i>Имя пользователя: </i>" + (user.getFirstname() == null ? "" : user.getFirstname()) + " " + (user.getLastname() == null ? "" : user.getLastname()) +
"\n<i>Сообщение от администрации: </i>" + (user.getSettings().isAdminNotice() ? "ВКЛ" : "ВЫКЛ") +
"\n<i>Выбранная группа: </i>" + (user.getSettings().getSelectedGroup() == null ? "Не выбран" : user.getSettings().getSelectedGroup()) +
"\n<i>Время для отправки: </i>" + (user.getSettings().getTimeToSendSchedule() == null ? "Не выбран" : user.getSettings().getTimeToSendSchedule()));
pushBot.executeMessage(sendMessage);
}
}
| 44.171429 | 169 | 0.652005 |
f9083aac6ae0618e1b628aa2a9281670c0bd7efe | 3,955 | package com.fbd.web.app.message.action;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fbd.core.app.message.model.StationMessageModel;
import com.fbd.core.base.BaseAction;
import com.fbd.core.common.model.SearchResult;
import com.fbd.web.app.message.service.IStationMessageService;
@Controller
@Scope("prototype")
@RequestMapping("/message")
public class MessageAction extends BaseAction {
/**
*
*/
private static final long serialVersionUID = -6244496133888715272L;
@Resource
private IStationMessageService stationMessageService;
/**
* Description: 分页查询所有消息节点的列表
*
* @param
* @return SearchResult<MessageNodeModel>
* @throws
* @Author dongzhongwei
* Create Date: 2015-2-4 下午12:20:04
*/
@RequestMapping(value = "/getMessageList.html", method = RequestMethod.POST)
public @ResponseBody Map<String,Object> getMessageList(HttpServletRequest request,StationMessageModel model){
Map<String,Object> resultMap = new HashMap<String,Object>();
try{
String userId = this.getUserId(request);
model.setUserId(userId);
model.setSort("sendTime");
SearchResult<StationMessageModel> result = stationMessageService.getPageList(model);
//查询未读消息数量
StationMessageModel qmodel1 = new StationMessageModel();
qmodel1.setUserId(userId);
qmodel1.setStatus("0");
long unReadCount = this.stationMessageService.selectMessageCount(qmodel1);
StationMessageModel qmodel2 = new StationMessageModel();
qmodel2.setUserId(userId);
qmodel2.setStatus("1");
long readCount = this.stationMessageService.selectMessageCount(qmodel2);
resultMap.put("unReadCount",unReadCount);
resultMap.put("readCount",readCount);
resultMap.put(SUCCESS, true);
resultMap.put(MSG, result);
}catch(Exception e){
e.printStackTrace();
resultMap.put(SUCCESS, false);
}
return resultMap;
}
/**
*
* Description: 阅读消息
*
* @param
* @return Map<String,Object>
* @throws
* @Author haolingfeng<br/>
* Create Date: 2015-2-27 下午3:02:27
*/
@RequestMapping(value = "/updateMsg.html", method = RequestMethod.POST)
public @ResponseBody Map<String,Object> updateMsgStatus(String id){
Map<String,Object> resultMap = new HashMap<String,Object>();
try{
stationMessageService.updateMessage(id);
resultMap.put(SUCCESS, true);
}catch(Exception e){
e.printStackTrace();
resultMap.put(SUCCESS, false);
}
return resultMap;
}
/**
*
* Description: 删除消息
*
* @param
* @return Map<String,Object>
* @throws
* @Author haolingfeng<br/>
* Create Date: 2015-2-27 下午3:02:27
*/
@RequestMapping(value = "/batchDelete.html", method = RequestMethod.POST)
public @ResponseBody Map<String,Object> batchDelete(String ids){
Map<String,Object> resultMap = new HashMap<String,Object>();
try{
stationMessageService.delMessage(ids);
resultMap.put(SUCCESS, true);
}catch(Exception e){
e.printStackTrace();
resultMap.put(SUCCESS, false);
}
return resultMap;
}
}
| 33.235294 | 114 | 0.624779 |
91afe88ff1631b7cacdbf2bd56a332778ad90017 | 4,338 | package com.zzstack.paas.underlying.metasvr.global;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.zzstack.paas.underlying.metasvr.bean.LogBean;
import com.zzstack.paas.underlying.utils.consts.CONSTS;
public class DeployLog {
private static final long EXPIRE_TIME = 10*60*1000; // 过期时间10分钟
private ConcurrentHashMap<String, LogBean> logMap;
private static ThreadPoolExecutor expiredExecutor;
private static BlockingQueue<Runnable> expiredWorksQueue;
private Runnable expiredCleaner;
private static DeployLog INSTANCE = null;
static {
expiredWorksQueue = new ArrayBlockingQueue<Runnable>(10);
expiredExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, expiredWorksQueue, new ThreadPoolExecutor.DiscardPolicy());
}
public DeployLog() {
logMap = new ConcurrentHashMap<String, LogBean>();
expiredCleaner = new ExpiredCleaner();
expiredExecutor.execute(expiredCleaner);
}
public static DeployLog get() {
if (DeployLog.INSTANCE == null) {
INSTANCE = new DeployLog();
}
return DeployLog.INSTANCE;
}
private void putLogBean(final String logKey, LogBean bean) {
logMap.put(logKey, bean);
}
private static ConcurrentHashMap<String, LogBean> getLogMap() {
DeployLog instance = DeployLog.get();
return instance.logMap;
}
private static LogBean getLogBean(final String logKey) {
ConcurrentHashMap<String, LogBean> instance = DeployLog.getLogMap();
return instance.get(logKey);
}
public static void pubLog(final String logKey, String log) {
if (logKey == null || logKey.length() == 0)
return;
final LogBean logBean = DeployLog.getLogBean(logKey);
String newLog = log.replaceAll(CONSTS.LINE_END, CONSTS.HTML_LINE_END);
if (logBean == null) {
LogBean newLogBean = new LogBean();
newLogBean.putLog(newLog);
DeployLog instance = DeployLog.get();
instance.putLogBean(logKey, newLogBean);
} else {
logBean.putLog(newLog);
}
}
public static void pubSuccessLog(final String logKey, final String log) {
if (logKey != null && !logKey.isEmpty()) {
StringBuffer logSB = new StringBuffer();
logSB.append(CONSTS.DEPLOY_SINGLE_SUCCESS_BEGIN_STYLE);
logSB.append(log);
logSB.append(CONSTS.END_STYLE);
pubLog(logKey, logSB.toString());
}
}
public static void pubFailLog(final String logKey, final String log) {
if (logKey != null && !logKey.isEmpty()) {
StringBuffer logSB = new StringBuffer();
logSB.append(CONSTS.DEPLOY_SINGLE_FAIL_BEGIN_STYLE);
logSB.append(log);
logSB.append(CONSTS.END_STYLE);
pubLog(logKey, logSB.toString());
}
}
public static void pubErrorLog(String logKey, String log) {
if (logKey != null && !logKey.isEmpty()) {
StringBuffer logSB = new StringBuffer();
logSB.append(CONSTS.DEPLOY_SINGLE_FAIL_BEGIN_STYLE);
logSB.append(log);
logSB.append(CONSTS.END_STYLE);
pubLog(logKey, logSB.toString());
}
}
public static String getLog(String sessionKey) {
final LogBean logBean = DeployLog.getLogBean(sessionKey);
if (logBean == null) {
return "";
} else {
return logBean.getLog();
}
}
private static void elimExpired() {
final ConcurrentHashMap<String, LogBean> logMap = DeployLog.getLogMap();
Iterator<Map.Entry<String, LogBean>> iter = logMap.entrySet().iterator();
long ts = System.currentTimeMillis();
List<String> removeList = new LinkedList<String>();
while (iter.hasNext()) {
Map.Entry<String, LogBean> entry = iter.next();
String key = entry.getKey();
LogBean logBean = entry.getValue();
if (ts - logBean.getLastTimestamp() > EXPIRE_TIME) {
logBean.clear();
removeList.add(key);
}
}
if (!removeList.isEmpty()) {
Iterator<String> removeIter = removeList.iterator();
while (removeIter.hasNext()) {
String key = removeIter.next();
logMap.remove(key);
}
}
removeList.clear();
}
private static class ExpiredCleaner implements Runnable {
public ExpiredCleaner() {
super();
}
@Override
public void run() {
DeployLog.elimExpired();
}
}
}
| 26.944099 | 130 | 0.717151 |
37a608dfadf705f4f6408a28b088b68e63d1a52c | 654 | package com.prismaqf.callblocker.utils;
import com.prismaqf.callblocker.sql.DbHelper;
import com.prismaqf.callblocker.sql.DbHelperTest;
import org.junit.rules.ExternalResource;
/**
* JUnit Rule to inject the DB file name in DBHelper
* @author ConteDiMonteCristo
*/
public class DebugDBFileName extends ExternalResource {
static class MyKey extends DebugKey {}
private final MyKey myKey = new MyKey();
@Override
protected void before() throws Throwable {
DbHelper.SetDebugDb(myKey.getKey(), DbHelperTest.DB_NAME);
}
@Override
protected void after() {
DbHelper.SetDebugDb(myKey.getKey(),null);
}
}
| 23.357143 | 66 | 0.724771 |
e3ae2044d84ec3ada6b83f69a69dc26859bf721b | 1,075 | package org.openxsp.example;
import java.util.Scanner;
import org.openxsp.java.RPCResult;
import org.openxsp.java.RPCResultHandler;
import org.openxsp.java.Verticle;
import org.vertx.java.core.json.JsonObject;
public class Sender extends Verticle {
public static final String EVENT = "org.openxsp.test";
@Override
public void start() {
System.out.println("Starting Sender Example module");
System.out.println("Type a message to send:");
Scanner reader = new Scanner(System.in);
String message = reader.next();
reader.close();
sendEvent(message);
}
private void sendEvent(String message){
JsonObject data = new JsonObject();
data.putString("message", message);
System.out.println("Sending message "+data+" to "+EVENT);
openxsp.eventBus().invoke(EVENT, "OptionalRpcAction", data, new RPCResultHandler() {
@Override
public void handle(RPCResult res) {
if (res.succeeded()) {
System.out.println("Successful reply received");
}
if (res.failed()) {
System.out.println("Unsuccessful reply received");
}
}
});
}
}
| 26.219512 | 86 | 0.710698 |
553221c477d2c03b17d8e11abcf97fa3986ed506 | 2,272 | package com.example.entity;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
public class ExampleEntity
{
private boolean booleanVar;
private int intVar;
private long longVar;
private String stringVar;
private Date dateVar;
private Calendar calendarVar;
private MyModel myModel;
private ArrayList<String> stringList;
// empty constructor
public ExampleEntity()
{
}
// copy constructor
public ExampleEntity(ExampleEntity origin)
{
booleanVar = origin.booleanVar;
intVar = origin.intVar;
longVar = origin.longVar;
if(origin.stringVar!=null) stringVar = new String(origin.stringVar);
if(origin.dateVar!=null) dateVar = new Date(origin.dateVar.getTime());
if(origin.calendarVar!=null)
{
calendarVar = Calendar.getInstance();
calendarVar.setTime(origin.calendarVar.getTime());
}
if(origin.myModel!=null) myModel = new MyModel(origin.myModel);
if(origin.stringList!=null)
{
stringList = new ArrayList<String>();
Iterator<String> iterator = origin.stringList.iterator();
while(iterator.hasNext())
{
String s = iterator.next();
stringList.add(new String(s));
}
}
}
public boolean isBooleanVar()
{
return booleanVar;
}
public void setBooleanVar(boolean booleanVar)
{
this.booleanVar = booleanVar;
}
public int getIntVar()
{
return intVar;
}
public void setIntVar(int intVar)
{
this.intVar = intVar;
}
public long getLongVar()
{
return longVar;
}
public void setLongVar(long longVar)
{
this.longVar = longVar;
}
public String getStringVar()
{
return stringVar;
}
public void setStringVar(String stringVar)
{
this.stringVar = stringVar;
}
public Date getDateVar()
{
return dateVar;
}
public void setDateVar(Date dateVar)
{
this.dateVar = dateVar;
}
public Calendar getCalendarVar()
{
return calendarVar;
}
public void setCalendarVar(Calendar calendarVar)
{
this.calendarVar = calendarVar;
}
public MyModel getMyModel()
{
return myModel;
}
public void setMyModel(MyModel myModel)
{
this.myModel = myModel;
}
public ArrayList<String> getStringList()
{
return stringList;
}
public void setStringList(ArrayList<String> stringList)
{
this.stringList = stringList;
}
}
| 18.933333 | 72 | 0.71963 |
88b4f650c5fe1f36fb7ac823104eafa93f16a06b | 2,896 | package nextstep.subway.line.ui;
import java.util.List;
import javax.validation.Valid;
import nextstep.subway.line.application.LineService;
import nextstep.subway.line.dto.LineRequest;
import nextstep.subway.line.dto.LineResponse;
import nextstep.subway.line.dto.LineUpdateRequest;
import nextstep.subway.line.dto.LinesResponse;
import nextstep.subway.line.dto.SectionCreateRequest;
import nextstep.subway.line.dto.SectionCreateResponse;
import nextstep.subway.line.dto.SectionDeleteRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.net.URI;
@RestController
public class LineController {
private final LineService lineService;
public LineController(final LineService lineService) {
this.lineService = lineService;
}
@GetMapping("/lines")
public ResponseEntity<?> showLines() {
List<LinesResponse> lines = lineService.findAll();
return ResponseEntity.ok(lines);
}
@GetMapping("/lines/{id}")
public ResponseEntity<?> showLine(@PathVariable Long id) {
LineResponse line = lineService.findById(id);
return ResponseEntity.ok(line);
}
@PostMapping("/lines")
public ResponseEntity<?> createLine(@RequestBody @Valid LineRequest lineRequest) {
LineResponse line = lineService.saveLine(lineRequest);
return ResponseEntity.created(URI.create("/lines/" + line.getId())).body(line);
}
@PutMapping("/lines/{id}")
public ResponseEntity<?> updateLine(@PathVariable Long id, @RequestBody @Valid LineUpdateRequest request) {
lineService.updateLine(id, request);
return ResponseEntity.ok().build();
}
@DeleteMapping("/lines/{id}")
public ResponseEntity<?> deleteLine(@PathVariable Long id) {
lineService.deleteLineById(id);
return ResponseEntity.noContent().build();
}
@PostMapping("/lines/{id}/sections")
public ResponseEntity<?> createSection(@PathVariable Long id,
@RequestBody @Valid SectionCreateRequest request) {
SectionCreateResponse section = lineService.addSection(id, request);
return ResponseEntity.created(URI.create("/lines/" + section.getId())).body(section);
}
@DeleteMapping("/lines/{id}/sections")
public ResponseEntity<?> deleteSection(@PathVariable Long id,
@RequestBody @Valid SectionDeleteRequest request) {
lineService.removeSection(id, request);
return ResponseEntity.noContent().build();
}
}
| 36.2 | 111 | 0.738605 |
c5dacc67a77cdc56d1e80bbef0c64784b5382f7d | 1,393 | package org.usfirst.frc330.commands.autocommands;
import org.usfirst.frc330.commands.*;
import org.usfirst.frc330.commands.commandgroups.*;
import org.usfirst.frc330.commands.drivecommands.*;
import org.usfirst.frc330.constants.ChassisConst;
import org.usfirst.frc330.constants.ShooterConst;
import org.usfirst.frc330.wpilibj.PIDGains;
import edu.wpi.first.wpilibj.command.BBCommandGroup;
import edu.wpi.first.wpilibj.command.WaitCommand;
/**
*
*/
public class ShootTest extends BBCommandGroup {
public ShootTest() {
// Add Commands here:
// e.g. addSequential(new Command1());
// addSequential(new Command2());
// these will run in order.
// To run multiple commands at the same time,
// use addParallel()
// e.g. addParallel(new Command1());
// addSequential(new Command2());
// Command1 and Command2 will run in parallel.
// A command group will require all of the subsystems that each member
// would require.
// e.g. if Command1 requires chassis, and Command2 requires arm,
// a CommandGroup containing them would require both the chassis and the
// arm.
//addSequential(new PrepareToShoot(ShooterConst.RIGHT_AUTO));
//addSequential(new WaitCommand(5));
//addSequential(new ShootWithWingsAgitate( ));
}
}
| 30.955556 | 80 | 0.672649 |
0f6e7b392c7dc09d6e04718d478e47357b1d1a94 | 2,649 | /*
* (c) 2005 David B. Bracewell
*
* 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 com.davidbracewell.collection.counter;
import com.davidbracewell.io.resource.Resource;
import com.davidbracewell.io.resource.StringResource;
import lombok.EqualsAndHashCode;
import static org.junit.Assert.*;
/**
* @author David B. Bracewell
*/
public class ForwardingCounterTest extends BaseCounterTest {
@Override
Counter<String> getCounter1() {
return new FC<>(super.getCounter1());
}
@Override
Counter<String> getCounter2() {
return new FC<>(super.getCounter2());
}
@Override
Counter<String> getCounter3() {
return new FC<>(super.getCounter3());
}
@Override
Counter<String> getEmptyCounter() {
return new FC<>(super.getEmptyCounter());
}
@EqualsAndHashCode(callSuper = false)
static class FC<T> extends ForwardingCounter<T> {
private static final long serialVersionUID = 1L;
final Counter<T> delegate;
FC(Counter<T> delegate) {this.delegate = delegate;}
@Override
protected Counter<T> delegate() {
return delegate;
}
}
@Override
public void csv() throws Exception {
Counter<String> counter = getCounter2();
Resource r = new StringResource();
counter.writeCsv(r);
Counter<String> fromCSV = new FC<>(Counters.readCsv(r, String.class));
assertEquals(counter, fromCSV);
}
@Override
public void json() throws Exception {
Counter<String> counter = getCounter2();
Resource r = new StringResource();
counter.writeJson(r);
Counter<String> fromJSON = new FC<>(Counters.readJson(r, String.class));
assertEquals(counter, fromJSON);
}
@Override
public void copy() throws Exception {
Counter<String> counter = getCounter2();
assertEquals(counter, new FC<>(counter.copy()));
}
}
| 27.884211 | 78 | 0.690072 |
1202fa1befb12523910b1fe37f9eb825770ea3a1 | 5,111 | /**
* Copyright 2021 Tianmian Tech. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.welab.wefe.gateway.init;
import com.welab.wefe.gateway.base.RpcServerAnnotate;
import com.welab.wefe.gateway.config.ConfigProperties;
import com.welab.wefe.gateway.util.ClassUtil;
import io.grpc.*;
import io.grpc.netty.NettyServerBuilder;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Initialize grpc server
*
* @author aaron.li
**/
@Component
public class InitRpcServer {
private final Logger LOG = LoggerFactory.getLogger(InitRpcServer.class);
@Autowired
private ConfigProperties configProperties;
/**
* Grpc service
*/
private Server rpcServer;
/**
* Does grpc service stop
*/
public static boolean SERVER_IS_SHUTDOWN = false;
/**
* Start service
*/
public void start() throws Exception {
try {
Map<String, RpcServerAnnotate> rpcClassBeans = ClassUtil.loadRpcClassBeans();
if (rpcClassBeans.isEmpty()) {
throw new Exception("start rpc server fail, is not exist available gRpc server.");
}
// Binding port
NettyServerBuilder serverBuilder = NettyServerBuilder.forPort(configProperties.getRpcServerPort());
for (Map.Entry<String, RpcServerAnnotate> entry : rpcClassBeans.entrySet()) {
RpcServerAnnotate rpcServerAnnotateConfig = entry.getValue();
BindableService rpcService = rpcServerAnnotateConfig.getRpcBean();
List<Class<? extends ServerInterceptor>> interceptors = rpcServerAnnotateConfig.getInterceptors();
if (CollectionUtils.isNotEmpty(interceptors)) {
serverBuilder.addService(ServerInterceptors.intercept(rpcService, listToInstanceArray(interceptors)));
} else {
serverBuilder.addService(rpcService);
}
}
// Set the maximum message that the server can receive(2000M)
serverBuilder.maxInboundMessageSize(2000 * 1024 * 1024);
serverBuilder.compressorRegistry(CompressorRegistry.getDefaultInstance());
serverBuilder.decompressorRegistry(DecompressorRegistry.getDefaultInstance());
serverBuilder.keepAliveTimeout(30, TimeUnit.SECONDS);
// Maximum space time
serverBuilder.maxConnectionIdle(120, TimeUnit.SECONDS);
serverBuilder.maxConnectionAge(120, TimeUnit.SECONDS);
serverBuilder.maxConnectionAgeGrace(180, TimeUnit.SECONDS);
// Start service
rpcServer = serverBuilder.build().start();
// Registration tick
Runtime.getRuntime().addShutdownHook(new Thread(InitRpcServer.this::stop));
// Start daemon
blockUntilShutdown();
} catch (Exception e) {
LOG.error("rpc server start fail:", e);
throw new Exception("rpc server start fail:");
}
}
/**
* Stop grpc service
*/
private void stop() {
try {
LOG.info("start shutting down rpc server.....");
SERVER_IS_SHUTDOWN = true;
if (rpcServer != null) {
rpcServer.shutdown().awaitTermination(30, TimeUnit.SECONDS);
rpcServer = null;
}
LOG.info("shutting down rpc server end.");
} catch (Exception e) {
LOG.error("rpc server shut down exception", e);
}
}
/**
* Start daemon
*/
private void blockUntilShutdown() throws InterruptedException {
if (rpcServer != null) {
rpcServer.awaitTermination();
}
}
/**
* The interceptor class is converted to the corresponding instance
*
* @param interceptors interceptor class list
* @return Interceptor instance list
*/
private ServerInterceptor[] listToInstanceArray(List<Class<? extends ServerInterceptor>> interceptors) throws IllegalAccessException, InstantiationException {
ServerInterceptor[] instanceArray = new ServerInterceptor[interceptors.size()];
for (int i = 0; i < interceptors.size(); i++) {
instanceArray[i] = interceptors.get(i).newInstance();
}
return instanceArray;
}
}
| 35.741259 | 162 | 0.654666 |
ed2252362c4851d612ef08a02bf34840630fde31 | 1,672 | package com.ebay.dss.zds.message.sink;
import com.ebay.dss.zds.message.TaggedEvent;
import com.ebay.dss.zds.message.ZetaEvent;
import com.ebay.dss.zds.message.ZetaEventListener;
import com.ebay.dss.zds.message.event.TagMetricEvent;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.influxdb.InfluxDB;
import org.influxdb.dto.Point;
import javax.annotation.PreDestroy;
public class InfluxEventSink implements ZetaEventListener {
private static final Logger logger = LogManager.getLogger();
private InfluxDB db;
private Boolean enabled;
public Boolean getEnabled() {
return enabled;
}
public InfluxEventSink setEnabled(Boolean enabled) {
this.enabled = enabled;
return this;
}
public InfluxEventSink(InfluxDB db) {
this.db = db;
this.enabled = true;
}
@Override
public void onEventReceived(ZetaEvent zetaEvent) {
if (zetaEvent instanceof TaggedEvent.InfluxStorable) {
if (zetaEvent instanceof TagMetricEvent) {
Point point = Point.measurement(((TaggedEvent.InfluxStorable) zetaEvent).measurement())
.tag(((TagMetricEvent) zetaEvent).getTags())
.fields(((TagMetricEvent) zetaEvent).getMetrics())
.build();
db.write(point);
}
}
}
@PreDestroy
public void close() {
logger.info("shutdown influx event sink...");
db.flush();
db.close();
logger.info("shutdown influx event sink, done");
}
}
| 29.333333 | 103 | 0.654306 |
e2e89a8a7345ccff08991f7e7bd5c7e96f3d5bdd | 1,108 | /*
* Copyright 2016 FabricMC
*
* 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.fabricmc.loader.util.version;
import java.util.function.Predicate;
import net.fabricmc.loader.api.VersionParsingException;
import net.fabricmc.loader.api.metadata.version.VersionPredicate;
/**
* @deprecated Internal API, do not use
*/
@Deprecated
public final class SemanticVersionPredicateParser {
public static Predicate<SemanticVersionImpl> create(String text) throws VersionParsingException {
VersionPredicate predicate = VersionPredicate.parse(text);
return v -> predicate.test(v);
}
}
| 31.657143 | 98 | 0.767148 |
ae535a9499c9f6c0c5a9a21a0132a0db20f7e1b8 | 23,536 | package com.congtyhai.dms.calendar;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.congtyhai.adapter.CalendarAgencyAdapter;
import com.congtyhai.adapter.CalendarStatusAdapter;
import com.congtyhai.adapter.CommonItemAdapter;
import com.congtyhai.haidateicker.DatePickerTimeline;
import com.congtyhai.dms.BaseActivity;
import com.congtyhai.dms.R;
import com.congtyhai.model.api.AgencyInfo;
import com.congtyhai.model.api.CalendarCreateSend;
import com.congtyhai.model.api.CalendarDayCreate;
import com.congtyhai.model.api.CalendarStatus;
import com.congtyhai.model.api.ResultInfo;
import com.congtyhai.model.app.CalendarAgencyInfo;
import com.congtyhai.model.app.CommonItemInfo;
import com.congtyhai.util.HAIRes;
import com.congtyhai.view.DividerItemDecoration;
import com.congtyhai.view.RecyclerTouchListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CreateCalendarActivity extends BaseActivity {
int month;
int year;
int days;
@BindView(R.id.timeline)
DatePickerTimeline timeline;
@BindView(R.id.estatus)
Spinner eStatus;
@BindView(R.id.egroup)
Spinner eGroups;
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
@BindView(R.id.txtcus)
TextView txtcus;
@BindView(R.id.enotes)
EditText eNoets;
HashMap<String, List<CalendarAgencyInfo>> calendarAgencyMap;
CalendarAgencyAdapter mAdapter;
List<CommonItemInfo> groups;
HashMap<Integer, CalendarDayCreate> calendarDayMap;
// danh sach nhom chon hien tai
HashMap<Integer, String> dayGroupAgencyChooseMap;
List<CalendarAgencyInfo> agencyInfos;
List<CalendarAgencyInfo> agencyInfosTemp;
int daySelect = 1;
String groupSelect = "-1";
int maxChoose = 0;
boolean requireCheck = true;
// String statusNotChoice = "NoChoice";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_calendar);
createToolbar();
ButterKnife.bind(this);
Intent intent = getIntent();
maxChoose = intent.getIntExtra("MaxChoose", 60);
requireCheck = intent.getBooleanExtra("checkRequire", true);
calendarDayMap = new HashMap<>();
calendarAgencyMap = new HashMap<>();
dayGroupAgencyChooseMap = new HashMap<>();
agencyInfos = new ArrayList<>();
agencyInfosTemp = new ArrayList<>();
groups = new ArrayList<>();
createTimeLine();
// lisst status
createListStatus();
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setItemAnimator(new DefaultItemAnimator());
mAdapter = new CalendarAgencyAdapter(agencyInfos, this);
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
@Override
public void onClick(View view, int position) {
// check group la group nao
CalendarAgencyInfo info = agencyInfos.get(position);
boolean isCheck = true;
if (info.getCheck() == 1) {
agencyInfos.get(position).setCheck(0);
agencyInfos.get(position).removeDayChoose(daySelect);
configMapItem(true, info.getCode());
isCheck = false;
} else {
agencyInfos.get(position).addDayChoose(daySelect);
agencyInfos.get(position).setCheck(1);
configMapItem(false, info.getCode());
isCheck = true;
}
mAdapter.notifyDataSetChanged();
agencyInfosTemp.clear();
agencyInfosTemp.addAll(agencyInfos);
for (Map.Entry<String, List<CalendarAgencyInfo>> entry : calendarAgencyMap.entrySet()) {
List<CalendarAgencyInfo> values = entry.getValue();
for (int i = 0; i < values.size(); i++) {
if (info.getCode().equals(values.get(i).getCode())) {
if (isCheck) {
entry.getValue().get(i).addDayChoose(daySelect);
} else {
entry.getValue().get(i).removeDayChoose(daySelect);
}
}
}
}
}
@Override
public void onLongClick(View view, int position) {
}
}));
eNoets.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
calendarDayMap.get(daySelect).setNotes(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
});
new ReadDataTask().execute();
}
private void setStatusName() {
int count = calendarDayMap.get(daySelect).getAgencies().size();
txtcus.setText("Số khách hàng chọn: " + count);
}
private void createListStatus() {
CalendarStatusAdapter adapter = new CalendarStatusAdapter(this, HAIRes.getInstance().getCalendarStatuses());
eStatus.setAdapter(adapter);
if (!requireCheck) {
eStatus.setSelection(HAIRes.getInstance().findPostitionStatus("HOLIDAY"));
} else {
eStatus.setSelection(HAIRes.getInstance().findPostitionStatus(HAIRes.getInstance().CALENDAR_CSKH));
}
eStatus.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String code = HAIRes.getInstance().getCalendarStatuses().get(i).getId();
calendarDayMap.get(daySelect).setStatus(code);
if(code.equals("HOLIDAY")) {
timeline.getTimelineView().addMapDateTextColor(daySelect, ContextCompat.getColor(CreateCalendarActivity.this, R.color.mti_bg_lbl_date_selected_color_red) );
} else if (code.equals("CSKH")) {
timeline.getTimelineView().addMapDateTextColor(daySelect, ContextCompat.getColor(CreateCalendarActivity.this, R.color.mti_lbl_date));
} else if (code.equals("TVBD")) {
timeline.getTimelineView().addMapDateTextColor(daySelect, ContextCompat.getColor(CreateCalendarActivity.this, R.color.mti_color_blue));
} else {
timeline.getTimelineView().addMapDateTextColor(daySelect, ContextCompat.getColor(CreateCalendarActivity.this, R.color.mti_bg_lbl_date_selected_color_yellow));
}
timeline.getTimelineView().notifiAdapter();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void createListGroup() {
if (!requireCheck) {
groups.clear();
groups.add(new CommonItemInfo("Check in C2", "-1"));
groups.add(new CommonItemInfo("Check in không cố định", "kvl"));
calendarAgencyMap.put("kvl", new ArrayList<CalendarAgencyInfo>());
}
CommonItemAdapter commonItemAdapter = new CommonItemAdapter(CreateCalendarActivity.this, groups);
eGroups.setAdapter(commonItemAdapter);
eGroups.setSelection(findPostionGroup());
eGroups.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
CommonItemInfo commonItemInfo = groups.get(i);
groupSelect = commonItemInfo.getCode();
if (dayGroupAgencyChooseMap.containsKey(daySelect)) {
dayGroupAgencyChooseMap.remove(daySelect);
}
dayGroupAgencyChooseMap.put(daySelect, groupSelect);
refeshList();
//
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private class ReadDataTask extends AsyncTask<String, Integer, List<AgencyInfo>> {
protected List<AgencyInfo> doInBackground(String... urls) {
List<AgencyInfo> data = new ArrayList<>();
try {
data = getListAgency();
} catch (Exception e) {
}
return data;
}
@Override
protected void onPreExecute() {
showpDialog();
}
protected void onPostExecute(List<AgencyInfo> result) {
groups.add(new CommonItemInfo("Tất cả ", "-1"));
for (AgencyInfo info : result) {
CalendarAgencyInfo calendarAgencyInfo = new CalendarAgencyInfo(info.getDeputy(), info.getCode(), info.getName(), 0, info.getType());
calendarAgencyInfo.setDayChoose(new ArrayList<Integer>());
calendarAgencyInfo.setGroup(info.getGroup() + "");
calendarAgencyInfo.setRank(info.getRank());
if (!calendarAgencyMap.containsKey(info.getGroup())) {
calendarAgencyMap.put(info.getGroup(), new ArrayList<CalendarAgencyInfo>());
groups.add(new CommonItemInfo("Cụm " + info.getGroup(), info.getGroup() + ""));
}
calendarAgencyMap.get(info.getGroup()).add(calendarAgencyInfo);
}
refeshList();
createListGroup();
hidepDialog();
}
}
private int findPostionGroup() {
for (int i = 0; i < groups.size(); i++) {
if (groups.get(i).getCode().equals(groupSelect + "")) {
return i;
}
}
return 0;
}
private void makeRequest(CalendarCreateSend calendarCreateSend) {
showpDialog();
Call<ResultInfo> call = apiInterface().calendarCreate(calendarCreateSend);
call.enqueue(new Callback<ResultInfo>() {
@Override
public void onResponse(Call<ResultInfo> call, Response<ResultInfo> response) {
hidepDialog();
if (response.body().getId().equals("1")) {
commons.showAlertInfo(CreateCalendarActivity.this, "Cảnh báo", "Đã tạo lịch", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
} else {
commons.showAlertInfo(CreateCalendarActivity.this, "Cảnh báo", response.body().getMsg(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
}
}
@Override
public void onFailure(Call<ResultInfo> call, Throwable t) {
hidepDialog();
commons.makeToast(CreateCalendarActivity.this, "Lỗi đường truyền");
}
});
}
@Override
public void onBackPressed() {
commons.showAlertCancel(CreateCalendarActivity.this, "Cảnh báo", "Lịch sẽ không được lưu lại?", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
}
private void createTimeLine() {
Intent intent = getIntent();
String data = intent.getStringExtra(HAIRes.getInstance().KEY_INTENT_CREATE_CALENDAR);
String[] dataSplit = data.split("/");
if (dataSplit.length != 2) {
onBackPressed();
}
year = Integer.parseInt(dataSplit[1]);
month = Integer.parseInt(dataSplit[0]);
days = countDayInMonth(year, month);
timeline.setFirstVisibleDate(year, getCalendarMonth(month), 01);
timeline.setLastVisibleDate(year, getCalendarMonth(month), days);
timeline.getMonthView().setVisibility(View.GONE);
timeline.setOnDateSelectedListener(new DatePickerTimeline.OnDateSelectedListener() {
@Override
public void onDateSelected(int year, int month, int day, int index) {
daySelect = day;
groupSelect = dayGroupAgencyChooseMap.get(daySelect);
String statusCode = HAIRes.getInstance().getCalendarStatuses().get(eStatus.getSelectedItemPosition()).getId();
if (!calendarDayMap.get(daySelect).getStatus().equals(statusCode)) {
eStatus.setSelection(HAIRes.getInstance().findPostitionStatus(calendarDayMap.get(daySelect).getStatus()));
}
eGroups.setSelection(findPostionGroup());
eNoets.setText(calendarDayMap.get(daySelect).getNotes());
refeshList();
}
});
timeline.setSelectedDate(year, getCalendarMonth(month), 1);
daySelect = 1;
timeline.setFollowScroll(false);
// add map
for (int i = 1; i <= days; i++) {
CalendarDayCreate calendarDayCreate = new CalendarDayCreate();
calendarDayCreate.setAgencies(new ArrayList<String>());
calendarDayCreate.setDay(i);
calendarDayCreate.setNotes("");
if(requireCheck) {
calendarDayCreate.setStatus(HAIRes.getInstance().CALENDAR_CSKH);
timeline.getTimelineView().addMapDateTextColor(i, ContextCompat.getColor(CreateCalendarActivity.this, R.color.mti_lbl_date) );
}
else
{
timeline.getTimelineView().addMapDateTextColor(i, ContextCompat.getColor(CreateCalendarActivity.this, R.color.mti_bg_lbl_date_selected_color_red) );
calendarDayCreate.setStatus("HOLIDAY");
}
calendarDayMap.put(i, calendarDayCreate);
// set tat ca group hien thi tat ca
dayGroupAgencyChooseMap.put(i, "-1");
}
}
private void refeshList() {
agencyInfos.clear();
if (groupSelect.equals("-1")) {
for (Map.Entry<String, List<CalendarAgencyInfo>> entry : calendarAgencyMap.entrySet()) {
List<CalendarAgencyInfo> values = entry.getValue();
agencyInfos.addAll(values);
}
} else {
List<CalendarAgencyInfo> values = calendarAgencyMap.get(groupSelect);
agencyInfos.addAll(values);
}
CalendarDayCreate dayCreates = calendarDayMap.get(daySelect);
for (int i = 0; i < agencyInfos.size(); i++) {
if (dayCreates.getAgencies().contains(agencyInfos.get(i).getCode())) {
agencyInfos.get(i).setCheck(1);
} else {
agencyInfos.get(i).setCheck(0);
}
}
mAdapter.notifyDataSetChanged();
agencyInfosTemp.clear();
agencyInfosTemp.addAll(agencyInfos);
setStatusName();
}
private void configMapItem(boolean isRemove, String code) {
CalendarDayCreate dayCreates = calendarDayMap.get(daySelect);
if (isRemove) {
if (dayCreates.getAgencies().contains(code)) {
dayCreates.getAgencies().remove(code);
}
} else {
if (!dayCreates.getAgencies().contains(code)) {
dayCreates.getAgencies().add(code);
}
}
setStatusName();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_create_calendar, menu);
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.find_action).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
handleSearch(newText);
return false;
}
});
return true;
}
private void handleSearch(String query) {
agencyInfos.clear();
for(CalendarAgencyInfo info: agencyInfosTemp) {
if (info.getCode().contains(query) || info.getName().contains(query))
agencyInfos.add(info);
}
mAdapter.notifyDataSetChanged();
}
private boolean checkPolicy() {
if (!requireCheck) {
return true;
}
int countChoose = 0;
boolean chooseEnough = false;
// check so luong khach hang da chon
for (Map.Entry<String, List<CalendarAgencyInfo>> entry : calendarAgencyMap.entrySet()) {
List<CalendarAgencyInfo> values = entry.getValue();
for (CalendarAgencyInfo info : values) {
if (info.getDayChoose().size() != 0 && info.getType().equals("CII")) {
countChoose++;
}
}
}
if (calendarAgencyMap.size() > maxChoose){
if (countChoose < maxChoose) {
chooseEnough = false;
}else {
chooseEnough = true;
}
}
if (!chooseEnough) {
// kiem tra moi khach hang phai duoc tham it nhat 1 lan
for (Map.Entry<String, List<CalendarAgencyInfo>> entry : calendarAgencyMap.entrySet()) {
List<CalendarAgencyInfo> values = entry.getValue();
for (CalendarAgencyInfo info : values) {
if (info.getDayChoose().size() == 0 && info.getType().equals("CII")) {
commons.showAlertInfo(CreateCalendarActivity.this, "Cảnh báo", "Khách hàng : " + info.getDeputy() + " ( " + info.getCode() + " - Cụm " + info.getGroup() + ") chưa được thăm lần nào trong tháng", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return false;
}
}
}
}
// cac khach hang co lich cskh thi phai dc tham
for (Map.Entry<Integer, CalendarDayCreate> entry : calendarDayMap.entrySet()) {
// String key = entry.getKey().toString();
CalendarDayCreate value = entry.getValue();
CalendarStatus calendarStatus = findStatusById(value.getStatus());
if (calendarStatus == null) {
commons.showAlertInfo(CreateCalendarActivity.this, "Cảnh báo", "Sai thông tin", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return false;
}
if (calendarStatus.getCompel() == 1) {
if (value.getAgencies().size() < calendarStatus.getNumber()) {
commons.showAlertInfo(CreateCalendarActivity.this, "Cảnh báo", "Ngày " + value.getDay() + " phải đi thăm ít nhất " + calendarStatus.getNumber() + " /ngày", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return false;
}
}
}
return true;
}
private CalendarStatus findStatusById(String id) {
for (CalendarStatus item : HAIRes.getInstance().getCalendarStatuses()) {
if (item.getId().equals(id))
return item;
}
return null;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.next_action:
if (checkPolicy()) {
commons.showAlertCancel(CreateCalendarActivity.this, "Cảnh báo", "Bạn không thể chỉnh sửa lại nếu tiếp tục ?", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// save
String user = prefsHelper.get(HAIRes.getInstance().PREF_KEY_USER, "");
String token = prefsHelper.get(HAIRes.getInstance().PREF_KEY_TOKEN, "");
CalendarCreateSend calendarCreateSend = new CalendarCreateSend();
calendarCreateSend.setUser(user);
calendarCreateSend.setToken(token);
calendarCreateSend.setMonth(month);
calendarCreateSend.setYear(year);
calendarCreateSend.setItems(new ArrayList<CalendarDayCreate>());
for (Map.Entry<Integer, CalendarDayCreate> entry : calendarDayMap.entrySet()) {
// String key = entry.getKey();
CalendarDayCreate value = entry.getValue();
calendarCreateSend.getItems().add(value);
}
makeRequest(calendarCreateSend);
}
});
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| 36.042879 | 258 | 0.587823 |
576aa8d9b4a80a444731f55c79250d675b14a609 | 645 | package ru.mail.jira.plugins.groovy.impl.groovy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.mail.jira.plugins.groovy.api.script.ExecutionContext;
public class ExecutionContextHolder {
private final Logger logger = LoggerFactory.getLogger(ExecutionContextHolder.class);
private final ThreadLocal<ExecutionContext> context = ThreadLocal.withInitial(ExecutionContext::new);
public ExecutionContext get() {
if (logger.isTraceEnabled()) {
logger.trace("accessing execution context");
}
return context.get();
}
public void reset() {
context.remove();
}
}
| 29.318182 | 105 | 0.714729 |
42a1f32ea3319acd386d2a8e21929f9f472fd1fe | 20,683 | /*
* 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.sysml.api.monitoring;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.sysml.lops.Lop;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.instructions.Instruction;
import org.apache.sysml.runtime.instructions.spark.SPInstruction;
import org.apache.sysml.runtime.instructions.spark.functions.SparkListener;
import scala.collection.Seq;
import scala.xml.Node;
/**
* Usage guide:
* MLContext mlCtx = new MLContext(sc, true);
* mlCtx.register...
* mlCtx.execute(...)
* mlCtx.getMonitoringUtil().getRuntimeInfoInHTML("runtime.html");
*/
public class SparkMonitoringUtil {
private HashMap<String, String> lineageInfo = new HashMap<String, String>(); // instruction -> lineageInfo
private HashMap<String, Long> instructionCreationTime = new HashMap<String, Long>();
private MultiMap<Location, String> instructions = new MultiMap<Location, String>();
private MultiMap<String, Integer> stageIDs = new MultiMap<String, Integer>();
private MultiMap<String, Integer> jobIDs = new MultiMap<String, Integer>();
private MultiMap<Integer, String> rddInstructionMapping = new MultiMap<Integer, String>();
private HashSet<String> getRelatedInstructions(int stageID) {
HashSet<String> retVal = new HashSet<String>();
if(_sparkListener != null) {
ArrayList<Integer> rdds = _sparkListener.stageRDDMapping.get(stageID);
for(Integer rddID : rdds) {
retVal.addAll(rddInstructionMapping.get(rddID));
}
}
return retVal;
}
private SparkListener _sparkListener = null;
public SparkListener getSparkListener() {
return _sparkListener;
}
private String explainOutput = "";
public String getExplainOutput() {
return explainOutput;
}
public void setExplainOutput(String explainOutput) {
this.explainOutput = explainOutput;
}
public SparkMonitoringUtil(SparkListener sparkListener) {
_sparkListener = sparkListener;
}
public void addCurrentInstruction(SPInstruction inst) {
if(_sparkListener != null) {
_sparkListener.addCurrentInstruction(inst);
}
}
public void addRDDForInstruction(SPInstruction inst, Integer rddID) {
this.rddInstructionMapping.put(rddID, getInstructionString(inst));
}
public void removeCurrentInstruction(SPInstruction inst) {
if(_sparkListener != null) {
_sparkListener.removeCurrentInstruction(inst);
}
}
public void setDMLString(String dmlStr) {
this.dmlStrForMonitoring = dmlStr;
}
public void resetMonitoringData() {
if(_sparkListener != null && _sparkListener.stageDAGs != null)
_sparkListener.stageDAGs.clear();
if(_sparkListener != null && _sparkListener.stageTimeline != null)
_sparkListener.stageTimeline.clear();
}
// public Multimap<Location, String> hops = ArrayListMultimap.create(); TODO:
private String dmlStrForMonitoring = null;
public void getRuntimeInfoInHTML(String htmlFilePath) throws DMLRuntimeException, IOException {
String jsAndCSSFiles = "<script src=\"js/lodash.min.js\"></script>"
+ "<script src=\"js/jquery-1.11.1.min.js\"></script>"
+ "<script src=\"js/d3.min.js\"></script>"
+ "<script src=\"js/bootstrap-tooltip.js\"></script>"
+ "<script src=\"js/dagre-d3.min.js\"></script>"
+ "<script src=\"js/graphlib-dot.min.js\"></script>"
+ "<script src=\"js/spark-dag-viz.js\"></script>"
+ "<script src=\"js/timeline-view.js\"></script>"
+ "<script src=\"js/vis.min.js\"></script>"
+ "<link rel=\"stylesheet\" href=\"css/bootstrap.min.css\">"
+ "<link rel=\"stylesheet\" href=\"css/vis.min.css\">"
+ "<link rel=\"stylesheet\" href=\"css/spark-dag-viz.css\">"
+ "<link rel=\"stylesheet\" href=\"css/timeline-view.css\"> ";
BufferedWriter bw = new BufferedWriter(new FileWriter(htmlFilePath));
bw.write("<html><head>\n");
bw.write(jsAndCSSFiles + "\n");
bw.write("</head><body>\n<table border=1>\n");
bw.write("<tr>\n");
bw.write("<td><b>Position in script</b></td>\n");
bw.write("<td><b>DML</b></td>\n");
bw.write("<td><b>Instruction</b></td>\n");
bw.write("<td><b>StageIDs</b></td>\n");
bw.write("<td><b>RDD Lineage</b></td>\n");
bw.write("</tr>\n");
for(Location loc : instructions.keySet()) {
String dml = getExpression(loc);
// Sort the instruction with time - so as to separate recompiled instructions
List<String> listInst = new ArrayList<String>(instructions.get(loc));
Collections.sort(listInst, new InstructionComparator(instructionCreationTime));
if(dml != null && dml.trim().length() > 1) {
bw.write("<tr>\n");
int rowSpan = listInst.size();
bw.write("<td rowspan=\"" + rowSpan + "\">" + loc.toString() + "</td>\n");
bw.write("<td rowspan=\"" + rowSpan + "\">" + dml + "</td>\n");
boolean firstTime = true;
for(String inst : listInst) {
if(!firstTime)
bw.write("<tr>\n");
if(inst.startsWith("SPARK"))
bw.write("<td style=\"color:red\">" + inst + "</td>\n");
else if(isInterestingCP(inst))
bw.write("<td style=\"color:blue\">" + inst + "</td>\n");
else
bw.write("<td>" + inst + "</td>\n");
bw.write("<td>" + getStageIDAsString(inst) + "</td>\n");
if(lineageInfo.containsKey(inst))
bw.write("<td>" + lineageInfo.get(inst).replaceAll("\n", "<br />") + "</td>\n");
else
bw.write("<td></td>\n");
bw.write("</tr>\n");
firstTime = false;
}
}
}
bw.write("</table></body>\n</html>");
bw.close();
}
private String getInQuotes(String str) {
return "\"" + str + "\"";
}
private String getEscapedJSON(String json) {
if(json == null)
return "";
else {
return json
//.replaceAll("\\\\", "\\\\\\")
.replaceAll("\\t", "\\\\t")
.replaceAll("/", "\\\\/")
.replaceAll("\"", "\\\\\"")
.replaceAll("\\r?\\n", "\\\\n");
}
}
private long maxExpressionExecutionTime = 0;
HashMap<Integer, Long> stageExecutionTimes = new HashMap<Integer, Long>();
HashMap<String, Long> expressionExecutionTimes = new HashMap<String, Long>();
HashMap<String, Long> instructionExecutionTimes = new HashMap<String, Long>();
HashMap<Integer, HashSet<String>> relatedInstructionsPerStage = new HashMap<Integer, HashSet<String>>();
private void fillExecutionTimes() {
stageExecutionTimes.clear();
expressionExecutionTimes.clear();
for(Location loc : instructions.keySet()) {
List<String> listInst = new ArrayList<String>(instructions.get(loc));
long expressionExecutionTime = 0;
for(String inst : listInst) {
long instructionExecutionTime = 0;
for(Integer stageId : stageIDs.get(inst)) {
try {
if(getStageExecutionTime(stageId) != null) {
long stageExecTime = getStageExecutionTime(stageId);
instructionExecutionTime += stageExecTime;
expressionExecutionTime += stageExecTime;
stageExecutionTimes.put(stageId, stageExecTime);
}
}
catch(Exception e) {}
relatedInstructionsPerStage.put(stageId, getRelatedInstructions(stageId));
}
instructionExecutionTimes.put(inst, instructionExecutionTime);
}
expressionExecutionTime /= listInst.size(); // average
maxExpressionExecutionTime = Math.max(maxExpressionExecutionTime, expressionExecutionTime);
expressionExecutionTimes.put(loc.toString(), expressionExecutionTime);
}
// Now fill empty instructions
for(Entry<String, Long> kv : instructionExecutionTimes.entrySet()) {
if(kv.getValue() == 0) {
// Find all stages that contain this as related instruction
long sumExecutionTime = 0;
for(Entry<Integer, HashSet<String>> kv1 : relatedInstructionsPerStage.entrySet()) {
if(kv1.getValue().contains(kv.getKey())) {
sumExecutionTime += stageExecutionTimes.get(kv1.getKey());
}
}
kv.setValue(sumExecutionTime);
}
}
for(Location loc : instructions.keySet()) {
if(expressionExecutionTimes.get(loc.toString()) == 0) {
List<String> listInst = new ArrayList<String>(instructions.get(loc));
long expressionExecutionTime = 0;
for(String inst : listInst) {
expressionExecutionTime += instructionExecutionTimes.get(inst);
}
expressionExecutionTime /= listInst.size(); // average
maxExpressionExecutionTime = Math.max(maxExpressionExecutionTime, expressionExecutionTime);
expressionExecutionTimes.put(loc.toString(), expressionExecutionTime);
}
}
}
public String getRuntimeInfoInJSONFormat() throws DMLRuntimeException, IOException {
StringBuilder retVal = new StringBuilder("{\n");
retVal.append(getInQuotes("dml") + ":" + getInQuotes(getEscapedJSON(dmlStrForMonitoring)) + ",\n");
retVal.append(getInQuotes("expressions") + ":" + "[\n");
boolean isFirstExpression = true;
fillExecutionTimes();
for(Location loc : instructions.keySet()) {
String dml = getEscapedJSON(getExpressionInJSON(loc));
if(dml != null) {
// Sort the instruction with time - so as to separate recompiled instructions
List<String> listInst = new ArrayList<String>(instructions.get(loc));
Collections.sort(listInst, new InstructionComparator(instructionCreationTime));
if(!isFirstExpression) {
retVal.append(",\n");
}
retVal.append("{\n");
isFirstExpression = false;
retVal.append(getInQuotes("beginLine") + ":" + loc.beginLine + ",\n");
retVal.append(getInQuotes("beginCol") + ":" + loc.beginCol + ",\n");
retVal.append(getInQuotes("endLine") + ":" + loc.endLine + ",\n");
retVal.append(getInQuotes("endCol") + ":" + loc.endCol + ",\n");
long expressionExecutionTime = expressionExecutionTimes.get(loc.toString());
retVal.append(getInQuotes("expressionExecutionTime") + ":" + expressionExecutionTime + ",\n");
retVal.append(getInQuotes("expressionHeavyHitterFactor") + ":" + ((double)expressionExecutionTime / (double)maxExpressionExecutionTime) + ",\n");
retVal.append(getInQuotes("expression") + ":" + getInQuotes(dml) + ",\n");
retVal.append(getInQuotes("instructions") + ":" + "[\n");
boolean firstTime = true;
for(String inst : listInst) {
if(!firstTime)
retVal.append(", {");
else
retVal.append("{");
if(inst.startsWith("SPARK")) {
retVal.append(getInQuotes("isSpark") + ":" + "true,\n");
}
else if(isInterestingCP(inst)) {
retVal.append(getInQuotes("isInteresting") + ":" + "true,\n");
}
retVal.append(getStageIDAsJSONString(inst) + "\n");
if(lineageInfo.containsKey(inst)) {
retVal.append(getInQuotes("lineageInfo") + ":" + getInQuotes(getEscapedJSON(lineageInfo.get(inst))) + ",\n");
}
retVal.append(getInQuotes("instruction") + ":" + getInQuotes(getEscapedJSON(inst)));
retVal.append("}");
firstTime = false;
}
retVal.append("]\n");
retVal.append("}\n");
}
}
return retVal.append("]\n}").toString();
}
private boolean isInterestingCP(String inst) {
if(inst.startsWith("CP rmvar") || inst.startsWith("CP cpvar") || inst.startsWith("CP mvvar"))
return false;
else if(inst.startsWith("CP"))
return true;
else
return false;
}
private String getStageIDAsString(String instruction) {
String retVal = "";
for(Integer stageId : stageIDs.get(instruction)) {
String stageDAG = "";
String stageTimeLine = "";
if(getStageDAGs(stageId) != null) {
stageDAG = getStageDAGs(stageId).toString();
}
if(getStageTimeLine(stageId) != null) {
stageTimeLine = getStageTimeLine(stageId).toString();
}
retVal += "Stage:" + stageId +
" ("
+ "<div>"
+ stageDAG.replaceAll("toggleDagViz\\(false\\)", "toggleDagViz(false, this)")
+ "</div>, "
+ "<div id=\"timeline-" + stageId + "\">"
+ stageTimeLine
.replaceAll("drawTaskAssignmentTimeline\\(", "registerTimelineData(" + stageId + ", ")
.replaceAll("class=\"expand-task-assignment-timeline\"", "class=\"expand-task-assignment-timeline\" onclick=\"toggleStageTimeline(this)\"")
+ "</div>"
+ ")";
}
return retVal;
}
private String getStageIDAsJSONString(String instruction) {
long instructionExecutionTime = instructionExecutionTimes.get(instruction);
StringBuilder retVal = new StringBuilder(getInQuotes("instructionExecutionTime") + ":" + instructionExecutionTime + ",\n");
boolean isFirst = true;
if(stageIDs.get(instruction).size() == 0) {
// Find back references
HashSet<Integer> relatedStages = new HashSet<Integer>();
for(Entry<Integer, HashSet<String>> kv : relatedInstructionsPerStage.entrySet()) {
if(kv.getValue().contains(instruction)) {
relatedStages.add(kv.getKey());
}
}
HashSet<String> relatedInstructions = new HashSet<String>();
for(Entry<String, Integer> kv : stageIDs.entries()) {
if(relatedStages.contains(kv.getValue())) {
relatedInstructions.add(kv.getKey());
}
}
retVal.append(getInQuotes("backReferences") + ": [\n");
boolean isFirstRelInst = true;
for(String relInst : relatedInstructions) {
if(!isFirstRelInst) {
retVal.append(",\n");
}
retVal.append(getInQuotes(relInst));
isFirstRelInst = false;
}
retVal.append("], \n");
}
else {
retVal.append(getInQuotes("stages") + ": {");
for(Integer stageId : stageIDs.get(instruction)) {
String stageDAG = "";
String stageTimeLine = "";
if(getStageDAGs(stageId) != null) {
stageDAG = getStageDAGs(stageId).toString();
}
if(getStageTimeLine(stageId) != null) {
stageTimeLine = getStageTimeLine(stageId).toString();
}
long stageExecutionTime = stageExecutionTimes.get(stageId);
if(!isFirst) {
retVal.append(",\n");
}
retVal.append(getInQuotes("" + stageId) + ": {");
// Now add related instructions
HashSet<String> relatedInstructions = relatedInstructionsPerStage.get(stageId);
retVal.append(getInQuotes("relatedInstructions") + ": [\n");
boolean isFirstRelInst = true;
for(String relInst : relatedInstructions) {
if(!isFirstRelInst) {
retVal.append(",\n");
}
retVal.append(getInQuotes(relInst));
isFirstRelInst = false;
}
retVal.append("],\n");
retVal.append(getInQuotes("DAG") + ":")
.append(
getInQuotes(
getEscapedJSON(stageDAG.replaceAll("toggleDagViz\\(false\\)", "toggleDagViz(false, this)"))
) + ",\n"
)
.append(getInQuotes("stageExecutionTime") + ":" + stageExecutionTime + ",\n")
.append(getInQuotes("timeline") + ":")
.append(
getInQuotes(
getEscapedJSON(
stageTimeLine
.replaceAll("drawTaskAssignmentTimeline\\(", "registerTimelineData(" + stageId + ", ")
.replaceAll("class=\"expand-task-assignment-timeline\"", "class=\"expand-task-assignment-timeline\" onclick=\"toggleStageTimeline(this)\""))
)
)
.append("}");
isFirst = false;
}
retVal.append("}, ");
}
retVal.append(getInQuotes("jobs") + ": {");
isFirst = true;
for(Integer jobId : jobIDs.get(instruction)) {
String jobDAG = "";
if(getJobDAGs(jobId) != null) {
jobDAG = getJobDAGs(jobId).toString();
}
if(!isFirst) {
retVal.append(",\n");
}
retVal.append(getInQuotes("" + jobId) + ": {")
.append(getInQuotes("DAG") + ":" )
.append(getInQuotes(
getEscapedJSON(jobDAG.replaceAll("toggleDagViz\\(true\\)", "toggleDagViz(true, this)"))
) + "}\n");
isFirst = false;
}
retVal.append("}, ");
return retVal.toString();
}
String [] dmlLines = null;
private String getExpression(Location loc) {
try {
if(dmlLines == null) {
dmlLines = dmlStrForMonitoring.split("\\r?\\n");
}
if(loc.beginLine == loc.endLine) {
return dmlLines[loc.beginLine-1].substring(loc.beginCol-1, loc.endCol);
}
else {
String retVal = dmlLines[loc.beginLine-1].substring(loc.beginCol-1);
for(int i = loc.beginLine+1; i < loc.endLine; i++) {
retVal += "<br />" + dmlLines[i-1];
}
retVal += "<br />" + dmlLines[loc.endLine-1].substring(0, loc.endCol);
return retVal;
}
}
catch(Exception e) {
return null; // "[[" + loc.beginLine + "," + loc.endLine + "," + loc.beginCol + "," + loc.endCol + "]]";
}
}
private String getExpressionInJSON(Location loc) {
try {
if(dmlLines == null) {
dmlLines = dmlStrForMonitoring.split("\\r?\\n");
}
if(loc.beginLine == loc.endLine) {
return dmlLines[loc.beginLine-1].substring(loc.beginCol-1, loc.endCol);
}
else {
String retVal = dmlLines[loc.beginLine-1].substring(loc.beginCol-1);
for(int i = loc.beginLine+1; i < loc.endLine; i++) {
retVal += "\\n" + dmlLines[i-1];
}
retVal += "\\n" + dmlLines[loc.endLine-1].substring(0, loc.endCol);
return retVal;
}
}
catch(Exception e) {
return null; // "[[" + loc.beginLine + "," + loc.endLine + "," + loc.beginCol + "," + loc.endCol + "]]";
}
}
public Seq<Node> getStageDAGs(int stageIDs) {
if(_sparkListener == null || _sparkListener.stageDAGs == null)
return null;
else
return _sparkListener.stageDAGs.get(stageIDs);
}
public Long getStageExecutionTime(int stageID) {
if(_sparkListener == null || _sparkListener.stageDAGs == null)
return null;
else
return _sparkListener.stageExecutionTime.get(stageID);
}
public Seq<Node> getJobDAGs(int jobID) {
if(_sparkListener == null || _sparkListener.jobDAGs == null)
return null;
else
return _sparkListener.jobDAGs.get(jobID);
}
public Seq<Node> getStageTimeLine(int stageIDs) {
if(_sparkListener == null || _sparkListener.stageTimeline == null)
return null;
else
return _sparkListener.stageTimeline.get(stageIDs);
}
public void setLineageInfo(Instruction inst, String plan) {
lineageInfo.put(getInstructionString(inst), plan);
}
public void setStageId(Instruction inst, int stageId) {
stageIDs.put(getInstructionString(inst), stageId);
}
public void setJobId(Instruction inst, int jobId) {
jobIDs.put(getInstructionString(inst), jobId);
}
public void setInstructionLocation(Location loc, Instruction inst) {
String instStr = getInstructionString(inst);
instructions.put(loc, instStr);
instructionCreationTime.put(instStr, System.currentTimeMillis());
}
private String getInstructionString(Instruction inst) {
String tmp = inst.toString();
tmp = tmp.replaceAll(Lop.OPERAND_DELIMITOR, " ");
tmp = tmp.replaceAll(Lop.DATATYPE_PREFIX, ".");
tmp = tmp.replaceAll(Lop.INSTRUCTION_DELIMITOR, ", ");
return tmp;
}
public class MultiMap<K, V extends Comparable<V>> {
private SortedMap<K, List<V>> m = new TreeMap<K, List<V>>();
public MultiMap(){
}
public void put(K key, V value) {
List<V> list;
if (!m.containsKey(key)) {
list = new ArrayList<V>();
m.put(key, list);
} else {
list = m.get(key);
}
list.add(value);
Collections.sort(list);
}
public Collection<Entry<K, V>> entries() {
// the treemap is sorted and the lists are sorted, so can traverse
// to generate a key/value ordered list of all entries.
Collection<Entry<K, V>> allEntries = new ArrayList<Entry<K, V>>();
for (K key : m.keySet()) {
List<V> list = m.get(key);
for (V value : list) {
Entry<K, V> listEntry = new SimpleEntry<K, V>(key, value);
allEntries.add(listEntry);
}
}
return allEntries;
}
public List<V> get(K key) {
return m.get(key);
}
public Set<K> keySet() {
return m.keySet();
}
}
}
| 32.77813 | 149 | 0.65856 |
c6b501e82525df7d4d021c14501ef907747678bc | 475 | package com.virex.admclient.network;
/**
* Вспомогательный класс для отправки POST запросов
*/
public class PostBody {
public interface OnPostCallback{
void onError(String message);
void onSuccess(String message);
}
/*
public String n;
public String id;
public String name;//login
public String topsw;//password
public String email;
public String signature;
public String text;
public String add2="Добавить";
*/
}
| 19.791667 | 51 | 0.68 |
213a2a6fad148616d5bfe3b5c52de8fced4dfa1d | 4,137 | /**
* Copyright 2017 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 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.
*
* @author Roman Dolomansky (rdolomansky@productengine.com)
*/
package com.comcast.redirector.thucydides.steps.changes;
import com.comcast.redirector.thucydides.pages.changes.ChangesPage;
import com.comcast.redirector.thucydides.tests.main.changes.PendingChangeType;
import net.thucydides.core.annotations.Step;
import net.thucydides.core.steps.ScenarioSteps;
import net.thucydides.junit.runners.ThucydidesRunner;
import org.junit.runner.RunWith;
@RunWith(ThucydidesRunner.class)
public class ChangesPageSteps extends ScenarioSteps {
private ChangesPage page;
public ChangesPage changesPage() {
return getPages().currentPageAt(ChangesPage.class);
}
@Step
public ChangesPageSteps clickApproveAllChangesButton() {
page.clickApproveAllChangesButton();
return this;
}
@Step
public ChangesPageSteps clickCancelAllChangesButton() {
page.clickCancelAllChangesButton();
return this;
}
@Step
public ChangesPageSteps clickTriggerReloadModelButton() {
page.clickTriggerReloadModelButton();
return this;
}
@Step
public ChangesPageSteps clickDownloadCoreBackupButton() {
page.clickDownloadCoreBackupButton();
return this;
}
@Step
public ChangesPageSteps clickApproveDistributionChangesButton() {
page.clickApproveDistributionChangesButton();
return this;
}
@Step
public ChangesPageSteps clickCancelDistributionChangesButton() {
page.clickCancelDistributionChangesButton();
return this;
}
@Step
public ChangesPageSteps clickExportDistributionChangesButton() {
page.clickExportDistributionChangesButton();
return this;
}
@Step
public ChangesPageSteps refreshPage() {
page.getDriver().navigate().refresh();
return this;
}
@Step
public ChangesPageSteps openPage() {
page.open();
page.waitFor(2).seconds();
return this;
}
@Step
public ChangesPageSteps approveChange(final PendingChangeType changeType, final String name) {
waitFor(700).milliseconds();
page.approveChange(changeType, name);
return this;
}
@Step
public ChangesPageSteps cancelChange(final PendingChangeType changeType, final String name) {
waitFor(500).milliseconds();
page.cancelChange(changeType, name);
return this;
}
@Step
public ChangesPageSteps exportChange(final PendingChangeType changeType, final String name) {
page.exportChange(changeType, name);
return this;
}
@Step
public ChangesPageSteps exportDistributionChange(final int idx) {
page.exportDistributionChange(idx);
return this;
}
@Step
public ChangesPageSteps isChangeNotPresent(final PendingChangeType changeType, final String ruleName) {
waitFor(500).milliseconds();
page.isChangeNotPresent(changeType, ruleName);
return this;
}
@Step
public ChangesPageSteps isChangePresent(final PendingChangeType changeType, final String ruleName) {
page.isChangePresent(changeType, ruleName);
return this;
}
@Step
public ChangesPageSteps isDistributionSectionNotPresent() {
page.isDistributionSectionNotPresent();
return this;
}
@Step
public ChangesPageSteps isDistributionSectionPresent() {
page.isDistributionSectionPresent();
return this;
}
}
| 26.350318 | 107 | 0.70365 |
71e9419864cdef4029cefb6979378e030afc5eef | 3,806 | package com.grouleff.pumpcontrol;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Random;
public class Client extends Thread {
private static final int REVC_PKG_TIMEOUT = 2000;
private static final long IDLE_TIME_OUT = 60 * 1000;
private final Socket clientSocket;
private RXTXLink dongle;
public Client(Socket clientSocket, String name) {
super(name);
this.clientSocket = clientSocket;
setDaemon(true);
start();
}
@Override
public void run() {
try {
clientSocket.setSoTimeout(MI301DongleProxy.SO_TIMEOUT);
dongle = MI301DongleProxy.getLink(); // throws if it fails...
resetDongle();
long lastUse = System.currentTimeMillis();
while (true) {
int len = handle();
if (len > 0) {
lastUse = System.currentTimeMillis();
}
if (System.currentTimeMillis() - lastUse > IDLE_TIME_OUT) {
return;
}
}
} catch (java.net.SocketException e) {
//fine.
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dongle != null) {
MI301DongleProxy.releaseLink(dongle);
}
try {
clientSocket.close();
} catch (IOException e) {
}
}
}
private void resetDongle() throws IOException {
Packet reset = rslpBegin(2);
reset.addByte((byte)3);
reset.addByte((byte)7); // reset dongle.
reset.addByte((byte)0);
reset.addByte((byte)0);
reset.updateLengthAndCheckSum();
reset.writeTo(dongle.getOutputStream(), false);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
private Packet rslpBegin(int payloadLength) {
Packet rslp = new Packet();
rslp.addByte((byte)0x27);
rslp.addByte((byte)(payloadLength + 2));
rslp.addByte((byte)0); // to dongle
rslp.addByte((byte)1); // seqno.
return rslp;
}
Random random = new Random();
public int copyPacket(InputStream inputStream, OutputStream outputStream, String dir) throws IOException {
Packet in = new Packet();
long startedAt = System.currentTimeMillis();
while (!in.isComplete()) {
in.readFrom(inputStream);
long time = System.currentTimeMillis() - startedAt;
if (in.getTop() == 0 && time > REVC_PKG_TIMEOUT) {
break; // If nothing has been received, break out of loop.
}
if (in.getTop() > 0 && time > IDLE_TIME_OUT) {
break; // Give up after idle timeout.
}
}
if (in.isComplete()) {
System.out.println(dir + " " + in);
in.writeTo(outputStream, false);
return in.getLength();
} else {
System.out.println(dir + " INCOMPLETE " + in);
return 0;
}
}
private int handle() throws IOException {
int len = copyPacket(clientSocket.getInputStream(), dongle.getOutputStream(), ">>>");
len += copyPacket(dongle.getInputStream(), clientSocket.getOutputStream(), "<<<");
return len;
}
private static String hex(byte[] buffer, int top) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < top; i++) {
hex(buffer[i], sb);
if (((i+1) % 16) == 0) {
sb.append("\n ");
} else {
sb.append(' ');
}
}
return sb.toString();
}
private static void hex(byte b, StringBuilder sb) {
String hexString = Integer.toHexString(((int)b) & 0xff);
if (hexString.length() < 2) {
sb.append('0');
}
sb.append(hexString.toUpperCase());
}
}
| 29.503876 | 110 | 0.567525 |
038047b9d38767224e3510fbc2763c59e41f8139 | 525 | package com.meterware.httpunit;
/**
* A listener for DNS Requests. Users may implement this interface to bypass the normal DNS lookup.
*
* @author <a href="russgold@httpunit.org">Russell Gold</a>
**/
public interface DNSListener {
/**
* Returns the IP address as a string for the specified host name.
* Note: no validation is done to verify that the returned value is an actual IP address or
* that the passed host name was not an IP address.
**/
String getIpAddress( String hostName );
}
| 27.631579 | 99 | 0.697143 |
9f66c0fb78716faa674957e2c18f4dceaccf6bc9 | 2,049 | package com.yz.enums;
/**
* es分词
* 更多请查询官网
*
*/
public enum AnalyzerEnum {
/**
* 不分词
* 结果同 STANDARD
*/
DEFUALT(0, ""),
/**
* 标准分词,按词切分,字母小写,无下划线
* heLLo World 2018 _ ----> hello, world ,2018
*/
STANDARD(1, "standard"),
/**
* 按照非字符切分,全部小写,数字和下划线等不会分词
* heLLo World 2018 _ ----> hello, world ,2018
*/
SIMPLE(2, "simple"),
/**
* 按照空格切分,不区分大小写,有数字和下划线等
* heLLo World 2018 _ ----> heLLo, World ,2018,_
*/
WHITESPACE(3, "whitespace"),
/**
* stop word指语气助词等修饰性的词语,比如the,an,的,这等等
* 在simple的基础上多了stop word的使用
*/
STOP(4, "stop"),
/**
* 不分词,不想对文本进行分词的时候使用
* 对整个词当做一个关键字处理
*/
KEYWORD(5, "keyword"),
/**
* 通过正则表达式区分
* 默认是\w+,即非字词的符号作为分隔符
* <p>
* the heLLo 'World -2018 ---> the,hello,world,2018
*/
PATTERN(6, "pattern"),
/**
* ik分词器
*/
IK(7, "ik_max_word");
private int code;
private String name;
public int getCode( ) {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getName( ) {
return name;
}
public void setName(String name) {
this.name = name;
}
AnalyzerEnum(int code, String name) {
this.code = code;
this.name = name;
}
/**
* 根据code获取性别枚举对象
*
* @param code
* @return
*/
public static AnalyzerEnum getAnalyzerEnum(int code) {
for (AnalyzerEnum analyzerEnum : AnalyzerEnum.values()) {
if (code == analyzerEnum.getCode()) {
return analyzerEnum;
}
}
return null;
}
/**
* 根据code获取名称
*
* @param code
* @return
*/
public static String getNameByCode(int code) {
for (AnalyzerEnum analyzerEnum : AnalyzerEnum.values()) {
if (code == analyzerEnum.getCode()) {
return analyzerEnum.getName();
}
}
return "";
}
}
| 17.817391 | 65 | 0.499268 |
e3121c9512d46af45a6a141b14a9588cd4f8b083 | 5,335 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.security.authz;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.index.shard.SearchOperationListener;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.search.SearchContextMissingException;
import org.elasticsearch.search.internal.ScrollContext;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.xpack.security.audit.AuditTrailService;
import org.elasticsearch.xpack.core.security.authc.Authentication;
import org.elasticsearch.xpack.core.security.authc.AuthenticationField;
import static org.elasticsearch.xpack.security.authz.AuthorizationService.ORIGINATING_ACTION_KEY;
import static org.elasticsearch.xpack.security.authz.AuthorizationService.ROLE_NAMES_KEY;
/**
* A {@link SearchOperationListener} that is used to provide authorization for scroll requests.
*
* In order to identify the user associated with a scroll request, we replace the {@link ScrollContext}
* on creation with a custom implementation that holds the {@link Authentication} object. When
* this context is accessed again in {@link SearchOperationListener#onPreQueryPhase(SearchContext)}
* the ScrollContext is inspected for the authentication, which is compared to the currently
* authentication.
*/
public final class SecuritySearchOperationListener implements SearchOperationListener {
private final ThreadContext threadContext;
private final XPackLicenseState licenseState;
private final AuditTrailService auditTrailService;
public SecuritySearchOperationListener(ThreadContext threadContext, XPackLicenseState licenseState, AuditTrailService auditTrail) {
this.threadContext = threadContext;
this.licenseState = licenseState;
this.auditTrailService = auditTrail;
}
/**
* Adds the {@link Authentication} to the {@link ScrollContext}
*/
@Override
public void onNewScrollContext(SearchContext searchContext) {
if (licenseState.isAuthAllowed()) {
searchContext.scrollContext().putInContext(AuthenticationField.AUTHENTICATION_KEY,
Authentication.getAuthentication(threadContext));
}
}
/**
* Checks for the {@link ScrollContext} if it exists and compares the {@link Authentication}
* object from the scroll context with the current authentication context
*/
@Override
public void validateSearchContext(SearchContext searchContext, TransportRequest request) {
if (licenseState.isAuthAllowed()) {
if (searchContext.scrollContext() != null) {
final Authentication originalAuth = searchContext.scrollContext().getFromContext(AuthenticationField.AUTHENTICATION_KEY);
final Authentication current = Authentication.getAuthentication(threadContext);
final String action = threadContext.getTransient(ORIGINATING_ACTION_KEY);
ensureAuthenticatedUserIsSame(originalAuth, current, auditTrailService, searchContext.id(), action, request,
threadContext.getTransient(ROLE_NAMES_KEY));
}
}
}
/**
* Compares the {@link Authentication} that was stored in the {@link ScrollContext} with the
* current authentication. We cannot guarantee that all of the details of the authentication will
* be the same. Some things that could differ include the roles, the name of the authenticating
* (or lookup) realm. To work around this we compare the username and the originating realm type.
*/
static void ensureAuthenticatedUserIsSame(Authentication original, Authentication current, AuditTrailService auditTrailService,
long id, String action, TransportRequest request, String[] roleNames) {
// this is really a best effort attempt since we cannot guarantee principal uniqueness
// and realm names can change between nodes.
final boolean samePrincipal = original.getUser().principal().equals(current.getUser().principal());
final boolean sameRealmType;
if (original.getUser().isRunAs()) {
if (current.getUser().isRunAs()) {
sameRealmType = original.getLookedUpBy().getType().equals(current.getLookedUpBy().getType());
} else {
sameRealmType = original.getLookedUpBy().getType().equals(current.getAuthenticatedBy().getType());
}
} else if (current.getUser().isRunAs()) {
sameRealmType = original.getAuthenticatedBy().getType().equals(current.getLookedUpBy().getType());
} else {
sameRealmType = original.getAuthenticatedBy().getType().equals(current.getAuthenticatedBy().getType());
}
final boolean sameUser = samePrincipal && sameRealmType;
if (sameUser == false) {
auditTrailService.accessDenied(current, action, request, roleNames);
throw new SearchContextMissingException(id);
}
}
}
| 52.303922 | 137 | 0.729897 |
642b0b53bb32ce8324efce9ae312352901161114 | 287 | package simpletextoverlay.printer;
import java.io.File;
import java.util.List;
import java.util.Map;
import simpletextoverlay.util.Alignment;
import simpletextoverlay.value.Value;
public interface IPrinter {
boolean print(File file, Map<Alignment, List<List<Value>>> format);
}
| 19.133333 | 71 | 0.783972 |
e7aadb13efbc7858fa7a4c4c016b216771d366d9 | 899 | package ru.alttiri.stepik.contest_java.functionals;
/**
2.10 Too many arguments
Write a lambda expression that accepts seven (!) string arguments and returns a string in upper case
concatenated from all of them (in the order of arguments).
You may write the expression in any valid format but with ; on the end.
Examples: (x, y) -> x + y; (x, y) -> { return x + y; };
Sample Input:
The lambda has too many string arguments.
Sample Output:
THELAMBDAHASTOOMANYSTRINGARGUMENTS.
*/
public class Main10 {
public static void main(String[] args) {
// (String q, String w, String e, String r, String t, String y, String u) ->
// new StringBuilder(q).append(w).append(e).append(r).append(t).append(y).append(u).toString().toUpperCase();
// или так
// (q, w, e, r, t, y, u) ->
// (q + w + e + r + t + y + u).toUpperCase();
}
}
| 26.441176 | 124 | 0.627364 |
ae12fd25aee2d7b06f0fbb7a451aa76d2568fdaf | 399 | package com.tcmj.pm.spread;
import com.tcmj.pm.spread.impl.SpreadDoubleImpl;
/**
* SpreadCalculatorFactory.
* @author Thomas Deutsch <thomas-deutsch(a.t)tcmj.de>
* @since 30.01.2011
*/
public class SpreadCalculatorFactory {
/**
* default no-arg-constructor.
*/
public static SpreadCalculator getSpreadCalculatorDoubleImpl() {
return new SpreadDoubleImpl();
}
}
| 19.95 | 68 | 0.696742 |
c6955da39dd2e5fb926660d25445528eff382bc9 | 3,122 | package starter.stepdefinitions;
import Data.TestData;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import net.thucydides.core.annotations.Steps;
import org.junit.jupiter.api.Assertions;
import starter.navigation.DirectLineFormActions;
import java.util.List;
public class GetQuoteStepDefinitions {
//Used to interact with the webpage
@Steps
DirectLineFormActions directLineFormActions;
@Given("The user has accessed the website")
public void the_customer_has_accessed_the_website() {
//Sets the URL to the Direct Line Quote page
directLineFormActions.toQuotePage();
}
@Given("user has accepted the cookies")
public void accepted_the_cookies() {
//Click on the accept cookies button (otherwise nothing else on the website is interactive)
directLineFormActions.acceptCookies();
}
@When("the user enters {string} as the registation number")
public void theUserEntersAsTheRegistationNumber(String testPlate) {
directLineFormActions.enterRegistration(testPlate);
}
@When("click submit")
public void click_submit() {
directLineFormActions.clickSubmitButton();
}
@Then("the website will show the users car {string}")
public void theWebsiteWillShowTheUsersCar(String carType) {
//Checks the Car Type
List<String> detailsReturned = directLineFormActions.getCarDetails();
Assertions.assertEquals(carType, detailsReturned.get(0),"Wrong Car Type returned - Test Failed");
}
@And("the users car {string}")
public void theUsersCar(String carDesc) {
//Checks the Car Description
List <String> detailsReturned = directLineFormActions.getCarDetails();
Assertions.assertEquals(carDesc, detailsReturned.get(1),"Wrong Car Description returned - Test Failed");
}
@Given("The user wants to check if their car has been modified")
public void theUserWantsToCheckIfTheirCarHasBeenModified() {
//The user navigates the quote page
directLineFormActions.toQuotePage();
}
@When("the user clicks the more info button")
public void theUserClicksTheMoreInfoButton() {
directLineFormActions.interactInformationButton();
}
@Then("the more info text will be shown to the user")
public void theMoreInfoTextWillBeShownToTheUser() {
Assertions.assertEquals(TestData.MODIFIED_HINT, directLineFormActions.returnModInfo(), "Wrong Description returned - Test Failed");
}
@Given("The user doesn't know their car registration")
public void theUserDoesnTKnowTheirCarRegistration() {
}
@When("the user enters their car make")
public void theUserEntersTheirCarMake() {
}
@And("the user answers the quote questions")
public void theUserAnswersTheQuoteQuestions() {
}
@And("the user enters their car worth")
public void theUserEntersTheirCarWorth() {
}
@And("the user enters their estimated mileage")
public void theUserEntersTheirEstimatedMileage() {
}
}
| 33.212766 | 139 | 0.721653 |
753621232c1447f3930fb17e478db863d09d78da | 109 | package com.irtimaled.bbor.client.gui;
interface IRowHeight extends IControl {
double getRowHeight();
}
| 18.166667 | 39 | 0.770642 |
c5d00888974cf801693032fecb88a9dead3bef7a | 3,519 |
package redox.datamodel.clinicalsummary.common;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import redox.datamodel.common.Address;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"Identifiers",
"LastName",
"MiddleName",
"FirstName",
"SSN",
"Relationship",
"DOB",
"Sex",
"Address"
})
public class Insured {
@JsonProperty("Identifiers")
private List<Object> identifiers = null;
@JsonProperty("LastName")
private String lastName;
@JsonProperty("MiddleName")
private String middleName;
@JsonProperty("FirstName")
private String firstName;
@JsonProperty("SSN")
private Object sSN;
@JsonProperty("Relationship")
private Object relationship;
@JsonProperty("DOB")
private Object dOB;
@JsonProperty("Sex")
private Object sex;
@JsonProperty("Address")
private Address address;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("Identifiers")
public List<Object> getIdentifiers() {
return identifiers;
}
@JsonProperty("Identifiers")
public void setIdentifiers(List<Object> identifiers) {
this.identifiers = identifiers;
}
@JsonProperty("LastName")
public String getLastName() {
return lastName;
}
@JsonProperty("LastName")
public void setLastName(String lastName) {
this.lastName = lastName;
}
@JsonProperty("MiddleName")
public String getMiddleName() {
return middleName;
}
@JsonProperty("MiddleName")
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
@JsonProperty("FirstName")
public String getFirstName() {
return firstName;
}
@JsonProperty("FirstName")
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@JsonProperty("SSN")
public Object getSSN() {
return sSN;
}
@JsonProperty("SSN")
public void setSSN(Object sSN) {
this.sSN = sSN;
}
@JsonProperty("Relationship")
public Object getRelationship() {
return relationship;
}
@JsonProperty("Relationship")
public void setRelationship(Object relationship) {
this.relationship = relationship;
}
@JsonProperty("DOB")
public Object getDOB() {
return dOB;
}
@JsonProperty("DOB")
public void setDOB(Object dOB) {
this.dOB = dOB;
}
@JsonProperty("Sex")
public Object getSex() {
return sex;
}
@JsonProperty("Sex")
public void setSex(Object sex) {
this.sex = sex;
}
@JsonProperty("Address")
public Address getAddress() {
return address;
}
@JsonProperty("Address")
public void setAddress(Address address) {
this.address = address;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
| 23.304636 | 85 | 0.662972 |
e4b005eef3c2aa8a5f3c817e92ba8266dddf78cd | 854 | package pgjdbcdemo;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author hom
*/
public class SQLInjectionDemo {
public static void main( String[] args ) throws
SQLException {
if (args.length < 1) {
System.out.println( "no arguments" );
System.exit(1);
}
System.out.println( "args[0] = [" + args[0] +']');
String sqlTemplate = "select * from president where name like '%s'";
String sql = String.format( sqlTemplate, args[0] );
try ( Connection con = PgJDBCDemo.createDemoConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery( sql ); ) {
new ResultSetPrinter( rs ).printTable( System.out );
}
}
}
| 27.548387 | 76 | 0.58548 |
40e9bf844f03771f551ad7b970285295e7ebd99d | 5,489 | package org.slos.query;
import java.util.List;
public class BattleTeamRecord {
private Integer rank;
private String color;
private String simpleHash;
private CardRecord summoner;
private List<CardRecord> monsters;
private Integer totalMana;
private Integer totalAttackDamage;
private Integer totalRangedDamage;
private Integer totalMagicDamage;
private Integer totalArmor;
private Integer totalHealth;
private Integer totalSpeed;
private Integer totalArmorHeal;
private Integer totalHealthHeal;
private Float weightedLevelAverage;
public BattleTeamRecord() {}
public BattleTeamRecord(Integer rank, String color, String simpleHash, CardRecord summoner, List<CardRecord> monsters, Integer totalMana, Integer totalAttackDamage, Integer totalRangedDamage, Integer totalMagicDamage, Integer totalArmor, Integer totalHealth, Integer totalSpeed, Integer totalArmorHeal, Integer totalHealthHeal, Float weightedLevelAverage) {
this.rank = rank;
this.color = color;
this.simpleHash = simpleHash;
this.summoner = summoner;
this.monsters = monsters;
this.totalMana = totalMana;
this.totalAttackDamage = totalAttackDamage;
this.totalRangedDamage = totalRangedDamage;
this.totalMagicDamage = totalMagicDamage;
this.totalArmor = totalArmor;
this.totalHealth = totalHealth;
this.totalSpeed = totalSpeed;
this.totalArmorHeal = totalArmorHeal;
this.totalHealthHeal = totalHealthHeal;
this.weightedLevelAverage = weightedLevelAverage;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public void setSimpleHash(String simpleHash) {
this.simpleHash = simpleHash;
}
public String getSimpleHash() {
StringBuffer simpleHash = new StringBuffer();
simpleHash.append(summoner.getMonsterId()+"-");
int monsterCount = 0;
for (CardRecord cardRecord : getMonsters()) {
simpleHash.append(cardRecord.getMonsterId());
if (monsterCount < getMonsters().size() - 1) {
simpleHash.append("-");
}
monsterCount++;
}
return simpleHash.toString();
}
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
public CardRecord getSummoner() {
return summoner;
}
public void setSummoner(CardRecord summoner) {
this.summoner = summoner;
}
public List<CardRecord> getMonsters() {
return monsters;
}
public void setMonsters(List<CardRecord> monsters) {
this.monsters = monsters;
}
public Integer getTotalMana() {
return totalMana;
}
public void setTotalMana(Integer totalMana) {
this.totalMana = totalMana;
}
public Integer getTotalAttackDamage() {
return totalAttackDamage;
}
public void setTotalAttackDamage(Integer totalAttackDamage) {
this.totalAttackDamage = totalAttackDamage;
}
public Integer getTotalRangedDamage() {
return totalRangedDamage;
}
public void setTotalRangedDamage(Integer totalRangedDamage) {
this.totalRangedDamage = totalRangedDamage;
}
public Integer getTotalMagicDamage() {
return totalMagicDamage;
}
public void setTotalMagicDamage(Integer totalMagicDamage) {
this.totalMagicDamage = totalMagicDamage;
}
public Integer getTotalArmor() {
return totalArmor;
}
public void setTotalArmor(Integer totalArmor) {
this.totalArmor = totalArmor;
}
public Integer getTotalHealth() {
return totalHealth;
}
public void setTotalHealth(Integer totalHealth) {
this.totalHealth = totalHealth;
}
public Integer getTotalSpeed() {
return totalSpeed;
}
public void setTotalSpeed(Integer totalSpeed) {
this.totalSpeed = totalSpeed;
}
public Integer getTotalArmorHeal() {
return totalArmorHeal;
}
public void setTotalArmorHeal(Integer totalArmorHeal) {
this.totalArmorHeal = totalArmorHeal;
}
public Integer getTotalHealthHeal() {
return totalHealthHeal;
}
public void setTotalHealthHeal(Integer totalHealthHeal) {
this.totalHealthHeal = totalHealthHeal;
}
public Float getWeightedLevelAverage() {
return weightedLevelAverage;
}
public void setWeightedLevelAverage(Float weightedLevelAverage) {
this.weightedLevelAverage = weightedLevelAverage;
}
@Override
public String toString() {
return "BattleTeamRecord{" +
"rank=" + rank +
", summoner=" + summoner +
", monsters=" + monsters +
", totalMana=" + totalMana +
", totalAttackDamage=" + totalAttackDamage +
", totalRangedDamage=" + totalRangedDamage +
", totalMagicDamage=" + totalMagicDamage +
", totalArmor=" + totalArmor +
", totalHealth=" + totalHealth +
", totalSpeed=" + totalSpeed +
", totalArmorHeal=" + totalArmorHeal +
", totalHealthHeal=" + totalHealthHeal +
", weightedLevelAverage=" + weightedLevelAverage +
'}';
}
}
| 28.440415 | 361 | 0.643469 |
56d790552e50450e87e80c2fc60ef43a8a99cbe3 | 800 | package com.revolsys.raster.commonsimaging;
import java.awt.image.BufferedImage;
import com.revolsys.raster.AbstractGeoreferencedImage;
import com.revolsys.spring.resource.Resource;
public class CommonsImagingGeoreferencedImage extends AbstractGeoreferencedImage {
public CommonsImagingGeoreferencedImage(final CommonsImagingImageReadFactory factory,
final Resource resource, final String worldFileExtension) {
super(worldFileExtension);
setImageResource(resource);
final BufferedImage bufferedImage = factory.readBufferedImage(resource);
setRenderedImage(bufferedImage);
loadImageMetaData();
postConstruct();
}
@Override
public void cancelChanges() {
if (getImageResource() != null) {
loadImageMetaData();
setHasChanges(false);
}
}
}
| 26.666667 | 87 | 0.775 |
f17394d1ade1d4dc550c63c78fe308fbc6271d6b | 1,573 | package com.github.terefang.gea.godot.pck;
import com.github.terefang.gea.GeaFile;
import java.io.*;
public class PckFile extends GeaFile<PckFileEntry>
{
int compression;
int format;
int major;
int minor;
int patch;
int flags;
public int getCompression() {
return compression;
}
public void setCompression(int compression) {
this.compression = compression;
}
public int getFormat() {
return format;
}
public void setFormat(int format) {
this.format = format;
}
public int getMajor() {
return major;
}
public void setMajor(int major) {
this.major = major;
}
public int getMinor() {
return minor;
}
public void setMinor(int minor) {
this.minor = minor;
}
public int getPatch() {
return patch;
}
public void setPatch(int patch) {
this.patch = patch;
}
public int getFlags() {
return flags;
}
public void setFlags(int flags) {
this.flags = flags;
}
public InputStream getFileStream(PckFileEntry _entry) throws IOException
{
if(_entry.getSize()==0) return null;
byte[] _buffer = new byte[(int) _entry.getSize()];
RandomAccessFile _raf = new RandomAccessFile(new File(this.getFilepath()), "r");
_raf.seek(_entry.getOffset());
_raf.read(_buffer);
_raf.close();
return new ByteArrayInputStream(_buffer);
}
@Override
public void close() throws IOException
{
}
}
| 18.951807 | 88 | 0.596949 |
11f671063a80f1d1708e335875823ff5a774ce71 | 3,891 | package com.galaxy.crawler.core.engine;
import com.galaxy.crawler.core.domain.Request;
import com.galaxy.crawler.core.scheduler.Scheduler;
import com.galaxy.crawler.core.spider.Spider;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author hufeng
* @version Container.java, v 0.1 2020/7/16 01:11 Exp $
*/
@Slf4j
public class Container implements Runnable {
protected Spider spider;
protected ExecutorService executorService;
protected final static int STAT_INIT = 0;
protected final static int STAT_RUNNING = 1;
protected final static int STAT_STOPPED = 2;
protected AtomicInteger stat = new AtomicInteger(STAT_INIT);
protected Scheduler scheduler;
protected int threadNum;
protected boolean exitWhenComplete = true;
protected boolean destroyWhenExit = true;
protected ReentrantLock nextUrlLock = new ReentrantLock();
protected Condition nextUrlCondition = nextUrlLock.newCondition();
protected List<Request> startRequests;
private int idleSleepTime = 30000;
public Container(Spider spider) {
this.spider = spider;
this.scheduler = spider.getScheduler();
this.threadNum = spider.getThreadNum();
this.startRequests = spider.getStartRequests();
}
public void initComponent() {
if (executorService == null || executorService.isShutdown()) {
executorService = Executors.newFixedThreadPool(threadNum);
}
}
@Override
public void run() {
checkRunningStat();
while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) {
final Request request = scheduler.poll();
if (request == null) {
if (exitWhenComplete) {
break;
}
// wait unit new url added
waitNextUrl();
} else {
// todo 控制速率
// todo 发布url ready事件
}
}
stat.set(STAT_STOPPED);
if (destroyWhenExit) {
close();
}
log.info("Container closed");
}
private void waitNextUrl() {
nextUrlLock.lock();
// double check
if (exitWhenComplete) {
return;
}
try {
nextUrlCondition.await(idleSleepTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
log.warn("waitNextUrl interrupted.", e);
} finally {
nextUrlLock.unlock();
}
}
private void checkRunningStat() {
while (true) {
int statNow = stat.get();
if (statNow == STAT_RUNNING) {
throw new IllegalStateException("Container is already running!");
}
if (stat.compareAndSet(statNow, STAT_RUNNING)) {
break;
}
}
}
public void close() {
if (executorService != null) {
executorService.shutdown();
try {
if (!executorService.awaitTermination(100, TimeUnit.MICROSECONDS)) {
log.warn("executorService still running..");
System.exit(0);
}
} catch (InterruptedException e) {
log.warn("close executorService interrupted.");
}
}
}
}
| 32.697479 | 91 | 0.558725 |
3588ff54d1a919c6cffec482667240ee65149491 | 5,966 | package com.hoopawolf.vrm.network;
import com.hoopawolf.vrm.helper.EntityHelper;
import com.hoopawolf.vrm.network.packets.client.PlaySoundEffectMessage;
import com.hoopawolf.vrm.network.packets.client.SendPlayerMessageMessage;
import com.hoopawolf.vrm.network.packets.client.SpawnParticleMessage;
import com.hoopawolf.vrm.ref.Reference;
import com.hoopawolf.vrm.util.ParticleRegistryHandler;
import net.fabricmc.fabric.api.network.PacketContext;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.particle.ParticleEffect;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.sound.SoundEvent;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.Formatting;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
public class MessageHandlerOnClient
{
private static final ParticleEffect[] types =
{
ParticleTypes.FLAME, //0
ParticleTypes.FIREWORK, //1
ParticleTypes.END_ROD, //2
ParticleRegistryHandler.DEATH_MARK_PARTICLE, //3
ParticleTypes.SMOKE, //4
ParticleRegistryHandler.PLAGUE_PARTICLE, //5
ParticleTypes.ITEM_SLIME, //6
ParticleTypes.HEART, //7
ParticleTypes.ANGRY_VILLAGER, //8
ParticleTypes.WITCH, //9
ParticleTypes.SQUID_INK, //10
ParticleTypes.HAPPY_VILLAGER, //11
ParticleTypes.DRAGON_BREATH, //12
ParticleTypes.SNEEZE, //13
};
private static final SoundEvent[] sound_type =
{
SoundEvents.ENTITY_GENERIC_EAT, //0
SoundEvents.ENTITY_PLAYER_BURP, //1
SoundEvents.BLOCK_BLASTFURNACE_FIRE_CRACKLE, //2
SoundEvents.BLOCK_NOTE_BLOCK_BANJO, //3
SoundEvents.ENTITY_VEX_CHARGE, //4
SoundEvents.BLOCK_END_PORTAL_SPAWN, //5
SoundEvents.ENTITY_PUFFER_FISH_BLOW_OUT, //6
SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, //7
SoundEvents.BLOCK_NOTE_BLOCK_CHIME, //8
SoundEvents.ENTITY_FOX_SCREECH, //9
};
public static void onMessageReceived(final PacketByteBuf message, PacketContext ctx)
{
boolean isClient = ctx.getPlayer().world.isClient;
if (!isClient)
{
Reference.LOGGER.warn("MessageToClient received on wrong side:" + ctx.getTaskQueue().getName());
return;
}
if (ctx.getPlayer().world == null)
{
Reference.LOGGER.warn("MessageToClient context could not provide a ClientWorld.");
return;
}
processMessage((ClientWorld) ctx.getPlayer().world, message, ctx);
}
private static void processMessage(ClientWorld worldClient, PacketByteBuf message, PacketContext ctx)
{
int id = message.readInt();
switch (id)
{
case 1:
{
SpawnParticleMessage _message = SpawnParticleMessage.decode(message);
ctx.getTaskQueue().submit(() ->
{
for (int i = 0; i < _message.getIteration(); ++i)
{
Vec3d targetCoordinates = _message.getTargetCoordinates();
Vec3d targetSpeed = _message.getTargetSpeed();
double spread = _message.getParticleSpread();
double spawnXpos = targetCoordinates.x;
double spawnYpos = targetCoordinates.y;
double spawnZpos = targetCoordinates.z;
double speedX = targetSpeed.x;
double speedY = targetSpeed.y;
double speedZ = targetSpeed.z;
worldClient.addParticle(/*_message.getPartcleType() == 2 ? new BlockParticleData(ParticleTypes.BLOCK, worldClient.getBlockState(new BlockPos(spawnXpos, spawnYpos - 1.0F, spawnZpos))) : */types[_message.getPartcleType()],
true,
MathHelper.lerp(worldClient.random.nextDouble(), spawnXpos + spread, spawnXpos - spread),
spawnYpos,
MathHelper.lerp(worldClient.random.nextDouble(), spawnZpos + spread, spawnZpos - spread),
speedX, speedY, speedZ);
}
});
}
break;
case 2:
{
PlaySoundEffectMessage _message = PlaySoundEffectMessage.decode(message);
ctx.getTaskQueue().submit(() ->
{
Entity entity = worldClient.getEntityById(_message.getEntityID());
float pitch = _message.getPitch();
float volume = _message.getVolume();
assert entity != null;
entity.playSound(sound_type[_message.getSoundType()], volume, pitch);
});
}
break;
case 3:
{
SendPlayerMessageMessage _message = SendPlayerMessageMessage.decode(message);
ctx.getTaskQueue().submit(() ->
{
PlayerEntity entity = worldClient.getPlayerByUuid(_message.getPlayerUUID());
String messageID = _message.getMessageID();
int color = _message.getColor();
EntityHelper.sendMessage(entity, messageID, Formatting.byColorIndex(color));
});
}
break;
default:
break;
}
}
}
| 41.144828 | 244 | 0.569728 |
9a0d097e866e852cb1a84dd794cad8f7ff075a90 | 3,466 | package knc.simulator.model;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ElevatorTest {
private final int defaultLowestStorey = 1;
private final int defaultHighestStorey = 4;
private final int defaultStartingStorey = defaultLowestStorey;
private Elevator elevator = new Elevator(defaultLowestStorey, defaultHighestStorey, defaultStartingStorey);
@Test
void testCanCreateNegativeStoreys() {
assertDoesNotThrow(() -> new Elevator(-44, -21));
}
@Test
void testLowestStoreyEqualToHighestShouldThrow() {
assertThrows(Exception.class, () -> new Elevator(5, 5));
}
@Test
void testLowestStoreyGreaterThanHighestShouldThrow() {
assertThrows(Exception.class, () -> new Elevator(3, 2));
}
@Test
void testDirectionIsUpdated() {
assertEquals(ElevatorAction.IDLE, elevator.getCurrentAction());
elevator.setTargetStorey(defaultStartingStorey + 1);
assertEquals(ElevatorAction.ASCENDING, elevator.getCurrentAction());
elevator.setTargetStorey(defaultStartingStorey - 1);
assertEquals(ElevatorAction.DESCENDING, elevator.getCurrentAction());
}
@Test
void testTraversalSpeed() {
int cyclesToTraverseOneLevel = 5;
int targetStorey = defaultStartingStorey + 1;
elevator.setCyclesToTraverseStorey(cyclesToTraverseOneLevel);
elevator.setTargetStorey(targetStorey);
for(int i=0; i<cyclesToTraverseOneLevel; i++) {
assertNotEquals(targetStorey, elevator.getCurrentStorey());
elevator.update();
}
assertEquals(targetStorey, elevator.getCurrentStorey());
}
@Test
void testInstantTraversalSpeed() {
int cyclesToTraverseOneLevel = 1;
int targetStorey = defaultStartingStorey + 1;
elevator.setCyclesToTraverseStorey(cyclesToTraverseOneLevel);
elevator.setTargetStorey(targetStorey);
assertNotEquals(targetStorey, elevator.getCurrentStorey());
elevator.update();
assertEquals(targetStorey, elevator.getCurrentStorey());
}
@Test
void testTraversalCyclesBelow1ShouldThrowException() {
assertThrows(Exception.class, () -> elevator.setCyclesToTraverseStorey(0));
assertThrows(Exception.class, () -> elevator.setCyclesToTraverseStorey(-5));
}
@Test
void testHoldCyclesBelow1ShouldThrowException() {
assertThrows(Exception.class, () -> elevator.setCyclesToHold(0));
assertThrows(Exception.class, () -> elevator.setCyclesToHold(-8));
}
@Test
void testHoldWhenTargetStoreyEqualsCurrent() {
elevator.setTargetStorey(defaultStartingStorey);
assertEquals(ElevatorAction.HOLD, elevator.getCurrentAction());
}
@Test
void testHoldAfterTargetStoreyReached() {
int cyclesToTraverseOneLevel = 1;
int targetStorey = defaultStartingStorey + 1;
elevator.setCyclesToTraverseStorey(cyclesToTraverseOneLevel);
elevator.setTargetStorey(targetStorey);
elevator.update();
assertEquals(ElevatorAction.HOLD, elevator.getCurrentAction());
}
@Test
void testIdleAfterHold() {
int cyclesToHold = 1;
elevator.setCyclesToHold(cyclesToHold);
elevator.setTargetStorey(defaultStartingStorey);
elevator.update();
assertEquals(ElevatorAction.IDLE, elevator.getCurrentAction());
}
} | 32.698113 | 111 | 0.6985 |
5629ee4ee5ccec180a09754f88d53032f78fefc1 | 776 | /**
* I18nConfigurationProperties.java 2 abr. 2021
*
*/
package org.sylrsykssoft.springboot.common.app.boot.configuration.properties.i18n;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.FieldDefaults;
/**
* @author juan.gonzalez.fernandez.jgf
*
*/
@ConfigurationProperties(prefix = "spring.messages")
@NoArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@Getter
@Setter
public class I18nMessageSourceConfigurationProperties {
boolean alwaysUseMessageFormat;
String basename;
int cacheDuration;
String encoding;
boolean fallbackToSystemLocale;
boolean useCodeAsDefaultMessage;
}
| 19.897436 | 82 | 0.805412 |
bf3fe7b677c4b6532d2505bbf26ea3be85da6f0c | 503 | package net.study.repository;
import net.study.domain.Study;
import net.study.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* First Editor : Donghyun Seo (egaoneko@naver.com)
* Last Editor :
* Date : 6/5/15 | 9:50 PM
* Description :
* Copyright ⓒ 2013-2015 Donghyun Seo All rights reserved.
* version :
*/
public interface StudyRepository extends JpaRepository<Study, Long> {
List<Study> findAllByUser(User user);
}
| 22.863636 | 69 | 0.713718 |
92dc3bbaccc752b20bb78f03722083c8202afcde | 1,821 | package com.gcats.cats.service;
import com.gcats.cats.model.User;
import com.gcats.cats.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
@Service("userService")
public class UserService {
private UserRepository userRepository;
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
public UserService(UserRepository userRepository,
BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userRepository = userRepository;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
public User findUserByLogin(String login) {
return userRepository.findByLogin(login);
}
public User findUserById(int id) {
return userRepository.findById(id);
}
public User saveUser(User user) {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setActive(1);
return userRepository.save(user);
}
public User update(User user) {
return userRepository.save(user);
}
public ModelAndView getModelWithUser(){
ModelAndView modelAndView = new ModelAndView();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = findUserByLogin(auth.getName());
modelAndView.addObject("user", user);
System.out.println(user.getPassword());
return modelAndView;
}
public Iterable<User> listAllUsers() {
return userRepository.findAll();
}
} | 30.864407 | 85 | 0.72927 |
1e8932fff4ef4734042210dcb02a1a8535d29629 | 1,346 | package be.unamur.transitionsystem.test.mutation.equivalence.exact;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import be.unamur.transitionsystem.State;
public class NFAPair {
ArrayList<State> x = new ArrayList<State>();
ArrayList<State> y = new ArrayList<State>();
private Logger logger = LoggerFactory.getLogger(NFAPair.class);
public NFAPair(ArrayList<State> x, ArrayList<State> y) {
this.x =x;
this.y = y;
}
public void printNFAPair() {
System.out.println("X:");
for (State s : x)
System.out.print(s.getName());
System.out.println("Y:");
for (State s: y)
System.out.print(s.getName());
}
public boolean equals(NFAPair p) {
if (this.x.equals(p.x) && this.y.equals(p.y)) {
//logger.debug("equals: " +x.toString() + " " + p.x.toString());
//logger.debug("equals: " +y.toString() + " " + p.y.toString());
return true;
}
else
return false;
}
public String toString() {
String res=new String();
res += "<<";
for (int i=0;i<x.size();i++) {
if (i==x.size()-1)
res += x.get(i).getName();
else
res += x.get(i).getName()+",";
}
res += ">,<";
for (int i=0;i<y.size();i++) {
if (i==y.size()-1)
res += y.get(i).getName();
else
res += y.get(i).getName()+",";
}
res += ">>";
return res;
}
}
| 20.089552 | 67 | 0.592868 |
ce48087b70085f3d6e6b5ff9a94afb1cfb107c10 | 426 | package br.com.mjv.oficina.exception;
/**
* Exceção disparada quando tentamos cadastrar um defeito já cadastrado em nossa base de dados.
* @author thiago
*
*/
public class DefeitoJaCadastradoException extends BusinnessException {
private static final long serialVersionUID = 1L;
public DefeitoJaCadastradoException(String defeito) {
super(String.format("Defeito %s já cadastrado na base de dados", defeito));
}
}
| 25.058824 | 95 | 0.7723 |
7615cc32e7231fb724ec0159df4f46cabd0c0957 | 833 | package com.adsizzler.mangolaa.commons.json.jackson.serializers;
import com.adsizzler.mangolaa.commons.domain.openrtb.enums.CreativeAttributes;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Objects;
/**
* Created by Ankush on 08/08/17.
*/
public class CreativeAttributesSerializer extends JsonSerializer<CreativeAttributes> {
@Override
public void serialize(
final CreativeAttributes creativeAttributes,
final JsonGenerator gen,
final SerializerProvider serializers
) throws IOException
{
if(Objects.nonNull(creativeAttributes)){
gen.writeNumber(creativeAttributes.getCode());
}
}
}
| 29.75 | 86 | 0.747899 |
c1e4b15b393080a1b0b2f91311b4ea2a6b816aa4 | 388 | package ru.wolfa.demo.hockey.match.repository;
import ru.wolfa.demo.hockey.match.domain.Tournament;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data repository for the Tournament entity.
*/
@SuppressWarnings("unused")
@Repository
public interface TournamentRepository extends JpaRepository<Tournament, Long> {
}
| 24.25 | 79 | 0.801546 |
8501cf31b481677363280b9467aa5337ec5d9a8c | 3,325 | /*
* Copyright 2018 Soojeong Shin
*
* 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.example.cv.baker_app.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
/**
* A {@link Step} object includes information such as step ID, short description, description,
* video URL, thumbnail URL.
* This class implements Parcelable interface to allow {@link Step} object to be sent as a Parcel.
*/
public class Step implements Parcelable {
@SerializedName("id")
private int mId;
@SerializedName("shortDescription")
private String mShortDescription;
@SerializedName("description")
private String mDescription;
@SerializedName("videoURL")
private String mVideoUrl;
@SerializedName("thumbnailURL")
private String mThumbnailUrl;
public Step(int id, String shortDescription, String description, String videoUrl, String thumbnailUrl) {
mId = id;
mShortDescription = shortDescription;
mDescription = description;
mVideoUrl = videoUrl;
mThumbnailUrl = thumbnailUrl;
}
private Step(Parcel in) {
mId = in.readInt();
mShortDescription = in.readString();
mDescription = in.readString();
mVideoUrl = in.readString();
mThumbnailUrl = in.readString();
}
public static final Creator<Step> CREATOR = new Creator<Step>() {
@Override
public Step createFromParcel(Parcel in) {
return new Step(in);
}
@Override
public Step[] newArray(int size) {
return new Step[size];
}
};
public void setStepId(int id) {
mId = id;
}
public int getStepId() {
return mId;
}
public void setShortDescription(String shortDescription) {
mShortDescription = shortDescription;
}
public String getShortDescription() {
return mShortDescription;
}
public void setDescription(String description) {
mDescription = description;
}
public String getDescription() {
return mDescription;
}
public void setVideoUrl(String videoUrl) {
mVideoUrl = videoUrl;
}
public String getVideoUrl() {
return mVideoUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
mThumbnailUrl = thumbnailUrl;
}
public String getThumbnailUrl() {
return mThumbnailUrl;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mId);
dest.writeString(mShortDescription);
dest.writeString(mDescription);
dest.writeString(mVideoUrl);
dest.writeString(mThumbnailUrl);
}
}
| 25.976563 | 108 | 0.661353 |
7565244532f397ffc573658ee4185979e95d5c6c | 1,031 | package com.gentics.mesh.util;
import java.util.Optional;
import io.vertx.core.http.impl.MimeMapping;
public class MimeTypeUtils {
/** Default MIME type for binary files. */
public static final String DEFAULT_BINARY_MIME_TYPE = "application/octet-stream";
/**
* Try to determine the MIME type from the given filename.
*
* The actual work is done by the {@link MimeMapping#getMimeTypeForFilename MimeMapping} class, this wrapper takes care of <code>null</code> values.
*
* @see MimeMapping#getMimeTypeForFilename(String)
* @param filename The filename to get a MIME type for
* @return An empty Optional when the filename is <code>null</code> or no MIME type could be determined, or an Optional containing the MIME type otherwise.
*/
public static Optional<String> getMimeTypeForFilename(String filename) {
if (filename == null) {
return Optional.empty();
}
String mimeType = MimeMapping.getMimeTypeForFilename(filename);
return mimeType == null ? Optional.empty() : Optional.of(mimeType);
}
}
| 33.258065 | 156 | 0.746848 |
6e10fb07648dd3adcc0ec285ec463e50445d9283 | 1,843 | /**
* Copyright 2013-2015 JueYue (qrb.jueyue@gmail.com)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.afterturn.easypoi.cache;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
import org.apache.poi.util.IOUtils;
import cn.afterturn.easypoi.cache.manager.POICacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 图片缓存处理
*
* @author JueYue
* 2016年1月8日 下午4:16:32
*/
public class ImageCache {
private static final Logger LOGGER = LoggerFactory
.getLogger(ImageCache.class);
public static byte[] getImage(String imagePath) {
InputStream is = POICacheManager.getFile(imagePath);
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
try {
BufferedImage bufferImg = ImageIO.read(is);
ImageIO.write(bufferImg,
imagePath.substring(imagePath.indexOf(".") + 1, imagePath.length()),
byteArrayOut);
return byteArrayOut.toByteArray();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
return null;
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(byteArrayOut);
}
}
}
| 30.213115 | 88 | 0.676614 |
1a58768886ccb9bc94a43845c81bca0f7223b449 | 9,838 |
import java.awt.Color;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
/*
* 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.
*/
/**
*
* @author Rohan
*/
public class your_acc extends javax.swing.JFrame {
/**
* Creates new form your_acc
*/
public your_acc() {
initComponents();
this.getContentPane().setBackground(Color.WHITE);
this.hidden_email.setVisible(false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
hidden_email = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Project Pictures/snap_buynow_head.PNG"))); // NOI18N
jLabel2.setFont(new java.awt.Font("Tahoma", 3, 36)); // NOI18N
jLabel2.setForeground(new java.awt.Color(153, 153, 153));
jLabel2.setText("Your account");
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Project Pictures/profile.jpg"))); // NOI18N
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel4.setText("Name :");
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel5.setText("jLabel5");
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel6.setText("Email :");
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel7.setText("jLabel7");
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel9.setText("Mobile :");
jLabel10.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel10.setText("jLabel10");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addGap(151, 151, 151)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(18, 18, 18)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(203, 203, 203)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(hidden_email)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(hidden_email))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jLabel7))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(jLabel10))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
try
{
Class.forName("java.sql.DriverManager");
Connection c=DriverManager.getConnection("jdbc:mysql://localhost:3306/gmail","root","12345");
Statement s=(Statement) c.createStatement();
String q="SELECT first_name,last_name,mobile FROM createaccount WHERE alt_email='"+this.hidden_email.getText()+"';";
ResultSet rs=s.executeQuery(q);
while(rs.next())
{
String fn=rs.getString("first_name");
String ln=rs.getString("last_name");
String mob=rs.getString("mobile");
jLabel5.setText(fn+" "+ln);
jLabel7.setText(this.hidden_email.getText());
jLabel10.setText(mob);
}
}catch(Exception e){JOptionPane.showMessageDialog(this,e.getMessage());} // TODO add your handling code here:
}//GEN-LAST:event_formWindowOpened
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(your_acc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(your_acc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(your_acc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(your_acc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new your_acc().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JLabel hidden_email;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel9;
// End of variables declaration//GEN-END:variables
}
| 45.336406 | 141 | 0.614962 |
c4c226bd930f979c15ddfbb89ded0b51f4b1d8d3 | 3,152 | package com.topology.impl.importers.sndlib;
import com.topology.impl.primitives.LinkImpl;
import com.topology.impl.primitives.NetworkElementImpl;
import com.topology.impl.primitives.TopologyManagerImpl;
import com.topology.importers.ImportTopology;
import com.topology.primitives.TopologyManager;
import com.topology.primitives.exception.FileFormatException;
import com.topology.primitives.exception.TopologyException;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.*;
public class SndLibImportTest {
private static final Logger log = LoggerFactory.getLogger(SndLibImportTest.class);
public enum SNDLibSource {
ABILENE ("abilene.xml", 12, 15),
ATLANTA("atlanta.xml", 15, 22),
JANOS_US("janos-us.xml", 26, 42),
JANOS_US_DUPLICATES("janos-us.xml", 26, 84, false),
ZIB54("zib54.xml", 54, 80),
ZIB54_DUPLICATES("zib54.xml", 54, 81, false);
SNDLibSource(String fileName, int nodeNum, int linkNum) {
this.fileName = fileName;
this.nodeNum = nodeNum;
this.linkNum = linkNum;
this.removeDuplicaties = true;
}
SNDLibSource(String fileName, int nodeNum, int linkNum, boolean removeDuplicaties) {
this.fileName = fileName;
this.nodeNum = nodeNum;
this.linkNum = linkNum;
this.removeDuplicaties = removeDuplicaties;
}
final String fileName;
final int nodeNum;
final int linkNum;
final boolean removeDuplicaties;
}
@ParameterizedTest(name = "{index} => message=''{0}''")
@EnumSource(SndLibImportTest.SNDLibSource.class)
public void testImport(SNDLibSource source) {
ImportTopology importer = new SNDLibImportTopology(source.removeDuplicaties);
TopologyManager manager = new TopologyManagerImpl(source.fileName);
try {
log.info("Loading topology from file {}", source.fileName);
importer.importFromFile(this.getClass().getClassLoader().getResource(source.fileName).getFile(), manager);
assertEquals(manager.getAllElements(NetworkElementImpl.class).size(), source.nodeNum, "Expected " + source.nodeNum + " nodes in " + source.fileName +
". Parsed Nodes = " + manager.getAllElements(NetworkElementImpl.class).size());
assertEquals(manager.getAllElements(LinkImpl.class).size(), source.linkNum, "Expected " + source.linkNum + " links in " + source.fileName +
". Parsed Links = " + manager.getAllElements(LinkImpl.class).size());
} catch (TopologyException e) {
log.error("Topology Exception while parsing test.topology file", e);
fail("Topology Exception while parsing test.topology file");
} catch (FileFormatException e) {
log.error("FileFormat Exception while parsing test.topology file", e);
fail("FileFormat Exception while parsing test.topology file");
} catch (IOException e) {
log.error("IO Exception while parsing test.topology file", e);
fail("IO Exception while parsing test.topology file");
}
manager.removeAllElements();
}
}
| 40.410256 | 155 | 0.728744 |
297b6e460eadf14f2c3f85f5863be3bede886579 | 814 | package com.scs.astrocommander.modules.inputmodes;
import com.scs.astrocommander.Main;
import com.scs.astrocommander.modules.PlayersShipModule;
import com.scs.rogueframework.ecs.components.ICarryable;
import com.scs.rogueframework.ecs.entities.DrawableEntity;
import com.scs.rogueframework.input.AbstractSelectNumberInputHandler;
import com.scs.rogueframework.input.IInputHander;
public class ChangeItemInputHandler extends AbstractSelectNumberInputHandler implements IInputHander {
public ChangeItemInputHandler(Main _main, PlayersShipModule psm) {
super(_main, psm);
}
@Override
protected void numberSelected(int i) {
ICarryable de = main.gameData.current_unit.equipment.get(i-1);
main.gameData.current_unit.currentItem = de;
main.addMsg("You use the " + ((DrawableEntity)de).getName());
}
}
| 32.56 | 102 | 0.813268 |
12b4ef1a24a3ddf135fb5f66435b9fbf7886e21b | 1,369 | /*
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.sun.xml.ws.rx.util;
import com.sun.xml.ws.api.message.Packet;
/**
*
* @author Marek Potociar <marek.potociar at sun.com>
*/
public class AbstractResponseHandler {
protected final SuspendedFiberStorage suspendedFiberStorage;
private String correlationId;
public AbstractResponseHandler(SuspendedFiberStorage suspendedFiberStorage, String correlationId) {
this.suspendedFiberStorage = suspendedFiberStorage;
this.correlationId = correlationId;
}
protected final String getCorrelationId() {
return correlationId;
}
protected final void setCorrelationId(String newCorrelationId) {
this.correlationId = newCorrelationId;
}
protected final void resumeParentFiber(Packet response) throws ResumeFiberException {
suspendedFiberStorage.resumeFiber(correlationId, response);
}
protected final void resumeParentFiber(Throwable error) throws ResumeFiberException {
suspendedFiberStorage.resumeFiber(correlationId, error);
}
}
| 31.113636 | 103 | 0.747261 |
f74a8593b1497823e7bc1c8365d01f384e961ac9 | 1,825 | package fr.jmini.openapi.openapitools.helidon.api;
import java.util.List;
import fr.jmini.openapi.openapitools.helidon.model.User;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.util.Map;
import java.util.List;
import javax.validation.constraints.*;
import javax.validation.Valid;
@Path("/user")
public class UserApi {
@POST
public Response createUser(@Valid User user) {
return Response.ok().entity("magic!").build();
}
@POST
@Path("/createWithArray")
public Response createUsersWithArrayInput(@Valid List<User> user) {
return Response.ok().entity("magic!").build();
}
@POST
@Path("/createWithList")
public Response createUsersWithListInput(@Valid List<User> user) {
return Response.ok().entity("magic!").build();
}
@DELETE
@Path("/{username}")
public Response deleteUser(@PathParam("username") String username) {
return Response.ok().entity("magic!").build();
}
@GET
@Path("/{username}")
@Produces({ "application/json", "application/xml" })
public Response getUserByName(@PathParam("username") String username) {
return Response.ok().entity("magic!").build();
}
@GET
@Path("/login")
@Produces({ "application/json", "application/xml" })
public Response loginUser(@QueryParam("username") String username,@QueryParam("password") String password) {
return Response.ok().entity("magic!").build();
}
@GET
@Path("/logout")
public Response logoutUser() {
return Response.ok().entity("magic!").build();
}
@PUT
@Path("/{username}")
public Response updateUser(@PathParam("username") String username,@Valid User user) {
return Response.ok().entity("magic!").build();
}
}
| 26.838235 | 118 | 0.649315 |
cbad101621acfcf35ec3d7eb465cb274c44afa20 | 428 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.application.impl;
import consulo.awt.hacking.InvocationUtil;
import javax.annotation.Nonnull;
public class InvocationUtil2 extends InvocationUtil {
@Nonnull
public static final Class<? extends Runnable> FLUSH_NOW_CLASS = FlushQueue.FlushNow.class;
}
| 32.923077 | 140 | 0.799065 |
62f643ad30f4686c08f3ca07c676e4263e6188ca | 1,397 | // This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.blockchain.models;
import com.aliyun.tea.*;
public class VcControllerAddUserRegisterPayload extends TeaModel {
// 注册用户did
@NameInMap("did")
@Validation(required = true)
public String did;
// 用户did对应的授权公钥
@NameInMap("public_key")
@Validation(required = true)
public String publicKey;
// 业务区块连的bizid
@NameInMap("vc_channel")
@Validation(maxLength = 32, minLength = 8)
public String vcChannel;
public static VcControllerAddUserRegisterPayload build(java.util.Map<String, ?> map) throws Exception {
VcControllerAddUserRegisterPayload self = new VcControllerAddUserRegisterPayload();
return TeaModel.build(map, self);
}
public VcControllerAddUserRegisterPayload setDid(String did) {
this.did = did;
return this;
}
public String getDid() {
return this.did;
}
public VcControllerAddUserRegisterPayload setPublicKey(String publicKey) {
this.publicKey = publicKey;
return this;
}
public String getPublicKey() {
return this.publicKey;
}
public VcControllerAddUserRegisterPayload setVcChannel(String vcChannel) {
this.vcChannel = vcChannel;
return this;
}
public String getVcChannel() {
return this.vcChannel;
}
}
| 26.865385 | 107 | 0.683608 |
c601e0d391be5ffd4647f6a32d24ed7118415a9a | 1,584 | package com.planmart;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public final class ShippingRule implements Rule {
public static final String[] STATES = new String[] { "VA", "NC", "SC", "TN", "AK", "KY", "AL" };
public static final Set<String> NO_SHIPPING_ALCOHOL_STATES = new HashSet<String>(Arrays.asList(STATES));
/**
* Shipping rules:
* 1. Non profits - free shipping.
* 2. Alcohol may not be shipped to VA, NC, SC, TN, AK, KY, AL
* 3. Alcohol may only be shipped to customers age 21 or over in the US
* 4. Shipping is $10 for orders under 20 pounds
* 5. Shipping is $20 for orders 20 pounds or over
*/
@Override
public boolean processRule(Order order) {
// Rule #1: free shipping to non profits.
if(order.getCustomer().getIsNonProfit() == true) {
// TODO: add code.
}
// Find out if alcohol product is in the order.
boolean isAlcoholInOrder = false;
for(ProductOrder product : order.getItems()) {
if(product.getProduct().getType() == ProductType.ALCOHOL) {
isAlcoholInOrder = true;
break;
}
}
// Rule #2: no shipping of alcohol to select states.
if(isAlcoholInOrder == true &&
NO_SHIPPING_ALCOHOL_STATES.contains(order.getShippingRegion().toUpperCase()) == true) {
return false;
}
// Rule #3: if US ship alcohol only to 21+ year old customer.
//if(order.)
//int age = order.getCustomer().getBirthDate()
return false;
}
}
| 33 | 107 | 0.616793 |
66bc6b5f82e7b12175d928358cadc6032eb841e4 | 3,472 | package com.zcj.test5;
import android.opengl.GLES20;
import android.opengl.Matrix;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zcj on 2019/6/25 23:08
* <p>
* 绘制圆锥
*/
public class Cone {
private final float[] mVertexPositions;
private final int COORDS_PER_VERTEX = 3;
private final int vertexStride = COORDS_PER_VERTEX * 4;
private final int vertexCount;
private FloatBuffer mVertexBuffer;
private int mProgram;
private int mPositionHandler;
private int mMatrixHandler;
private float[] mProjectionMatrix = new float[16];
private float[] mViewMatrix = new float[16];
private float[] mModelMatrix = new float[16];
private float[] mMVPMatrix = new float[16];
public Cone() {
mVertexPositions = createPositions(1.0f);
vertexCount = mVertexPositions.length / COORDS_PER_VERTEX;
}
public void init() {
ByteBuffer bb = ByteBuffer.allocateDirect(mVertexPositions.length * 4);
bb.order(ByteOrder.nativeOrder());
mVertexBuffer = bb.asFloatBuffer();
mVertexBuffer.put(mVertexPositions);
mVertexBuffer.position(0);
int vertexShader = Test5Util.loadShader(Test5Activity.APP.getResources(), GLES20.GL_VERTEX_SHADER, "t5_shader_vertex_cone.glsl");
int fragmentShader = Test5Util.loadShader(Test5Activity.APP.getResources(), GLES20.GL_FRAGMENT_SHADER, "t5_shader_fragment_cone.glsl");
mProgram = Test5Util.createOpenGLESProgram(vertexShader, fragmentShader);
}
public void resize(int width, int height) {
float ratio = (float) width / height;
Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1, 1, 3.0f, 20.f);
Matrix.setLookAtM(mViewMatrix, 0, 8.0f, -4.0f, 6.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
Matrix.setIdentityM(mModelMatrix, 0);
Matrix.translateM(mModelMatrix, 0, 0, -0.5f, 0);
float[] tmpMatrix = new float[16];
Matrix.multiplyMM(tmpMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0);
Matrix.multiplyMM(mMVPMatrix, 0, tmpMatrix, 0, mModelMatrix, 0);
}
public void draw() {
GLES20.glUseProgram(mProgram);
mPositionHandler = GLES20.glGetAttribLocation(mProgram, "vPosition");
GLES20.glEnableVertexAttribArray(mPositionHandler);
GLES20.glVertexAttribPointer(mPositionHandler, COORDS_PER_VERTEX, GLES20.GL_FLOAT,
false, vertexStride, mVertexBuffer);
mMatrixHandler = GLES20.glGetUniformLocation(mProgram, "vMatrix");
GLES20.glUniformMatrix4fv(mMatrixHandler, 1, false, mMVPMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, vertexCount);
GLES20.glDisableVertexAttribArray(mPositionHandler);
}
private float[] createPositions(float step) {
List<Float> data = new ArrayList<>();
float height = 2.0f;
float radius = 1.0f;
data.add(0.0f);
data.add(height);
data.add(0.0f);
for (float i = 0; i < 360f + step; i += step) {
data.add((float) (radius * Math.cos(i * Math.PI / 180f)));
data.add(0.0f);
data.add((float) (radius * Math.sin(i * Math.PI / 180f)));
}
float[] positions = new float[data.size()];
for (int j = 0; j < data.size(); j++) {
positions[j] = data.get(j);
}
return positions;
}
}
| 36.547368 | 143 | 0.658698 |
320e9c24829afc033275730bd2c5bb3944257c3e | 974 | import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws Exception{
// 7-1
Reader fr = new FileReader("pref.properties");
Properties p = new Properties();
p.load(fr);
System.out.println(p.getProperty("aichi.capital") + ":" + p.getProperty("aichi.food"));
fr.close();
// 7-2
ResourceBundle rb = ResourceBundle.getBundle("pref");
System.out.println(rb.getString("aichi.capital") + ":" + rb.getString("aichi.food"));
// 7-3
Employee tanaka = new Employee();
tanaka.name = "田中一郎";
tanaka.age = 41;
Department soumubu = new Department();
soumubu.name = "総務部";
soumubu.leader = tanaka;
FileOutputStream fos = new FileOutputStream("company.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(soumubu);
oos.flush();
oos.close();
}
} | 32.466667 | 95 | 0.586242 |
31de58e86fa5b7a68f76eb9b34a472ea27b96919 | 158 | package NBlog;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BlogPostRepository extends JpaRepository<BlogPost, Long> {
}
| 19.75 | 75 | 0.829114 |
71469f408a9aa91ac61e75fc12f7d973ad70b374 | 3,351 | package org.pushtalk.server;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.pushtalk.server.api.GetRecentChatsServlet;
import org.pushtalk.server.api.GetRecentMessagesServlet;
import org.pushtalk.server.api.ShowedMessageServlet;
import org.pushtalk.server.api.TalkServlet;
import org.pushtalk.server.api.UnreadMessageServlet;
import org.pushtalk.server.api.UserInfoServlet;
import org.pushtalk.server.web.AllChannelListServlet;
import org.pushtalk.server.web.ChannelUserListServlet;
import org.pushtalk.server.web.ChattingServlet;
import org.pushtalk.server.web.EnterChannelServlet;
import org.pushtalk.server.web.ExitChannelServlet;
import org.pushtalk.server.web.MainServlet;
import org.pushtalk.server.web.NewChannelServlet;
import org.pushtalk.server.web.RootServlet;
import org.pushtalk.server.web.UserChangeNameServlet;
import org.pushtalk.server.web.UserRegisterServlet;
public class JettyServer {
static Logger LOG = Logger.getLogger(JettyServer.class);
public static void main(String[] args) throws Exception {
int port = 10010;
if (args.length >= 1) {
String sPort = args[0];
try {
port = Integer.parseInt(sPort);
} catch (NumberFormatException e) {
LOG.info("Invalid port arg - " + sPort + ". User default value - " + port);
}
}
Server server = new Server(port);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
// channel
context.addServlet(new ServletHolder(new AllChannelListServlet()), "/channel");
context.addServlet(new ServletHolder(new NewChannelServlet()), "/channel/new");
context.addServlet(new ServletHolder(new EnterChannelServlet()), "/channel/enter");
context.addServlet(new ServletHolder(new ExitChannelServlet()), "/channel/exit");
context.addServlet(new ServletHolder(new ChannelUserListServlet()), "/channel/users");
// user
context.addServlet(new ServletHolder(new RootServlet()), "/");
context.addServlet(new ServletHolder(new MainServlet()), "/main");
context.addServlet(new ServletHolder(new UserRegisterServlet()), "/user/register");
context.addServlet(new ServletHolder(new UserChangeNameServlet()), "/user/changeName");
// chatting
context.addServlet(new ServletHolder(new ChattingServlet()), "/chatting");
// ajax & api
context.addServlet(new ServletHolder(new UserInfoServlet()), "/api/user");
context.addServlet(new ServletHolder(new ShowedMessageServlet()), "/api/showedMessage");
context.addServlet(new ServletHolder(new GetRecentMessagesServlet()), "/api/getRecentMessages");
context.addServlet(new ServletHolder(new GetRecentChatsServlet()), "/api/getRecentChats");
context.addServlet(new ServletHolder(new TalkServlet()), "/api/talk");
context.addServlet(new ServletHolder(new UnreadMessageServlet()), "/api/unreadMessage");
server.start();
server.join();
LOG.info("Jetty Server started with port:" + port);
LOG.info("Push Talk Server is started. Version:" + Config.VERSION);
}
}
| 44.68 | 104 | 0.729931 |
16766e25aead6f05c81555741913400d51d51a79 | 2,197 | package com.pinxiango.studytest;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
public class CardActivity extends AppCompatActivity {
private ViewPager view_pager;
private List<Fragment> mFragments;
private String[] images = {
"http://oqe10cpgp.bkt.clouddn.com/image/greateimage/01.jpg",
"http://oqe10cpgp.bkt.clouddn.com/image/greateimage/02.jpg",
"http://oqe10cpgp.bkt.clouddn.com/image/greateimage/03.jpg",
"http://oqe10cpgp.bkt.clouddn.com/image/greateimage/04.jpg",
"http://oqe10cpgp.bkt.clouddn.com/image/greateimage/05.jpg",
"http://oqe10cpgp.bkt.clouddn.com/image/greateimage/06.jpg",
};
private List<CardItem> mCardItems;
private String link = "http://www.artbloger.com/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card);
view_pager = (ViewPager) findViewById(R.id.view_pager);
view_pager.setOffscreenPageLimit(3);
initCardItems();
initFragments();
view_pager.setPageTransformer(false, new CradTranformer(dpToPixels(2, this)));
CardFragmentAdapter cardFragmentAdapter = new CardFragmentAdapter(getSupportFragmentManager(), mFragments);
view_pager.setAdapter(cardFragmentAdapter);
}
private void initCardItems() {
mCardItems = new ArrayList<>();
String content = getString(R.string.content);
for (int i = 0; i < images.length; i++) {
mCardItems.add(new CardItem(images[i], content, link));
}
}
private void initFragments() {
mFragments = new ArrayList<>();
for (int i = 0; i < mCardItems.size(); i++) {
mFragments.add(CardFragment.newInstance(mCardItems.get(i)));
}
}
public static float dpToPixels(int dp, Context context) {
return dp * (context.getResources().getDisplayMetrics().density);
}
}
| 31.84058 | 115 | 0.67228 |
790e10b80c9b5323a2208d0f5724cb5c1574a62f | 553 | package com.helospark.lightdi.it.specialvaluecontext;
import com.helospark.lightdi.annotation.Autowired;
import com.helospark.lightdi.annotation.Configuration;
import com.helospark.lightdi.descriptor.DependencyDescriptor;
@Configuration
public class SpecialValueWithSetterInjectConfiguration {
private DependencyDescriptor descriptor;
@Autowired
public void setDescriptor(DependencyDescriptor descriptor) {
this.descriptor = descriptor;
}
public DependencyDescriptor getDescriptor() {
return descriptor;
}
}
| 26.333333 | 64 | 0.790235 |
fbc19d71ba075803611f0ff286c5dcb9f516ca12 | 253 | package com.jstarcraft.recommendation.data.processor;
import com.jstarcraft.recommendation.data.accessor.DataInstance;
/**
* 数据选择器
*
* @author Birdy
*
*/
public interface DataSelector {
boolean select(DataInstance instance);
}
| 15.8125 | 65 | 0.711462 |
205d9cbdb747de2efb376879952a428e85588902 | 4,508 | package com.frankzhu.filtermenu.holder;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
/**
* Author: ZhuWenWu
* Version V1.0
* Date: 15/5/16 18:37
* Description:
* Modification History:
* Date Author Version Description
* -----------------------------------------------------------------------------------
* 15/5/16 ZhuWenWu 1.0 1.0
* Why & What is modified:
*/
public class PopLinearLayoutManager extends LinearLayoutManager {
private int showCount = 1;
private boolean isLimitHeight = false;
public PopLinearLayoutManager(Context context) {
super(context);
}
public PopLinearLayoutManager(Context context, int showCount) {
super(context);
this.showCount = showCount;
}
public PopLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public void setShowCount(int showCount) {
this.showCount = showCount;
isLimitHeight = true;
}
public void setIsLimitHeight(boolean isLimitHeight) {
this.isLimitHeight = isLimitHeight;
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
if (isLimitHeight) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < showCount; i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
} else {
super.onMeasure(recycler, state, widthSpec, heightSpec);
}
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
if (position < getItemCount()) {
try {
View view = recycler.getViewForPosition(0);//fix 动态添加时报IndexOutOfBoundsException
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 38.20339 | 116 | 0.558341 |
a5f4d497bd111e0212548e171e1fd4e2589e223e | 944 | package com.mall.system.service;
import com.mall.common.core.mybatisplus.core.IServicePlus;
import com.mall.common.core.mybatisplus.core.PagePlus;
import com.mall.system.bo.UserBo;
import com.mall.system.entity.UmsAdmin;
import com.mall.system.vo.UserVo;
import java.util.List;
/**
* 用户信息表 服务类.
*
* @author 钟舒艺
* @since 2021-07-06
*/
public interface IUmsAdminService extends IServicePlus<UmsAdmin, UserVo> {
/**
* 根据用户名查询用户.
*
* @param userName 用户名.
* @return 用户信息(含密码)
*/
UmsAdmin getUmsAdminByUserName(String userName);
/**
* 根据角色id获取用户列表.
*
* @param roleId 角色id
* @return 用户列表
*/
List<UmsAdmin> getUserListByRoleId(Long roleId);
/**
* 条件分页查询用户列表.
*
* @param pagePlus 分页信息
* @param bo 条件
* @return 分页后信息
*/
PagePlus<UmsAdmin, UserVo> getUserListPage(
PagePlus<UmsAdmin, UserVo> pagePlus, UserBo bo
);
}
| 20.085106 | 74 | 0.638771 |
5f4460b38982f8bbb5ee753788b4e264388efe6a | 4,032 | /*
* 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.tomato.study.rpc.registry.zookeeper.impl;
import org.apache.zookeeper.WatchedEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.modules.junit4.PowerMockRunner;
import org.tomato.study.rpc.core.data.MetaData;
import org.tomato.study.rpc.registry.zookeeper.CuratorClient;
import org.tomato.study.rpc.registry.zookeeper.data.ZookeeperConfig;
import org.tomato.study.rpc.utils.ReflectUtils;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.mockito.PowerMockito.whenNew;
/**
* @author Tomato
* Created on 2021.07.18
*/
@PowerMockIgnore({"javax.management.*"})
@RunWith(PowerMockRunner.class)
public class ListenerTest extends BaseTest {
private final String microServiceId = "mock_service_id";
private final String stage = "default";
private PathChildrenListener listener;
private List<MetaData> mockChildren;
private ZookeeperRegistry spyRegistry;
@Mock
private CuratorClient mockClient;
@Mock
private WatchedEvent mockEvent;
@Before
public void init() throws Exception {
whenNew(CuratorClient.class).withAnyArguments().thenReturn(mockClient);
spyRegistry = spy(
new ZookeeperRegistry(
ZookeeperConfig.builder()
.connString("mock")
.namespace("tomato")
.charset(StandardCharsets.UTF_8)
.build()));
ReflectUtils.reflectSet(
spyRegistry,
ZookeeperRegistry.class,
"curatorWrapper",
mock(CuratorClient.class));
this.listener = new PathChildrenListener(spyRegistry, mockClient);
this.mockChildren = new ArrayList<>(mockMetadataSet(microServiceId));
}
@After
public void destroy() {
this.listener = null;
this.mockChildren = null;
}
@Test
public void watcherProcessTest() throws Exception {
// mock更新路径
String mockPath = "/tomato/" + microServiceId + "/" + stage + "/providers";
when(mockEvent.getPath()).thenReturn(mockPath);
// mock路径对应的孩子节点
Collection<URI> uriList = mockChildren.stream()
.map(MetaData::convert)
.filter(Optional::isPresent)
.map(Optional::get).collect(Collectors.toList());
List<String> children = uriList.stream()
.map(URI::toString)
.collect(Collectors.toList());
when(mockClient.getChildrenAndAddWatcher(any(), any())).thenReturn(children);
listener.process(this.mockEvent);
verify(spyRegistry, times(1)).notify(
eq(mockPath),
eq(uriList)
);
}
}
| 33.882353 | 85 | 0.679067 |
10cbe4211eff697b2813bd377236a442d40a1d0d | 1,183 | package svenhjol.charm.mixin;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.EnchantingTableBlock;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import svenhjol.charm.base.helper.EnchantmentsHelper;
@Mixin(EnchantingTableBlock.class)
public class EnchantingTableBlockMixin {
/**
* When rendering a rune particle on the client, this hook redirects
* the default check of `isOf(Blocks.BOOKSHELF)` to check
* EnchantmentsHelper.ENCHANTING_BLOCKS.
*
* If present, returns true to enable the rune particle to be rendered.
* Falls back to vanilla behavior if not.
*/
@Redirect(
method = "randomDisplayTick",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/block/BlockState;isOf(Lnet/minecraft/block/Block;)Z"
)
)
private boolean hookRandomDisplayTick(BlockState state, Block block) {
return EnchantmentsHelper.canBlockPowerEnchantingTable(state) || state.isOf(Blocks.BOOKSHELF);
}
}
| 35.848485 | 102 | 0.727811 |
e4dae9bdd57f8d6fb22ee36f5fcd780301b47463 | 1,530 | /*
* Created by Orchextra
*
* Copyright (C) 2016 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.di.modules;
import com.gigigo.ggglib.ContextProvider;
import com.gigigo.orchextra.di.modules.control.ControlModuleProvider;
import com.gigigo.orchextra.di.modules.device.DeviceModuleProvider;
import com.gigigo.orchextra.di.modules.device.UiModuleProvider;
import com.gigigo.orchextra.domain.abstractions.initialization.OrchextraStatusAccessor;
import com.gigigo.orchextra.sdk.OrchextraTasksManager;
import com.gigigo.orchextra.sdk.application.applifecycle.OrchextraActivityLifecycle;
public interface OrchextraModuleProvider extends ControlModuleProvider, DeviceModuleProvider, UiModuleProvider {
OrchextraActivityLifecycle provideOrchextraActivityLifecycle();
ContextProvider provideContextProvider();
OrchextraModule getOrchextraModule();
OrchextraTasksManager getOrchextraTasksManager();
OrchextraStatusAccessor provideOrchextraStatusAccessor();
}
| 41.351351 | 112 | 0.815033 |
1e19bc675ca69883f532806f0130c1da332b6ac3 | 11,514 | package com.serenegiant.camera;
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2021 saki t_saki@serenegiant.com
*
* 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 android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.MediaCodec;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.util.Size;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
/**
* Camera 2 API用のヘルパークラス
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class Camera2Utils implements CameraConst {
private static final boolean DEBUG = false;
private static final String TAG = Camera2Utils.class.getSimpleName();
@Retention(RetentionPolicy.SOURCE)
@IntDef({
CameraDevice.TEMPLATE_PREVIEW,
CameraDevice.TEMPLATE_STILL_CAPTURE,
CameraDevice.TEMPLATE_RECORD,
CameraDevice.TEMPLATE_VIDEO_SNAPSHOT,
CameraDevice.TEMPLATE_ZERO_SHUTTER_LAG,
CameraDevice.TEMPLATE_MANUAL,
})
public @interface RequestTemplate {}
/**
* Compares two {@code Size}s based on their areas.
*/
protected static class CompareSizesByArea implements Comparator<Size> {
@Override
public int compare(Size lhs, Size rhs) {
// We cast here to ensure the multiplications won't overflow
return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
(long) rhs.getWidth() * rhs.getHeight());
}
}
/**
* 指定した条件に合うカメラを探す
* @param manager
* @param preferedFace カメラの方向、対応するカメラがなければ異なるfaceのカメラが選択される
* @return
* @throws CameraAccessException
*/
public static CameraConst.CameraInfo findCamera(
@NonNull final CameraManager manager,
@CameraConst.FaceType final int preferedFace)
throws CameraAccessException {
if (DEBUG) Log.v(TAG, "findCamera:preferedFace=" + preferedFace);
CameraConst.CameraInfo info = null;
int targetFace;
final String[] cameraIds = manager.getCameraIdList();
if ((cameraIds != null) && (cameraIds.length > 0)) {
final int face = (preferedFace == FACING_BACK
? CameraCharacteristics.LENS_FACING_BACK
: CameraCharacteristics.LENS_FACING_FRONT);
boolean triedAllCameras = false;
targetFace = face;
String cameraId = null;
int orientation = 0;
cameraLoop:
for (; !triedAllCameras ;) {
for (final String id: cameraIds) {
final CameraCharacteristics characteristics = manager.getCameraCharacteristics(id);
if (characteristics.get(CameraCharacteristics.LENS_FACING) == targetFace) {
final StreamConfigurationMap map = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
cameraId = id;
orientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
break cameraLoop;
}
}
if ((cameraId == null) && (targetFace == face)) {
targetFace = (face == CameraCharacteristics.LENS_FACING_BACK
? CameraCharacteristics.LENS_FACING_FRONT
: CameraCharacteristics.LENS_FACING_BACK);
} else {
triedAllCameras = true;
}
}
if (!TextUtils.isEmpty(cameraId)) {
info = new CameraConst.CameraInfo(cameraId, face, orientation,
CameraConst.DEFAULT_WIDTH, CameraConst.DEFAULT_HEIGHT);
}
}
return info;
}
/**
* 指定した条件に合うカメラを探す
* @param manager
* @param width
* @param height
* @param preferedFace
* @param degrees
* @return
* @throws CameraAccessException
*/
@Nullable
public static CameraConst.CameraInfo findCamera(
@NonNull final CameraManager manager,
final int width, final int height,
final int preferedFace, final int degrees)
throws CameraAccessException {
if (DEBUG) Log.v(TAG, String.format("findCamera:Size(%dx%d),preferedFace=%d,degrees=%d",
width, height, preferedFace, degrees));
String cameraId = null;
Size previewSize = null;
int targetFace = -1;
int orientation = 0;
final String[] cameraIds = manager.getCameraIdList();
if ((cameraIds != null) && (cameraIds.length > 0)) {
final int face = (preferedFace == FACING_BACK
? CameraCharacteristics.LENS_FACING_BACK
: CameraCharacteristics.LENS_FACING_FRONT);
boolean triedAllCameras = false;
targetFace = face;
cameraLoop:
for (; !triedAllCameras ;) {
for (final String id: cameraIds) {
final CameraCharacteristics characteristics
= manager.getCameraCharacteristics(id);
if (characteristics.get(CameraCharacteristics.LENS_FACING) == targetFace) {
final StreamConfigurationMap map = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
previewSize = chooseOptimalSize(characteristics, map, width, height, degrees);
orientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
cameraId = id;
break cameraLoop;
}
}
if ((cameraId == null) && (targetFace == face)) {
targetFace = (face == CameraCharacteristics.LENS_FACING_BACK
? CameraCharacteristics.LENS_FACING_FRONT
: CameraCharacteristics.LENS_FACING_BACK);
} else {
triedAllCameras = true;
}
}
}
if (!TextUtils.isEmpty(cameraId) && (previewSize != null)) {
return new CameraConst.CameraInfo(cameraId, targetFace, orientation,
previewSize.getWidth(), previewSize.getHeight());
}
if (DEBUG) Log.w(TAG, "findCamera: not found");
return null;
}
/**
* 指定した条件に合う解像度を選択する
* @param manager
* @param cameraId
* @param targetFace
* @param width
* @param height
* @param degrees
* @return
* @throws CameraAccessException
*/
public static CameraConst.CameraInfo chooseOptimalSize(
@NonNull final CameraManager manager,
final String cameraId, @CameraConst.FaceType final int targetFace,
final int width, final int height, final int degrees)
throws CameraAccessException {
if (DEBUG) Log.v(TAG,
String.format("chooseOptimalSize:Size(%dx%d),targetFace=%d,degrees=%d",
width, height, targetFace, degrees));
final CameraCharacteristics characteristics
= manager.getCameraCharacteristics(cameraId);
final StreamConfigurationMap map = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
final Size previewSize
= chooseOptimalSize(characteristics, map, width, height, degrees);
final int orientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
if (!TextUtils.isEmpty(cameraId) && (previewSize != null)) {
return new CameraConst.CameraInfo(cameraId, targetFace, orientation,
previewSize.getWidth(), previewSize.getHeight());
}
return null;
}
/**
* 指定した条件に合う解像度を選択する
* @param characteristics
* @param map
* @param _width
* @param _height
* @param degrees
* @return
*/
public static Size chooseOptimalSize(
final CameraCharacteristics characteristics,
final StreamConfigurationMap map,
final int _width, final int _height, final int degrees) {
if (DEBUG) Log.v(TAG,
String.format("chooseOptimalSize:size(%d,%d),degrees=%d",
_width, _height, degrees));
// カメラの物理的な有効解像度を取得する
final Rect activeArraySize = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
if (DEBUG) Log.v(TAG, "activeArraySize=" + activeArraySize);
// if (DEBUG) dump_available_scene_modes(characteristics);
// MediaCodec用の解像度一覧を取得
Size[] sizes = map.getOutputSizes(MediaCodec.class); // MediaRecorder.class
if (DEBUG) { for (final Size sz : sizes) { Log.v(TAG, "chooseOptimalSize:getOutputSizes(MediaCodec)=" + sz); } }
// MediaCodec用の最大解像度を探す
final Size ppsfv = Collections.max(Arrays.asList(sizes), new CompareSizesByArea());
// widthまたはheightが未指定名の時は最大解像度を使う・・・ここは1080pに制限しといた方が良いかもしれない
if ((_width <= 0) || (_height <= 0)) {
Log.d(TAG, "chooseOptimalSize:select" + ppsfv);
return ppsfv;
}
// 縦画面か横画面かに合わせてアスペクト比を計算する(カメラ側は常に横長)
final int width = Math.max(_width, _height);
final int height = Math.min(_width, _height);
final double aspect = (width > 0) && (height > 0)
? (width / (double)height)
: (ppsfv.getWidth() / (double)ppsfv.getHeight());
final long max_areas = (width > 0) && (height > 0) ? width * (long)height : ppsfv.getWidth() * (long)ppsfv.getHeight();
double a, r, selectedDelta = Double.MAX_VALUE;
Size selectedSize = null;
long areas;
// SurfaceTextureへの描画用の解像度を一覧を取得
sizes = map.getOutputSizes(SurfaceTexture.class);
if (DEBUG) { for (final Size sz : sizes) { Log.v(TAG, "chooseOptimalSize:getOutputSizes(SurfaceTexture)=" + sz); } }
// サイズが一致するものを探す
for (Size sz : sizes) {
if ((sz.getWidth() == width) && (sz.getHeight() == height)) {
selectedSize = sz;
Log.v(TAG, "chooseOptimalSize:found(" + selectedSize + ")");
return selectedSize;
}
}
final List<Size> possible = new ArrayList<Size>();
if (selectedSize == null) {
// 指定幅と同じでアスペクト比の小さいものを探す
for (Size sz : sizes) {
a = sz.getWidth() / (double)sz.getHeight();
areas = sz.getWidth() * (long)sz.getHeight();
r = Math.abs(a - aspect) / aspect;
// if (DEBUG) Log.v(TAG, String.format("getOutputSizes(SurfaceTexture):%dx%d,a=%6.4f,r=%6.4f",
// sz.getWidth(), sz.getHeight(), a, r));
// 画素数が指定値以下でアスペクト比の差が0.2未満のを保存しておく
if ((r < 0.2) && (areas <= max_areas)) {
possible.add(sz);
}
// 指定幅と同じであればよりアスペクト比の差が小さいものを保持する
if (sz.getWidth() == width) {
if (r < selectedDelta) {
selectedSize = sz;
selectedDelta = r;
}
}
}
}
// 指定幅と同じでアスペクト比の差が5%未満のものがなければ高さ基準で再度探す
if ((selectedSize == null) || (selectedDelta >= 0.05)) {
// heightが同じでアスペクト比が+/-5%未満のを探す
selectedDelta = Double.MAX_VALUE;
selectedSize = null;
for (Size sz : sizes) {
if (sz.getWidth() == width) {
a = sz.getWidth() / (double)sz.getHeight();
r = Math.abs(a - aspect) / aspect;
if (r < selectedDelta) {
selectedSize = sz;
selectedDelta = r;
}
}
}
}
// アスペクト比の差が+/-5%未満のがあればそれを選択する
if ((selectedSize != null) && (selectedDelta < 0.05)) {
Log.d(TAG, String.format("chooseOptimalSize:select(%dx%d), request(%d,%d)",
selectedSize.getWidth(), selectedSize.getHeight(), width, height));
return selectedSize;
}
// アスペクト比の差が0.2未満の中で最大解像度を取得する
try {
selectedSize = Collections.max(possible, new CompareSizesByArea());
} catch (Exception e) {
if (DEBUG) Log.w(TAG, e);
}
// ここまで見つからなければMediaCodec用の最大解像度を使う・・・1080p以下に制限した方が良いかもしれない
if (selectedSize == null)
selectedSize = ppsfv;
Log.d(TAG, "chooseOptimalSize:select(" + selectedSize + ")");
return selectedSize;
}
}
| 33.568513 | 121 | 0.713479 |
da81ee474d207b43db40f728c659e2e209a04878 | 4,479 | package com.ab.quake_iii;
import android.app.Notification;
import android.app.PendingIntent;
import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import androidx.core.app.NotificationManagerCompat;
import org.threeten.bp.LocalTime;
import java.util.ArrayList;
import java.util.List;
public class NotificationJobService extends JobService {
private static final String TAG = "NotificationJobService";
public static LocalTime localTime;
private BackgroundTask backgroundTask;
private int selectedMagnitude;
private String selectedCity;
@Override
public boolean onStartJob(JobParameters params) {
Log.i(TAG, "KendimeLog: Schedule Job Started.");
backgroundTask = new BackgroundTask(params);
backgroundTask.execute();
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
Log.i(TAG, "KendimeLog: Schedule Job Stopped.");
return true;
}
public int startNotify(Ping lastPing) {
Intent notificationIntent = new Intent(this, SplashActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,0);
NotificationCreator nc = new NotificationCreator();
Notification notification = nc.createNotification(pendingIntent, this, lastPing);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
notificationManager.notify(1377,notification);
return START_NOT_STICKY;
}
public class BackgroundTask extends AsyncTask<Void, Void, Void>{
private Container container;
private JobParameters params;
private WebListener webListener;
private Ping notifyPing;
private List<Ping> last5eq = new ArrayList<>();
private String lastPingInformation;
private Boolean isListEmpty = false;
public BackgroundTask(JobParameters params) {
this.params = params;
}
@Override
protected Void doInBackground(Void... voids) {
Creator creator = new Creator();
creator.create();
container = Creator.getObject("container");
container.setService(true);
webListener = new WebListener();
webListener.getData();
webListener.getDataFromWeb();
Log.i(TAG, "KendimeLog: Pingler başarılı yaratıldı. Bildirim için Ping kontrolü işlemi başladı.");
List<Ping> allPings = container.getPingList();
for(int i=0; i<5; i++){
if(allPings.get(i).getMagnitudeML() >= (double) selectedMagnitude) {
last5eq.add(allPings.get(i));
}
}
if(last5eq.isEmpty()){
isListEmpty = true;
jobFinished(params, false);
return null;
}else{
notifyPing = last5eq.get(0);
}
if(!(lastPingInformation.equals(notifyPing.toString())) && notifyPing.getTime().isAfter(localTime.minusMinutes(60))){
startNotify(notifyPing);
}
jobFinished(params, false);
Log.i(TAG, "KendimeLog: Schedule Job Finished.");
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//Eğer app açılma sürecindeyse kendini sonlandırsın bu seferlik.Ya exit ya da stop bir şey. sanırım finished
NotificationCreator.editor = NotificationCreator.sharedPref.edit();
selectedMagnitude = NotificationCreator.sharedPref.getInt("selectedMagnitude", 1);
selectedCity = NotificationCreator.sharedPref.getString("selectedCity", "Çanakkale");
lastPingInformation = NotificationCreator.sharedPref.getString("lastPing", "Nothing");
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(isListEmpty == false){
NotificationCreator.editor = NotificationCreator.sharedPref.edit();
NotificationCreator.editor.remove("lastPing");
NotificationCreator.editor.putString("lastPing", notifyPing.toString());
NotificationCreator.editor.commit();
}
}
}
}
| 34.453846 | 129 | 0.647466 |
3fa981dcdc69fe0aebcd28a612348077a142019c | 7,572 | package com.rs.net.packets.logic.impl;
import java.util.Optional;
import com.rs.GameConstants;
import com.rs.game.item.Item;
import com.rs.game.map.World;
import com.rs.game.map.WorldTile;
import com.rs.game.npc.familiar.Familiar.SpecialAttack;
import com.rs.game.player.Inventory;
import com.rs.game.player.Player;
import com.rs.game.player.PlayerCombat;
import com.rs.game.player.content.Magic;
import com.rs.game.player.controller.ControllerHandler;
import com.rs.game.route.RouteEvent;
import com.rs.io.InputStream;
import com.rs.net.packets.logic.LogicPacket;
import com.rs.net.packets.logic.LogicPacketSignature;
import com.rs.utilities.Utility;
@LogicPacketSignature(packetId = 34, packetSize = 11, description = "An Interface that's used onto a Player (Magic, etc..)")
public class InterfaceOnPlayerPacket implements LogicPacket {
@Override
public void execute(Player player, InputStream stream) {
if (!player.isStarted() || !player.isClientLoadedMapRegion() || player.isDead())
return;
if (player.getMovement().isLocked()/* || player.getEmotesManager().isDoingEmote() */)
return;
final int itemId = stream.readUnsignedShort128();
int interfaceSlot = stream.readUnsignedShortLE();
int playerIndex = stream.readUnsignedShortLE128();
final boolean forceRun = stream.readUnsignedByteC() == 1;
int interfaceHash = stream.readInt();
int interfaceId = interfaceHash >> 16;
int componentId = interfaceHash - (interfaceId << 16);
if (Utility.getInterfaceDefinitionsSize() <= interfaceId)
return;
if (!player.getInterfaceManager().containsInterface(interfaceId))
return;
if (componentId == 65535)
componentId = -1;
if (componentId != -1 && Utility.getInterfaceDefinitionsComponentsSize(interfaceId) <= componentId)
return;
final Player p2 = World.getPlayers().get(playerIndex);
if (p2 == null || p2 == player || p2.isDead() || p2.isFinished()
|| !player.getMapRegionsIds().contains(p2.getRegionId()))
return;
player.getMovement().stopAll();
if (forceRun)
player.setRun(forceRun);
switch (interfaceId) {
case 1110:
if (componentId == 87)
// ClansManager.invite(player, p2);
break;
case Inventory.INVENTORY_INTERFACE:
final Item item = player.getInventory().getItem(interfaceSlot);
if (item == null || item.getId() != itemId)
return;
player.setRouteEvent(new RouteEvent(p2, () -> {
if (!ControllerHandler.execute(player, controller -> controller.processItemOnPlayer(player, p2, item)))
return;
// if (itemId == 4155)
// player.getSlayerManager().invitePlayer(p2);
}));
break;
case 662:
case 747:
if (player.getFamiliar() == null)
return;
player.resetWalkSteps();
if ((interfaceId == 747 && componentId == 15) || (interfaceId == 662 && componentId == 65)
|| (interfaceId == 662 && componentId == 74) || interfaceId == 747 && componentId == 18) {
if ((interfaceId == 662 && componentId == 74 || interfaceId == 747 && componentId == 24
|| interfaceId == 747 && componentId == 18)) {
if (player.getFamiliar().getSpecialAttack() != SpecialAttack.ENTITY)
return;
}
if (!player.isCanPvp() || !p2.isCanPvp()) {
player.getPackets().sendGameMessage("You can only attack players in a player-vs-player area.");
return;
}
if (!player.getFamiliar().canAttack(p2)) {
player.getPackets().sendGameMessage("You can only use your familiar in a multi-zone area.");
return;
} else {
player.getFamiliar().setSpecial(
interfaceId == 662 && componentId == 74 || interfaceId == 747 && componentId == 18);
player.getFamiliar().setTarget(p2);
}
}
break;
case 193:
switch (componentId) {
case 28:
case 32:
case 24:
case 20:
case 30:
case 34:
case 26:
case 22:
case 29:
case 33:
case 25:
case 21:
case 31:
case 35:
case 27:
case 23:
if (Magic.checkCombatSpell(player, componentId, 1, false)) {
player.setNextFaceWorldTile(new WorldTile(p2.getCoordFaceX(p2.getSize()),
p2.getCoordFaceY(p2.getSize()), p2.getPlane()));
if (!ControllerHandler.execute(player, controller -> controller.canAttack(player, p2))) {
return;
}
if (!player.isCanPvp() || !p2.isCanPvp()) {
player.getPackets().sendGameMessage("You can only attack players in a player-vs-player area.");
return;
}
if (!p2.isMultiArea() || !player.isMultiArea()) {
if (player.getAttackedBy() != p2 && player.getAttackedByDelay() > Utility.currentTimeMillis()) {
player.getPackets()
.sendGameMessage("That " + (player.getAttackedBy().isPlayer() ? "player" : "npc")
+ " is already in combat.");
return;
}
if (p2.getAttackedBy() != player && p2.getAttackedByDelay() > Utility.currentTimeMillis()) {
if (p2.getAttackedBy().isNPC()) {
p2.setAttackedBy(player); // changes
// enemy
// to player,
// player has
// priority over
// npc on single
// areas
} else {
player.getPackets().sendGameMessage("That player is already in combat.");
return;
}
}
}
player.getAction().setAction(new PlayerCombat(player, Optional.of(p2)));
}
break;
}
case 192:
switch (componentId) {
case 25: // air strike
case 28: // water strike
case 30: // earth strike
case 32: // fire strike
case 34: // air bolt
case 39: // water bolt
case 42: // earth bolt
case 45: // fire bolt
case 49: // air blast
case 52: // water blast
case 58: // earth blast
case 63: // fire blast
case 70: // air wave
case 73: // water wave
case 77: // earth wave
case 80: // fire wave
case 86: // teleblock
case 84: // air surge
case 87: // water surge
case 89: // earth surge
case 91: // fire surge
case 99: // storm of armadyl
case 36: // bind
case 66: // Sara Strike
case 67: // Guthix Claws
case 68: // Flame of Zammy
case 55: // snare
case 81: // entangle
if (Magic.checkCombatSpell(player, componentId, 1, false)) {
player.setNextFaceWorldTile(new WorldTile(p2.getCoordFaceX(p2.getSize()),
p2.getCoordFaceY(p2.getSize()), p2.getPlane()));
if (!ControllerHandler.execute(player, controller -> controller.canAttack(player, p2))) {
return;
}
if (!player.isCanPvp() || !p2.isCanPvp()) {
player.getPackets().sendGameMessage("You can only attack players in a player-vs-player area.");
return;
}
if (!p2.isMultiArea() || !player.isMultiArea()) {
if (player.getAttackedBy() != p2 && player.getAttackedByDelay() > Utility.currentTimeMillis()) {
player.getPackets()
.sendGameMessage("That " + (player.getAttackedBy().isPlayer() ? "player" : "npc")
+ " is already in combat.");
return;
}
if (p2.getAttackedBy() != player && p2.getAttackedByDelay() > Utility.currentTimeMillis()) {
if (p2.getAttackedBy().isNPC()) {
p2.setAttackedBy(player); // changes
// enemy
// to player,
// player has
// priority over
// npc on single
// areas
} else {
player.getPackets().sendGameMessage("That player is already in combat.");
return;
}
}
}
player.getAction().setAction(new PlayerCombat(player, Optional.of(p2)));
}
break;
}
break;
case 430:
Magic.processLunarSpell(player, componentId, p2);
break;
}
if (GameConstants.DEBUG)
System.out.println("Spell:" + componentId);
}
} | 34.108108 | 124 | 0.642102 |
43ba3d17a18c042e043cee05ffc7f51a50a673eb | 918 | package org.silknow.converter.ontologies;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.ResourceFactory;
import org.jetbrains.annotations.Contract;
public class Schema {
protected static final Property property(String uri) {
return ResourceFactory.createProperty(NS, uri);
}
public static final String NS = "http://schema.org/";
@Contract(pure = true)
public static String getURI() {
return NS;
}
public static final Property birthPlace = property("birthPlace");
public static final Property deathPlace = property("deathPlace");
public static final Property birthDate = property("birthDate");
public static final Property deathDate = property("deathDate");
public static final Property startTime = property("startTime");
public static final Property contentUrl = property("contentUrl");
public static final Property error = property("error");
}
| 29.612903 | 67 | 0.754902 |
599bfb003cb907a884297146685e9b241508f6a5 | 1,987 | package org.r10r.slqify.testutils;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import org.testcontainers.containers.PostgreSQLContainer;
/**
* A class that starts a postgres server in a static way.
*
* Therefore this server can be re-used across different tests.
* This reduces the time it takes to run integration tests dramatically.
*
* Notes:
* - This does NOT WORK when tests run in parallel.
* - Re-use of the postgres server can only be guaranteed if all tests run in the same JVM.
*/
public class ARunningPostgresServer {
private static Logger logger = LoggerFactory.getLogger(ARunningPostgresServer.class);
private static PostgreSQLContainer postgreSQLContainer;
static {
try {
startPostgres();
} catch (Exception e) {
throw new RuntimeException(e);
}
addShutdownHook();
}
public static DataSource getDatasource() {
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl(postgreSQLContainer.getJdbcUrl());
hikariConfig.setUsername(postgreSQLContainer.getUsername());
hikariConfig.setPassword(postgreSQLContainer.getPassword());
return new HikariDataSource(hikariConfig);
}
private static void startPostgres() throws Exception {
String dockerImageName = PostgreSQLContainer.IMAGE + ":11";
postgreSQLContainer = new PostgreSQLContainer<>(dockerImageName);
postgreSQLContainer.start();
}
private static void addShutdownHook() {
logger.info("Adding hook to shut-down postgres server");
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
logger.info("Shutting-down embedded postgres Server");
postgreSQLContainer.stop();
}
});
}
}
| 30.106061 | 91 | 0.685959 |
f8ba55e80b1addeca1ac8c827d312c7adbecf5ae | 184 | package org.yewon.parent;
import org.yewon.grand.Life;
public class Animal extends Life{
public void move() {
System.out.println("STATUS: Life.Animal.move()");
}
}
| 15.333333 | 52 | 0.663043 |
1cda7e93733bfe1dc7a13793192ccdc112fed793 | 6,221 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ambari.view.weather;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.ambari.view.NoSuchResourceException;
import org.apache.ambari.view.ReadRequest;
import org.apache.ambari.view.ResourceAlreadyExistsException;
import org.apache.ambari.view.ResourceProvider;
import org.apache.ambari.view.SystemException;
import org.apache.ambari.view.UnsupportedPropertyException;
import org.apache.ambari.view.ViewContext;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Resource provider for city resource of the weather view.
*/
public class CityResourceProvider implements ResourceProvider<CityResource> {
/**
* The logger.
*/
protected final static Logger LOG =
LoggerFactory.getLogger(CityResourceProvider.class);
/**
* The view context.
*/
@Inject
ViewContext viewContext;
// ----- ResourceProvider --------------------------------------------------
@Override
public CityResource getResource(String resourceId, Set<String> propertyIds) throws
SystemException, NoSuchResourceException, UnsupportedPropertyException {
Map<String, String> properties = viewContext.getProperties();
String units = properties.get("units");
try {
return getResource(resourceId, units, propertyIds);
} catch (IOException e) {
throw new SystemException("Can't get city resource " + resourceId + ".", e);
}
}
@Override
public Set<CityResource> getResources(ReadRequest request) throws
SystemException, NoSuchResourceException, UnsupportedPropertyException {
Set<CityResource> resources = new HashSet<CityResource>();
Map<String, String> properties = viewContext.getProperties();
String units = properties.get("units");
String cityStr = properties.get("cities");
String[] cities = cityStr.split(";");
for (String city : cities) {
try {
resources.add(getResource(city, units, request.getPropertyIds()));
} catch (IOException e) {
throw new SystemException("Can't get city resource " + city + ".", e);
}
}
return resources;
}
@Override
public void createResource(String resourceId, Map<String, Object> stringObjectMap) throws
SystemException, ResourceAlreadyExistsException, NoSuchResourceException, UnsupportedPropertyException {
throw new UnsupportedOperationException("Creating city resources is not currently supported");
}
@Override
public boolean updateResource(String resourceId, Map<String, Object> stringObjectMap) throws
SystemException, NoSuchResourceException, UnsupportedPropertyException {
throw new UnsupportedOperationException("Updating city resources is not currently supported");
}
@Override
public boolean deleteResource(String resourceId) throws
SystemException, NoSuchResourceException, UnsupportedPropertyException {
throw new UnsupportedOperationException("Deleting city resources is not currently supported");
}
// ----- helper methods ----------------------------------------------------
// Get a city resource from the given id.
private CityResource getResource(String resourceId, String units, Set<String> propertyIds) throws IOException {
CityResource resource = new CityResource();
resource.setId(resourceId);
resource.setUnits(units);
if (isWeatherRequested(propertyIds)) {
resource.setWeather(getWeatherProperty(resourceId, units));
}
return resource;
}
// Determine whether the weather property has been requested.
private boolean isWeatherRequested(Set<String> propertyIds) {
for (String propertyId : propertyIds) {
if (propertyId.startsWith("weather")) {
return true;
}
}
return false;
}
// Populate the weather property.
private Map<String, Object> getWeatherProperty(String city, String units) throws IOException {
URIBuilder uriBuilder = new URIBuilder();
uriBuilder.setScheme("http");
uriBuilder.setHost("api.openweathermap.org");
uriBuilder.setPath("/data/2.5/weather");
uriBuilder.setParameter("q", city);
uriBuilder.setParameter("units", units);
String url = uriBuilder.toString();
InputStream in = readFrom(url);
try {
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> results = new Gson().fromJson(IOUtils.toString(in, "UTF-8"), mapType);
ArrayList list = (ArrayList) results.get("weather");
if (list != null) {
Map weather = (Map) list.get(0);
results.put("weather", weather);
results.put("icon_src", "http://openweathermap.org/img/w/" + weather.get("icon"));
}
return results;
} finally {
in.close();
}
}
// Get an input stream from the given URL spec.
private static InputStream readFrom(String spec) throws IOException {
URLConnection connection = new URL(spec).openConnection();
connection.setConnectTimeout(5000);
connection.setDoOutput(true);
return connection.getInputStream();
}
}
| 33.809783 | 113 | 0.715319 |
434915854792350e0d6e28c76f1099569f5c5c5e | 127 | package cn.gyw.middleware.shardingjdbc;
public class ShardingJdbcApp {
public static void main(String[] args) {
}
}
| 14.111111 | 44 | 0.708661 |
ede70cd36363e22ce940282431d48d6deb87df89 | 2,965 | /*
* Copyright 2018. AppDynamics LLC and its affiliates.
* All Rights Reserved.
* This is unpublished proprietary source code of AppDynamics LLC and its affiliates.
* The copyright notice above does not evidence any actual or intended publication of such source code.
*/
package com.appdynamics.extensions.logstash.ssl;
import java.io.File;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLSocket;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.appdynamics.extensions.PathResolver;
import com.appdynamics.extensions.logstash.LogstashAlertExtension;
import com.appdynamics.extensions.logstash.config.SSL;
public class SocketFactory {
private static final Logger LOGGER = Logger.getLogger(SocketFactory.class);
public static Socket createSocket(SSL ssl, String host, int port) throws Exception {
Socket socket = null;
if (ssl != null && ssl.isEnable()) {
if (ssl.isAllowSelfSignedCert()) {
EasySSLProtocolSocketFactory sslProtocolSocketFactory = new EasySSLProtocolSocketFactory();
socket = sslProtocolSocketFactory.createSocket(host, port);
} else {
AuthSSLProtocolSocketFactory sslProtocolSocketFactory = new AuthSSLProtocolSocketFactory(
getUrl(ssl.getKeystorePath()), ssl.getKeystorePassword(),
getUrl(ssl.getTruststorePath()), ssl.getTruststorePassword());
socket = sslProtocolSocketFactory.createSocket(host, port);
}
// fix for SSL Error: SSLv2Hello is disabled, when jdk6 initiates SSL connection with jdk7
SSLSocket sslSocket = (SSLSocket) socket;
List<String> enabledProtocols = new ArrayList<String>();
for (String protocol : sslSocket.getEnabledProtocols()) {
if (!protocol.equalsIgnoreCase("SSLv2Hello")) {
enabledProtocols.add(protocol);
}
}
sslSocket.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
} else {
socket = new Socket(host, port);
}
return socket;
}
private static URL getUrl(String filename) throws MalformedURLException {
URL url = null;
if(StringUtils.isBlank(filename)){
url = new URL("");
} else {
File file = new File(filename);
if(file.exists()){
//for absolute path
url = file.toURI().toURL();
} else {
//for relative paths
File jarPath = PathResolver.resolveDirectory(LogstashAlertExtension.class);
url = new URL(String.format("%s%s%s", jarPath.toURI().toURL(), File.separator, filename));
}
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Filepath url: " + url.toString());
}
return url;
}
}
| 30.255102 | 103 | 0.688702 |
616039f65993c329017586a9eabe77e6f89cb0f3 | 1,305 | package com.zhenjin.rmi.client;
import com.zhenjin.rmi.entity.User;
import com.zhenjin.rmi.facade.UserFacade;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.rmi.RemoteException;
import java.util.List;
/**
* 测试类
*
* @author ZhenJin
*/
@RunWith(SpringRunner.class)
// 在SpringBootTest注解中不能加参数
// webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
// 否则会报 UnsatisfiedDependencyException: Error creating bean with name
@SpringBootTest(classes = RmiClientApplication.class)
public class RmiClientTest {
@Autowired
private UserFacade userFacade;
@Test
public void userByNameTest() {
try {
User zhenJin = userFacade.getByName("ZhenJin");
System.out.println("=======> " + zhenJin + " <=======");
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Test
public void userBySexTest() {
try {
List<User> userList = userFacade.getBySex("男");
userList.forEach(System.out::println);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
| 26.1 | 69 | 0.677395 |
30c46354397125fadc5d0cb3927c15fadb373af4 | 1,067 | package search;
import java.util.ArrayList;
import java.util.Random;
/** Generates one-dimensional lists with random values.
*
* @author Douglas Luman
*/
public class RandomList {
ArrayList<Integer> used = new ArrayList<Integer>();
public final int[] list;
private Random seed = new Random();
/** Constructor.
*
* @param indexes Length of dimension
*/
public RandomList(int indexes) {
int number;
this.list = new int[indexes];
for(int i = 0; i < this.list.length; i++) {
do {
number = this.seed.nextInt(indexes + 50) + 1;
this.list[i] = number;
} while (checkUsed(number));
this.used.add(number);
}
}
/** Checks if a number has already been used.
*
* @param number Number to check
*/
private boolean checkUsed(int number){
if(this.used.indexOf(number) > -1) {
return true;
}
return false;
}
public String toString() {
String result = new String();
for (int number : this.list) {
result += number + "\n";
}
return result;
}
} | 21.34 | 55 | 0.606373 |
1ed800805e2775f72a6ba848455a9c35a8028651 | 1,661 | package com.webleader.appms.db.service.communication;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import com.webleader.appms.bean.communication.EvacuateDetail;
/**
* @className EvacuationService
* @description 撤离呼叫信息查询
* @author ding
* @date 2017年4月22日 上午10:57:18
* @version 1.0.0
*/
public interface EvacuationService {
/**
* @description 通过区域ID,evacuateId,查询详细的撤离呼叫信息
* @param condition:regionId,evacuateId,startTime,endTime,pageSize,pageBegin
* @return List<EvacuateDetail>
* @throws SQLException
*/
public List<EvacuateDetail> listEvacuateDetailByPageCondition(Map<Object, Object> condition) throws SQLException;
/**
* @description 通过条件,查询符合的报警记录条件数
* @param condition:regionId,evacuateId,startTime,endTime,pageSize,pageBegin
* @return int
* @throws SQLException
*/
public int countEvacuateDetailByCondition(Map<Object, Object> condition) throws SQLException;
/**
* @description 通过userId,regionId,startTime,endTime 查询得到所有符合需求的员工基本信息,为了插入到撤离表中
* @param condition
* @return
* @throws SQLException
* @author ding
*/
public List<Map<Object, Object>> getInsertEvacuation(Map<Object, Object> condition) throws SQLException;
/**
* @description 添加撤退呼叫总记录
* @param evacuation
* @return int
* @throws SQLException
*/
public int insertEvacuation(List<Map<Object, Object>> evacuation) throws SQLException;
/**
* @description 添加撤离呼叫详情记录
* @param evacuateDetail
* @return
* @throws SQLException
*/
public int insertEvacuateDetail(List<Map<Object, Object>> evacuateDetail) throws SQLException;
}
| 28.152542 | 115 | 0.724865 |
dc5da5d77609c91c037ae356154e6a3336d41479 | 6,563 | package com.example.developerandroidx.ui.widget.codeView;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import com.example.developerandroidx.R;
import com.example.developerandroidx.base.BaseActivityWithButterKnife;
import com.example.developerandroidx.utils.Constant;
import butterknife.BindView;
import butterknife.OnClick;
import thereisnospon.codeview.CodeView;
import thereisnospon.codeview.CodeViewTheme;
/**
* 描述:代码展示界面
* 引用:https://github.com/Thereisnospon/CodeView
*/
public class CodeViewActivity extends BaseActivityWithButterKnife {
private String code;
@BindView(R.id.cv_code_view)
CodeView cv_code_view;
@BindView(R.id.tltle)
View tltle;
@BindView(R.id.iv_shrink)
ImageView iv_shrink;
private ChangeOrientationHandler handler;
private SensorManager sm;
private Sensor sensor;
private OrientationSensorListener listener;
private class ChangeOrientationHandler extends Handler {
@SuppressLint("SourceLockedOrientationActivity")
@Override
public void handleMessage(Message msg) {
if (msg.what == 888) {
int orientation = msg.arg1;
if (orientation > 45 && orientation < 135) {
if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
// Log.d(MainActivity.TAG, "横屏翻转: ");
} else if (orientation > 135 && orientation < 225) {
//倒转竖屏,效果还是竖屏,所以不做处理
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
// Log.d(MainActivity.TAG, "竖屏翻转: ");
} else if (orientation > 225 && orientation < 315) {
if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// Log.d(MainActivity.TAG, "横屏: ");
} else if ((orientation > 315 && orientation < 360) || (orientation > 0 && orientation < 45)) {
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Log.d(MainActivity.TAG, "竖屏: ");
}
}
super.handleMessage(msg);
}
}
private class OrientationSensorListener implements SensorEventListener {
private static final int _DATA_X = 0;
private static final int _DATA_Y = 1;
private static final int _DATA_Z = 2;
public static final int ORIENTATION_UNKNOWN = -1;
private Handler rotateHandler;
public OrientationSensorListener(Handler handler) {
rotateHandler = handler;
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
int orientation = ORIENTATION_UNKNOWN;
float X = -values[_DATA_X];
float Y = -values[_DATA_Y];
float Z = -values[_DATA_Z];
float magnitude = X * X + Y * Y;
// Don't trust the angle if the magnitude is small compared to the y value
if (magnitude * 4 >= Z * Z) {
float OneEightyOverPi = 57.29577957855f;
float angle = (float) Math.atan2(-Y, X) * OneEightyOverPi;
orientation = 90 - (int) Math.round(angle);
// normalize to 0 - 359 range
while (orientation >= 360) {
orientation -= 360;
}
while (orientation < 0) {
orientation += 360;
}
}
if (rotateHandler != null) {
rotateHandler.obtainMessage(888, orientation, 0).sendToTarget();
}
}
}
@Override
protected int bindLayout() {
return R.layout.activity_code_view;
}
@SuppressLint("SourceLockedOrientationActivity")
@Override
protected void initView() {
cv_code_view.setTheme(CodeViewTheme.ANDROIDSTUDIO);
cv_code_view.fillColor();
tltle.setBackgroundResource(R.color.codeViewBackground);
setTitleTextLight();
setTitle("Code");
iv_right.setImageResource(R.mipmap.icon_blow_up);
iv_right.setVisibility(View.VISIBLE);
//取消使用重力感应切换,使用体验比较差,改用放大缩小按钮
//根据手重力感应切换屏幕方向
handler = new ChangeOrientationHandler();
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
listener = new OrientationSensorListener(handler);
sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);
//横屏的时候不显示title栏,可视面积最大化
if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ||
getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
tltle.setVisibility(View.GONE);
iv_shrink.setVisibility(View.VISIBLE);
} else {
tltle.setVisibility(View.VISIBLE);
iv_shrink.setVisibility(View.GONE);
}
}
@Override
protected void initData() {
code = getIntent().getStringExtra(Constant.IntentParams.INTENT_PARAM);
cv_code_view.showCode(code);
}
@SuppressLint("SourceLockedOrientationActivity")
@OnClick({R.id.iv_right, R.id.iv_shrink})
public void click(View v) {
switch (v.getId()) {
case R.id.iv_right:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
break;
case R.id.iv_shrink:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
}
}
@Override
protected void onPause() {
sm.unregisterListener(listener);
super.onPause();
}
@Override
protected void onResume() {
sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);
super.onResume();
}
}
| 35.284946 | 111 | 0.635075 |
62f8b9fc402398d95dd8ff58eae5047b0185a6d1 | 9,776 | package laurencewarne.secondspace.common;
import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;
import java.util.stream.Collectors;
import com.artemis.Component;
import com.artemis.World;
import com.artemis.WorldConfiguration;
import com.artemis.WorldConfigurationBuilder;
import com.artemis.link.EntityLinkManager;
import com.artemis.managers.WorldSerializationManager;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.esotericsoftware.kryonet.Listener.TypeListener;
import com.esotericsoftware.kryonet.Server;
import org.aeonbits.owner.ConfigFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import laurencewarne.componentlookup.ComponentLookupPlugin;
import laurencewarne.secondspace.common.init.ServerConfig;
import laurencewarne.secondspace.common.manager.ChunkManager;
import laurencewarne.secondspace.common.manager.ConnectionManager;
import laurencewarne.secondspace.common.ship.ShipCoordinateLocaliser;
import laurencewarne.secondspace.common.system.AugmentationHandlerSystem;
import laurencewarne.secondspace.common.system.CannonCooldownSystem;
import laurencewarne.secondspace.common.system.CannonFiringSystem;
import laurencewarne.secondspace.common.system.CollisionSystem;
import laurencewarne.secondspace.common.system.InitSpawnedEntitiesSystem;
import laurencewarne.secondspace.common.system.PhysicsRectangleSynchronizerSystem;
import laurencewarne.secondspace.common.system.PhysicsSystem;
import laurencewarne.secondspace.common.system.PlayerShipCreatorSystem;
import laurencewarne.secondspace.common.system.ShipConnectionSystem;
import laurencewarne.secondspace.common.system.ShipPartRemovalSystem;
import laurencewarne.secondspace.common.system.ShipPositioningSystem;
import laurencewarne.secondspace.common.system.SpawnFromTemplateSystem;
import laurencewarne.secondspace.common.system.TemplateLoadingSystem;
import laurencewarne.secondspace.common.system.TerminalSystem;
import laurencewarne.secondspace.common.system.ThrusterSystem;
import laurencewarne.secondspace.common.system.WeldControllerSystem;
import laurencewarne.secondspace.common.system.WorldDeserializationSystem;
import laurencewarne.secondspace.common.system.WorldSerializationSystem;
import laurencewarne.secondspace.common.system.command.AddRectangleCommandExecutorSystem;
import laurencewarne.secondspace.common.system.command.AddWeldCommandExecutorSystem;
import laurencewarne.secondspace.common.system.command.AugmentationCommandExecutorSystem;
import laurencewarne.secondspace.common.system.command.EntityRemovalCommandExecutorSystem;
import laurencewarne.secondspace.common.system.command.SaveCommandExecutorSystem;
import laurencewarne.secondspace.common.system.command.SpawnCommandExecutorSystem;
import laurencewarne.secondspace.common.system.network.FromClientAuthenticatorSystem;
import laurencewarne.secondspace.common.system.network.NetworkInitializationSystem;
import laurencewarne.secondspace.common.system.network.NetworkRegisterSystem;
import laurencewarne.secondspace.common.system.network.NewClientConnectionSystem;
import laurencewarne.secondspace.common.system.network.RegisterAuthSystem;
import laurencewarne.secondspace.common.system.network.StateSenderSystem;
import laurencewarne.secondspace.common.system.resolvers.ConnectionToWeldSystem;
import laurencewarne.secondspace.common.system.resolvers.PhysicsRectangleDataResolverSystem;
import lombok.Getter;
import lombok.NonNull;
import net.fbridault.eeel.EEELPlugin;
import net.mostlyoriginal.api.event.common.EventSystem;
/**
* Headless implementation of {@link Game}, ie does no rendering and creates no
* windows, just updates the world.
*/
@Getter
public class SecondSpaceServerBase extends Game {
private final Logger logger = LoggerFactory.getLogger(SecondSpaceServerBase.class);
private com.badlogic.gdx.physics.box2d.World box2dWorld;
private World world;
private Server server;
@Override
public void create() {
////////////////////////
// Load server config //
////////////////////////
FileHandle serverConfigFile = Gdx.files.local("server.properties");
logger.info("Loading server config file");
final Properties serverProperties = new Properties();
try {
serverProperties.load(serverConfigFile.read());
logger.info("Loaded server config file: " + serverConfigFile.path());
}
catch (GdxRuntimeException e){
logger.info(
"Server properties file is not a valid file or missing," +
" using default server configuration"
);
}
catch (IOException|IllegalArgumentException e){
logger.error(
"Error occurred whilst reading the server properties file," +
" using default server configuration."
);
}
ServerConfig serverConfig = ConfigFactory.create(
ServerConfig.class, serverProperties
);
server = new Server();
//////////////////////////////////////////////////////////////////
// Create world configuration, add plugins and systems to world //
//////////////////////////////////////////////////////////////////
final WorldConfigurationBuilder setupBuilder =
new WorldConfigurationBuilder();
setupWorldConfig(setupBuilder);
final WorldConfiguration setup = setupBuilder.build();
/////////////////////////////////////
// Inject non-artemis dependencies //
/////////////////////////////////////
injectDependencies(setup, serverConfig);
///////////////////////////////
// Create Artermis World obj //
///////////////////////////////
logger.info("Initializing world systems");
world = new World(setup);
logger.info("Finished intializing world systems");
}
/**
* Add systems and plugins to the artemis {@link WorldConfigurationBuilder} here.
*
* @param configBuilder {@link WorldConfigurationBuilder} obj to use
*/
protected void setupWorldConfig(WorldConfigurationBuilder configBuilder) {
configBuilder
.dependsOn(EntityLinkManager.class)
.with(new EEELPlugin())
.with(new ComponentLookupPlugin())
.with( // Deserialization and events
new EventSystem(),
new WorldSerializationManager(),
new WorldDeserializationSystem()
)
.with( // Managers
new ConnectionManager(),
new ChunkManager()
)
.with( // Network
new NetworkRegisterSystem(), // Registers classes for Kryo
new NetworkInitializationSystem(), // Starts server
new NewClientConnectionSystem(), // Handles new clients
new StateSenderSystem(), // Sends world state to clients
new FromClientAuthenticatorSystem(), // Handles client requests
new RegisterAuthSystem() // Handles specific requests
)
.with( // Terminal and command systems
new TerminalSystem(),
new AddRectangleCommandExecutorSystem(),
new AddWeldCommandExecutorSystem(),
new SpawnCommandExecutorSystem(),
new AugmentationCommandExecutorSystem(),
new EntityRemovalCommandExecutorSystem(),
new SaveCommandExecutorSystem()
)
.with( // Entity creation and initialization
new TemplateLoadingSystem(),
new SpawnFromTemplateSystem(),
new AugmentationHandlerSystem(),
new InitSpawnedEntitiesSystem()
)
.with( // Create fron-end components from back-end components
new PhysicsRectangleDataResolverSystem(),
new ConnectionToWeldSystem()
)
.with( // Ship and ShipPart handling
// Adds welds in box2d world
new WeldControllerSystem(),
// Sends WeldRequests when ShipParts are added
new ShipConnectionSystem(),
new ShipPositioningSystem(),
new ShipPartRemovalSystem()
)
.with( // 'vanity' systems
new PhysicsSystem(1f/40f),
new CollisionSystem(),
new ThrusterSystem(),
new CannonFiringSystem(),
new CannonCooldownSystem(),
new PlayerShipCreatorSystem()
)
.with( // Synchronizes front-end components and back-end components
new PhysicsRectangleSynchronizerSystem()
)
.with( // Serialization
new WorldSerializationSystem()
);
}
/**
* Inject system dependencies or perform any other config on the {@link WorldConfiguration} object prior to {@link World} creation.
*
* @param setup
* @param serverConfig loaded server configuration file
*/
protected void injectDependencies(
@NonNull WorldConfiguration setup, @NonNull ServerConfig serverConfig
) {
setup.register(new ShipCoordinateLocaliser());
box2dWorld = new com.badlogic.gdx.physics.box2d.World(
new Vector2(0f, 0f), true
);
setup.register(box2dWorld);
final FileHandle worldSaveFile = Gdx.files.local(
serverConfig.worldSaveFileLocation()
);
if (!worldSaveFile.exists()) {
logger.info("Creating empty world save file: {}", worldSaveFile.path());
// Minimum acceptable JSON file
worldSaveFile.writeString("{}", false);
}
setup.register("worldSaveFile", worldSaveFile);
final FileHandle[] templateFiles = Gdx.files.local(
serverConfig.templatesDirectory()
).list();
setup.register(
"templateFiles",
Arrays.stream(templateFiles).collect(Collectors.toList())
);
setup.register("server", server);
setup.register("kryo", server.getKryo());
final TypeListener listener = new TypeListener();
server.addListener(listener);
setup.register(listener);
setup.register(
"server-to-client-components",
new Array<Class<? extends Component>>()
);
setup.register(
"client-to-server-components",
new Array<Class<? extends Component>>()
);
}
@Override
public void render() {
world.setDelta(Gdx.graphics.getDeltaTime());
world.process();
}
@Override
public void dispose() {
world.dispose();
}
}
| 37.891473 | 135 | 0.753785 |
6cce19683e3eb60446f4dc194e32240d49ab5dc5 | 2,994 | class FlexTester2 {
public static void main (String[] args) {
System.out.println("Hello World!");
System.out.println("This is FlexTester v2.0!\r\n");
CompareToEqualsTest();
SortTest();
GetValueSearchForTest();
System.out.println("\r\nGoodbye!");
}
public static void GetValueSearchForTest () {
System.out.println("======== getValue() ========");
FlexArrayRectangle list1 = CreateRandomRectangle(20, true);
System.out.println("List before getValue: " + list1);
System.out.println("Middle of the list: " + list1.getValue(list1.getLength() / 2 - 1));
System.out.println("First element of the list: " + list1.getValue(0));
System.out.println("Last element of the list: " + list1.getValue(list1.getLength() - 1));
System.out.println("Non active element of the list: " + list1.getValue(list1.getLength() + 100));
System.out.println("======== searchFor() ========");
System.out.println("List before searchFor: " + list1);
System.out.println("SearchFor element with value Rect(12,12) IN the list: " + list1.searchFor(new Rectangle(12, 12)));
System.out.println("SearchFor element with value Rect(100,100) NOT IN the list: " + list1.searchFor(new Rectangle(100,100)));
}
public static void SortTest () {
System.out.println("======== sort() ========");
FlexArrayRectangle list1 = CreateRandomRectangle(20, true);
System.out.println("List before sort: " + list1);
list1.sort();
System.out.println("List after sort: " + list1);
}
public static void CompareToEqualsTest () {
System.out.println("======== compareTo() ========");
FlexArrayRectangle list1 = CreateRandomRectangle(20, false);
FlexArrayRectangle list2 = CreateRandomRectangle(20, true);
FlexArrayRectangle list3 = CreateRandomRectangle(12, true);
System.out.println(list1);
System.out.println(list2);
System.out.println(list3);
System.out.println(list1.compareTo(list2)); // Returns 0, since they have same sum
System.out.println(list1.compareTo(list3)); // Returns 1, they have different sum
System.out.println(list2.compareTo(list3)); // Returns 1, they have different sum
System.out.println("======== equals() ========");
System.out.println(list1.equals(list2)); // Returns true, tho they are in different order, they have the same sum
System.out.println(list1.equals(list3)); // Returns false, they have different sum
}
// Creates a Random Primitive Object for testing
// j is the size of the array, random is whether or not the values should be in a random order
public static FlexArrayRectangle CreateRandomRectangle (int j, boolean random) {
FlexArrayRectangle list = new FlexArrayRectangle(j);
for (int i = 0; i < j; i++) {
if (random)
list.insert((int)(Math.random() * j - 1), new Rectangle(i, i));
else
list.append(new Rectangle(i, i));
}
return list;
}
} | 41.013699 | 129 | 0.651971 |
c56c067d28dfa500b10ae83cb8abb56b64c7989f | 1,970 |
package fr.cg44.plugin.socle.api.tripadvisor.bean;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"abbrv",
"level",
"name",
"location_id"
})
public class Ancestor {
@JsonProperty("abbrv")
private Object abbrv;
@JsonProperty("level")
private String level;
@JsonProperty("name")
private String name;
@JsonProperty("location_id")
private String locationId;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("abbrv")
public Object getAbbrv() {
return abbrv;
}
@JsonProperty("abbrv")
public void setAbbrv(Object abbrv) {
this.abbrv = abbrv;
}
@JsonProperty("level")
public String getLevel() {
return level;
}
@JsonProperty("level")
public void setLevel(String level) {
this.level = level;
}
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
@JsonProperty("location_id")
public String getLocationId() {
return locationId;
}
@JsonProperty("location_id")
public void setLocationId(String locationId) {
this.locationId = locationId;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
| 23.452381 | 85 | 0.680711 |
56756d6bc4d3201ca03beb564051fa93d46fe288 | 1,346 | /*
* Copyright 2017 Huawei Technologies Co., Ltd.
*
* 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.openo.vnfsdkfunctest.responsehandler;
import org.junit.Before;
import org.junit.Test;
import org.openo.vnfsdk.functest.responsehandler.TestResult;
import static org.junit.Assert.assertNotNull;
public class TestResultTest {
private TestResult testResult = null;
@Before
public void setUp() {
testResult = new TestResult();
}
@Test
public void testResultTest() {
testResult.setName("Huawei");
testResult.setDescription("description");
testResult.setStatus("success");
assertNotNull( testResult );
assertNotNull( testResult.getName() );
assertNotNull( testResult.getStatus() );
assertNotNull( testResult.getDescription() );
}
}
| 29.26087 | 75 | 0.713224 |
31d5e2e085bda25980ed67c63db47f2f2dc0f37c | 3,249 | package net.minecraft.world.gen.foliageplacer;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.Random;
import java.util.Set;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MutableBoundingBox;
import net.minecraft.world.gen.IWorldGenerationReader;
import net.minecraft.world.gen.feature.BaseTreeFeatureConfig;
import net.minecraft.world.gen.feature.FeatureSpread;
public class DarkOakFoliagePlacer extends FoliagePlacer {
public static final Codec<DarkOakFoliagePlacer> field_236745_a_ = RecordCodecBuilder.create((p_236746_0_) -> {
return func_242830_b(p_236746_0_).apply(p_236746_0_, DarkOakFoliagePlacer::new);
});
public DarkOakFoliagePlacer(FeatureSpread p_i241997_1_, FeatureSpread p_i241997_2_) {
super(p_i241997_1_, p_i241997_2_);
}
protected FoliagePlacerType<?> func_230371_a_() {
return FoliagePlacerType.field_236770_i_;
}
protected void func_230372_a_(IWorldGenerationReader p_230372_1_, Random p_230372_2_, BaseTreeFeatureConfig p_230372_3_, int p_230372_4_, FoliagePlacer.Foliage p_230372_5_, int p_230372_6_, int p_230372_7_, Set<BlockPos> p_230372_8_, int p_230372_9_, MutableBoundingBox p_230372_10_) {
BlockPos blockpos = p_230372_5_.func_236763_a_().up(p_230372_9_);
boolean flag = p_230372_5_.func_236765_c_();
if (flag) {
this.func_236753_a_(p_230372_1_, p_230372_2_, p_230372_3_, blockpos, p_230372_7_ + 2, p_230372_8_, -1, flag, p_230372_10_);
this.func_236753_a_(p_230372_1_, p_230372_2_, p_230372_3_, blockpos, p_230372_7_ + 3, p_230372_8_, 0, flag, p_230372_10_);
this.func_236753_a_(p_230372_1_, p_230372_2_, p_230372_3_, blockpos, p_230372_7_ + 2, p_230372_8_, 1, flag, p_230372_10_);
if (p_230372_2_.nextBoolean()) {
this.func_236753_a_(p_230372_1_, p_230372_2_, p_230372_3_, blockpos, p_230372_7_, p_230372_8_, 2, flag, p_230372_10_);
}
} else {
this.func_236753_a_(p_230372_1_, p_230372_2_, p_230372_3_, blockpos, p_230372_7_ + 2, p_230372_8_, -1, flag, p_230372_10_);
this.func_236753_a_(p_230372_1_, p_230372_2_, p_230372_3_, blockpos, p_230372_7_ + 1, p_230372_8_, 0, flag, p_230372_10_);
}
}
public int func_230374_a_(Random p_230374_1_, int p_230374_2_, BaseTreeFeatureConfig p_230374_3_) {
return 4;
}
protected boolean func_230375_b_(Random p_230375_1_, int p_230375_2_, int p_230375_3_, int p_230375_4_, int p_230375_5_, boolean p_230375_6_) {
return p_230375_3_ != 0 || !p_230375_6_ || p_230375_2_ != -p_230375_5_ && p_230375_2_ < p_230375_5_ || p_230375_4_ != -p_230375_5_ && p_230375_4_ < p_230375_5_ ? super.func_230375_b_(p_230375_1_, p_230375_2_, p_230375_3_, p_230375_4_, p_230375_5_, p_230375_6_) : true;
}
protected boolean func_230373_a_(Random p_230373_1_, int p_230373_2_, int p_230373_3_, int p_230373_4_, int p_230373_5_, boolean p_230373_6_) {
if (p_230373_3_ == -1 && !p_230373_6_) {
return p_230373_2_ == p_230373_5_ && p_230373_4_ == p_230373_5_;
} else if (p_230373_3_ == 1) {
return p_230373_2_ + p_230373_4_ > p_230373_5_ * 2 - 2;
} else {
return false;
}
}
}
| 53.262295 | 288 | 0.750385 |
fb0abf42f70162d765782298d9604df3223be87f | 2,150 | package com.thebluealliance.androidclient.renderers;
import android.support.annotation.IntDef;
import com.thebluealliance.androidclient.datafeed.APICache;
import com.thebluealliance.androidclient.listitems.CardedAwardListElement;
import com.thebluealliance.androidclient.listitems.ListElement;
import com.thebluealliance.androidclient.models.Award;
import com.thebluealliance.androidclient.models.Team;
import com.thebluealliance.androidclient.types.ModelType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Map;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class AwardRenderer implements ModelRenderer<Award, AwardRenderer.RenderArgs> {
@Retention(RetentionPolicy.SOURCE)
@IntDef({RENDER_CARDED})
public @interface RenderType{}
public static final int RENDER_CARDED = 0;
private APICache mDatafeed;
@Inject
public AwardRenderer(APICache datafeed) {
mDatafeed = datafeed;
}
@Override
public @Nullable ListElement renderFromKey(String key, ModelType type, RenderArgs args) {
return null;
}
@Override
public @Nullable ListElement renderFromModel(Award award, RenderArgs args) {
switch (args.renderType) {
case RENDER_CARDED:
return new CardedAwardListElement(
mDatafeed,
award.getName(),
award.getEventKey(),
award.getRecipientList(),
args.teams,
args.selectedTeamKey);
}
return null;
}
public static class RenderArgs {
public final @RenderType int renderType;
public final Map<String, Team> teams;
public final String selectedTeamKey;
/**
* Constructor to render carded element
*/
public RenderArgs(Map<String, Team> teams, String selectedTeamKey) {
renderType = RENDER_CARDED;
this.teams = teams;
this.selectedTeamKey = selectedTeamKey;
}
}
}
| 30.714286 | 93 | 0.677209 |
f1d3957287ce479e1ec3fb8548aa6722b5a43686 | 362 | package io.straas.android.sdk.demo.common;
import io.straas.android.sdk.authentication.identity.Identity;
public class MemberIdentity {
/**
* Represents a user known by Straas server
* See <a href="https://github.com/Straas/Straas-android-sdk-sample/wiki/User-Identity">User-Identity</a>
*/
public static Identity ME = Identity.GUEST;
}
| 30.166667 | 109 | 0.723757 |
c36d96c26cc79d0275707d83c69f6340a2ad900a | 395 | package com.oracle.oci.eclipse.ui.explorer.database.validate;
import org.eclipse.swt.widgets.Text;
public class PasswordInputValidator extends ControlValidator<Text, String> {
public PasswordInputValidator(InputValidator<String> inputValidator) {
super(inputValidator);
}
@Override
protected String getInput(Text control) {
return control.getText();
}
}
| 23.235294 | 76 | 0.736709 |
d0622bb58e91aab822db79e9bb64b378c7cd1a0d | 1,129 | package com.study.easy.one.MinStack;
import java.util.Stack;
//剑指 Offer 30. 包含min函数的栈
//定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
//
//示例:
//MinStack minStack = new MinStack();
//minStack.push(-2);
//minStack.push(0);
//minStack.push(-3);
//minStack.min(); --> 返回 -3.
//minStack.pop();
//minStack.top(); --> 返回 0.
//minStack.min(); --> 返回 -2.
//
//链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/
class MinStack {
private final Stack<Integer> stackA;
private final Stack<Integer> stackB;
/**
* initialize your data structure here.
*/
public MinStack() {
stackA = new Stack<>();
stackB = new Stack<>();
}
public void push(int x) {
stackA.push(x);
if (stackB.isEmpty() || stackB.peek() >= x) {
stackB.push(x);
}
}
public void pop() {
int value = stackA.pop();
if (value == stackB.peek()) {
stackB.pop();
}
}
public int top() {
return stackA.peek();
}
public int min() {
return stackB.peek();
}
} | 21.301887 | 76 | 0.554473 |
7456d787b37b4685930d2b05007ab7de0aeec68c | 4,498 | package org.firstinspires.ftc.teamcode20.Frank;
import com.qualcomm.hardware.rev.Rev2mDistanceSensor;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit;
import org.firstinspires.ftc.teamcode20.BaseAuto;
@Disabled
public class BrickGrabTest extends BaseAuto {
Rev2mDistanceSensor left,right;
ElapsedTime t;
double vr, leftDist, rightDist, vt, v,threshold;
boolean[] rB = {true};
boolean[] dpadUP = {true}, dpadDOWN = {true}, dpadLEFT = {true}, dpadRIGHT = {true};
//double 操;
//String logName = "FaceWallLog"+System.currentTimeMillis()+".csv";
@Override
public void runOpMode() throws InterruptedException {
//initLogger(logName);
//writeLogHeader("time,LF_count,LB_count,RF_count,RB_count,LF_power,LB_power,RF_power,RB_power,front_UltS,left_UltS,right_UltS,front_left_REV,front_right_REV");
initDrivetrain();
t = new ElapsedTime();
left = hardwareMap.get(Rev2mDistanceSensor.class,"left");
right = hardwareMap.get(Rev2mDistanceSensor.class,"right");
initIMU();
vr = 0.1;
v = 0.15;
threshold=8;
waitForStart();
while(opModeIsActive()){
if(zheng(this.gamepad1.dpad_up,dpadUP)){
vr +=0.02;
}
if(zheng(this.gamepad1.dpad_down,dpadDOWN)){
vr -=0.02;
}
if(zheng(this.gamepad1.dpad_left,dpadLEFT)){
v-=0.02;
}
if(zheng(this.gamepad1.dpad_right,dpadRIGHT)){
v+=0.02;
}
telemetry.addData("Left", "%.2f", left.getDistance(DistanceUnit.INCH));
telemetry.addData("Right","%.2f",right.getDistance(DistanceUnit.INCH));
telemetry.addData("Rotational speed","%.2f", vr);
telemetry.addData("Translational speed", "%.2f",vt);
telemetry.addData("Forward speed", "%.2f",v);
telemetry.addData("WAITING FOR ACTIONS",0);
if(zheng(this.gamepad1.right_bumper, rB)) {
leftDist = left.getDistance(DistanceUnit.INCH);
rightDist = right.getDistance(DistanceUnit.INCH);
/*
while((leftDist > 20 && rightDist > 20) || (Math.abs(leftDist-rightDist) > 6)){
leftDist = left.getDistance(DistanceUnit.INCH);
rightDist = right.getDistance(DistanceUnit.INCH);
telemetry.addData("Left", "%.2f", left.getDistance(DistanceUnit.INCH));
telemetry.addData("Right","%.2f",right.getDistance(DistanceUnit.INCH));
telemetry.update();
//好活(-v,-v,-v,-v); 向前(屁股向后)
好活(v,v,v,v);
}
*/
boolean flag = false;
while (!flag){
leftDist = left.getDistance(DistanceUnit.INCH);
rightDist = right.getDistance(DistanceUnit.INCH);
if(leftDist <threshold&& rightDist <threshold){
setAllDrivePower(0);
flag = true;
}
else if(leftDist <threshold){
setAllDrivePower(0.2, -0.2, 0.2, -0.2);
}
else if(rightDist <threshold){
setAllDrivePower(-0.2, 0.2, -0.2, 0.2);
}
else{
//好活(v,v,v,v);
vt = ((leftDist + rightDist)/2) / 10 * vr + 0.08;
if(near(leftDist, rightDist,8)){
if (leftDist < rightDist) setAllDrivePower(v/2 + vr - vt, v/2 + vr + vt, -v/2 + vr - vt, -v/2 + vr + vt);
else setAllDrivePower(v/2 -vr + vt, v/2 -vr - vt, -v/2 -vr + vt, -v/2 -vr - vt);
}
else if (leftDist < rightDist){
setAllDrivePower(LF.getPower() +0.05, LB.getPower()-0.05, RF.getPower()+0.05, RB.getPower()-0.05);
}
//else 开倒车(LF.getPower() -0.05, LB.getPower()+0.05, RF.getPower()-0.05, RB.getPower()+0.05);
wait(80);
}
}
//开倒车(0);
}
telemetry.update();
}
}
}
| 42.037383 | 168 | 0.5249 |
cd6f44ae68801fb7691f134c2c054a20ebaf687d | 5,246 | package com.example.aliahmed.myapplication;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.chad.library.adapter.base.BaseQuickAdapter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* A simple {@link Fragment} subclass.
*/
public class AutoScrollFragment extends Fragment {
@BindView(R.id.rec_scroll_stock)
RecyclerView rvTickerList;
List<StockListModel> stockListModels = new ArrayList<>();
private ScrollStockAdapter scrollStockAdapter;
StockListModel model = new StockListModel();
int scrollCount = 0;
public AutoScrollFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_auto_scroll, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onResume() {
super.onResume();
//Dummy Value
model.setAskerName("Ali Ahmed");
model.setBidderName("Tanzim");
model.setId("abc");
model.setType("BUY");
model.setIsSyncedWithServer(true);
model.setTransactionTime("12/12/2016");
model.setShortName("ABC");
model.setShareQuantity(10);
//add to the list
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
stockListModels.add(model);
scrollStockAdapter = new ScrollStockAdapter(stockListModels);
rvTickerList.setAdapter(scrollStockAdapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()) {
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
try {
LinearSmoothScroller smoothScroller = new LinearSmoothScroller(Objects.requireNonNull(getContext())) {
private static final float SPEED = 3500f;// Change this value (default=25f)
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return SPEED / displayMetrics.densityDpi;
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
} catch (Exception e) {
e.printStackTrace();
}
}
};
// LinearLayoutManager layoutManager = new LinearLayoutManager(this);
autoScrollAnother();
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
rvTickerList.setLayoutManager(layoutManager);
rvTickerList.setHasFixedSize(true);
rvTickerList.setItemViewCacheSize(1000);
rvTickerList.setDrawingCacheEnabled(true);
rvTickerList.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
rvTickerList.setAdapter(scrollStockAdapter);
scrollStockAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
Toast.makeText(getContext(), "Item clicked", Toast.LENGTH_LONG).show();
}
});
}
/**
* Autoscroll detected from here, where counter, time and runnable is declared.
*/
public void autoScrollAnother() {
scrollCount = 0;
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
rvTickerList.smoothScrollToPosition((scrollCount++));
if (scrollCount == scrollStockAdapter.getData().size() - 4) {
stockListModels.addAll(stockListModels);
scrollStockAdapter.notifyDataSetChanged();
}
handler.postDelayed(this, 2000);
}
};
handler.postDelayed(runnable, 2000);
}
}
| 34.064935 | 122 | 0.646778 |
8857bf95dedcecf609777d9321cabe7b89929cb2 | 4,322 | package pro.taskana.rest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.util.MultiValueMap;
import pro.taskana.BaseQuery;
import pro.taskana.exceptions.InvalidArgumentException;
import pro.taskana.rest.resource.PagedResources.PageMetadata;
/** Abstract superclass for taskana REST controller with pageable resources. */
public abstract class AbstractPagingController {
private static final String PAGING_PAGE = "page";
private static final String PAGING_PAGE_SIZE = "page-size";
protected String[] extractCommaSeparatedFields(List<String> list) {
List<String> values = new ArrayList<>();
if (list != null) {
list.forEach(item -> values.addAll(Arrays.asList(item.split(","))));
}
return values.toArray(new String[0]);
}
protected void validateNoInvalidParameterIsLeft(MultiValueMap<String, String> params)
throws InvalidArgumentException {
if (!params.isEmpty()) {
throw new InvalidArgumentException("Invalid parameter specified: " + params.keySet());
}
}
protected PageMetadata getPageMetadata(
MultiValueMap<String, String> params, BaseQuery<?, ?> query) throws InvalidArgumentException {
PageMetadata pageMetadata = null;
if (hasPagingInformationInParams(params)) {
// paging
long totalElements = query.count();
pageMetadata = initPageMetadata(params, totalElements);
validateNoInvalidParameterIsLeft(params);
} else {
// not paging
validateNoInvalidParameterIsLeft(params);
}
return pageMetadata;
}
protected <T> List<T> getQueryList(BaseQuery<T, ?> query, PageMetadata pageMetadata) {
List<T> resultList;
if (pageMetadata != null) {
resultList = query.listPage((int) pageMetadata.getNumber(), (int) pageMetadata.getSize());
} else {
resultList = query.list();
}
return resultList;
}
protected PageMetadata initPageMetadata(MultiValueMap<String, String> param, long totalElements)
throws InvalidArgumentException {
long pageSize = getPageSize(param);
long page = getPage(param);
PageMetadata pageMetadata =
new PageMetadata(pageSize, page, totalElements >= 0 ? totalElements : Integer.MAX_VALUE);
if (pageMetadata.getNumber() > pageMetadata.getTotalPages()) {
// unfortunately no setter for number
pageMetadata = new PageMetadata(pageSize, pageMetadata.getTotalPages(), totalElements);
}
return pageMetadata;
}
// This method is deprecated please remove it after updating taskana-simple-history reference to
// it.
// TODO: @Deprecated
protected PageMetadata initPageMetadata(
String pagesizeParam, String pageParam, long totalElements) throws InvalidArgumentException {
long pageSize;
long page;
try {
pageSize = Long.parseLong(pagesizeParam);
page = Long.parseLong(pageParam);
} catch (NumberFormatException e) {
throw new InvalidArgumentException(
"page and pageSize must be a integer value.", e.getCause());
}
PageMetadata pageMetadata = new PageMetadata(pageSize, page, totalElements);
if (pageMetadata.getNumber() > pageMetadata.getTotalPages()) {
// unfortunately no setter for number
pageMetadata = new PageMetadata(pageSize, pageMetadata.getTotalPages(), totalElements);
}
return pageMetadata;
}
private boolean hasPagingInformationInParams(MultiValueMap<String, String> params) {
return params.getFirst(PAGING_PAGE) != null;
}
private long getPage(MultiValueMap<String, String> params) throws InvalidArgumentException {
String param = params.getFirst(PAGING_PAGE);
params.remove(PAGING_PAGE);
try {
return Long.parseLong(param != null ? param : "1");
} catch (NumberFormatException e) {
throw new InvalidArgumentException("page must be a integer value.", e.getCause());
}
}
private long getPageSize(MultiValueMap<String, String> params) throws InvalidArgumentException {
String param = params.getFirst(PAGING_PAGE_SIZE);
params.remove(PAGING_PAGE_SIZE);
try {
return param != null ? Long.parseLong(param) : Integer.MAX_VALUE;
} catch (NumberFormatException e) {
throw new InvalidArgumentException("page-size must be a integer value.", e.getCause());
}
}
}
| 36.627119 | 100 | 0.718417 |
a74c01b95594659ff7f9ebc20d73000f3b512d79 | 2,307 | package me.ericandjacob.util;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;
public class CryptoUtils {
public static byte[] generateSalt(int length) {
Random random = new SecureRandom();
byte[] salt = new byte[length];
random.nextBytes(salt);
return salt;
}
public static boolean isEqual(byte[] b1, byte[] b2) {
if (b1.length != b2.length) {
return false;
}
for (int i = 0; i < b1.length; ++i) {
if ((b1[i] ^ b2[i]) != 0) {
return false;
}
}
return true;
}
public static void clearCharArray(char[] arr) {
for (int i = 0; i < arr.length; ++i) {
arr[i] = 0x0;
}
}
public static void clearByteArray(byte[] arr) {
for (int i = 0; i < arr.length; ++i) {
arr[i] = 0x0;
}
}
// http://stackoverflow.com/questions/5513144/converting-char-to-byte#9670279
public static byte[] toBytes(char[] chars) {
CharBuffer charBuffer = CharBuffer.wrap(chars);
ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(charBuffer);
byte[] bytes =
Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit());
Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data
Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
return bytes;
}
public static char[] toChars(byte[] bytes) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
CharBuffer charBuffer = StandardCharsets.UTF_8.decode(byteBuffer);
char[] chars =
Arrays.copyOfRange(charBuffer.array(), charBuffer.position(), charBuffer.limit());
Arrays.fill(byteBuffer.array(), (byte) 0);
Arrays.fill(charBuffer.array(), '\u0000');
return chars;
}
public static byte[] generateHash(String algo, byte[]... bytes) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance(algo);
for (int i = 0; i < bytes.length; ++i) {
digest.update(bytes[i]);
}
return digest.digest();
}
}
| 30.355263 | 100 | 0.641526 |
492c8d361ab087b33e8158e0daaa1340cdd82d0f | 2,698 | /*
* 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 opennlp.tools.lang.spanish;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import opennlp.maxent.io.SuffixSensitiveGISModelReader;
import opennlp.tools.namefind.NameFinderEventStream;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.util.Span;
/**
* Class which identifies multi-token chunk which are treated as a single token in for POS-tagging.
*/
public class TokenChunker {
private NameFinderME nameFinder;
public TokenChunker(String modelName) throws IOException {
nameFinder = new NameFinderME(new SuffixSensitiveGISModelReader(
new File(modelName)).getModel());
}
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.err.println("Usage: java opennlp.tools.spanish.TokenChunker model < tokenized_sentences");
System.exit(1);
}
TokenChunker chunker = new TokenChunker(args[0]);
java.io.BufferedReader inReader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in,"ISO-8859-1"));
PrintStream out = new PrintStream(System.out,true,"ISO-8859-1");
for (String line = inReader.readLine(); line != null; line = inReader.readLine()) {
if (line.equals("")) {
out.println();
}
else {
String[] tokens = line.split(" ");
Span[] spans = chunker.nameFinder.find(tokens);
String[] outcomes = NameFinderEventStream.generateOutcomes(spans, null, tokens.length);
//System.err.println(java.util.Arrays.asList(chunks));
for (int ci=0,cn=outcomes.length;ci<cn;ci++) {
if (ci == 0) {
out.print(tokens[ci]);
}
else if (outcomes[ci].equals(NameFinderME.CONTINUE)) {
out.print("_"+tokens[ci]);
}
else {
out.print(" "+tokens[ci]);
}
}
out.println();
}
}
}
}
| 36.459459 | 120 | 0.685322 |
cd5e23030153a92781ac7327cf17ccf631229398 | 1,487 | /*
*
* Copyright 2020 HuiFer All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.github.huifer.view.redis.model.info;
public class RedisCliInfoKeyspace {
private String dbIndex;
private KeyInfo keyInfo;
public String getDbIndex() {
return dbIndex;
}
public void setDbIndex(String dbIndex) {
this.dbIndex = dbIndex;
}
public KeyInfo getKeyInfo() {
return keyInfo;
}
public void setKeyInfo(KeyInfo keyInfo) {
this.keyInfo = keyInfo;
}
public static class KeyInfo {
private String keys;
private String expires;
private String avgTtl;
public String getKeys() {
return keys;
}
public void setKeys(String keys) {
this.keys = keys;
}
public String getExpires() {
return expires;
}
public void setExpires(String expires) {
this.expires = expires;
}
public String getAvgTtl() {
return avgTtl;
}
public void setAvgTtl(String avgTtl) {
this.avgTtl = avgTtl;
}
}
}
| 19.826667 | 75 | 0.707465 |
93e41f79d8b05376da3f704a28a191aa5bcb56e1 | 22,275 | /*
* Copyright 2019 dmfs GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dmfs.tasks.widget;
import android.animation.LayoutTransition;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.graphics.Rect;
import android.net.Uri;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import com.jmedeisis.draglinearlayout.DragLinearLayout;
import com.jmedeisis.draglinearlayout.DragLinearLayout.OnViewSwapListener;
import org.dmfs.android.bolts.color.colors.AttributeColor;
import org.dmfs.jems.function.Function;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.optional.Optional;
import org.dmfs.jems.optional.decorators.Mapped;
import org.dmfs.jems.optional.elementary.Present;
import org.dmfs.jems.procedure.Procedure;
import org.dmfs.jems.procedure.composite.ForEach;
import org.dmfs.tasks.R;
import org.dmfs.tasks.linkify.ActionModeLinkify;
import org.dmfs.tasks.model.ContentSet;
import org.dmfs.tasks.model.DescriptionItem;
import org.dmfs.tasks.model.FieldDescriptor;
import org.dmfs.tasks.model.adapters.DescriptionFieldAdapter;
import org.dmfs.tasks.model.layout.LayoutOptions;
import java.util.List;
import androidx.core.view.ViewCompat;
import static org.dmfs.jems.optional.elementary.Absent.absent;
/**
* View widget for descriptions with checklists.
*
* @author Marten Gajda <marten@dmfs.org>
*/
public class DescriptionFieldView extends AbstractFieldView implements OnCheckedChangeListener, OnViewSwapListener, OnClickListener, ActionModeLinkify.ActionModeListener
{
private DescriptionFieldAdapter mAdapter;
private DragLinearLayout mContainer;
private List<DescriptionItem> mCurrentValue;
private boolean mBuilding = false;
private LayoutInflater mInflater;
private InputMethodManager mImm;
private View mActionView;
public DescriptionFieldView(Context context)
{
super(context);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mImm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
}
public DescriptionFieldView(Context context, AttributeSet attrs)
{
super(context, attrs);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mImm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
}
public DescriptionFieldView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mImm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
}
@Override
protected void onFinishInflate()
{
super.onFinishInflate();
mContainer = findViewById(R.id.checklist);
mContainer.setOnViewSwapListener(this);
mContainer.findViewById(R.id.add_item).setOnClickListener(this);
mActionView = mInflater.inflate(R.layout.description_field_view_element_actions, mContainer, false);
}
@Override
public void setFieldDescription(FieldDescriptor descriptor, LayoutOptions layoutOptions)
{
super.setFieldDescription(descriptor, layoutOptions);
mAdapter = (DescriptionFieldAdapter) descriptor.getFieldAdapter();
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (mCurrentValue == null || mBuilding)
{
return;
}
int childCount = mContainer.getChildCount();
for (int i = 0; i < childCount; ++i)
{
if (mContainer.getChildAt(i).findViewById(android.R.id.checkbox) == buttonView)
{
mCurrentValue.get(i).checked = isChecked;
((TextView) mContainer.getChildAt(i).findViewById(android.R.id.title)).setTextAppearance(getContext(),
isChecked ? R.style.checklist_checked_item_text : R.style.dark_text);
if (mValues != null)
{
mAdapter.validateAndSet(mValues, mCurrentValue);
}
return;
}
}
}
@Override
public void updateValues()
{
mAdapter.validateAndSet(mValues, mCurrentValue);
}
@Override
public void onContentLoaded(ContentSet contentSet)
{
super.onContentLoaded(contentSet);
}
@Override
public void onContentChanged(ContentSet contentSet)
{
if (mValues != null)
{
List<DescriptionItem> newValue = mAdapter.get(mValues);
if (newValue != null && !newValue.equals(mCurrentValue)) // don't trigger unnecessary updates
{
updateCheckList(newValue);
mCurrentValue = newValue;
}
}
}
private void updateCheckList(List<DescriptionItem> list)
{
setVisibility(VISIBLE);
mBuilding = true;
int count = 0;
for (final DescriptionItem item : list)
{
View itemView = mContainer.getChildAt(count);
if (itemView == null || itemView.getId() != R.id.checklist_element)
{
itemView = createItemView();
mContainer.addDragView(itemView, itemView.findViewById(R.id.drag_handle), mContainer.getChildCount() - 1);
}
bindItemView(itemView, item);
++count;
}
while (mContainer.getChildCount() > count + 1)
{
View view = mContainer.getChildAt(count);
mContainer.removeDragView(view);
}
mBuilding = false;
}
@Override
public void onSwap(View view1, int position1, View view2, int position2)
{
if (mCurrentValue != null)
{
DescriptionItem item1 = mCurrentValue.get(position1);
DescriptionItem item2 = mCurrentValue.get(position2);
// swap items in the list
mCurrentValue.set(position2, item1);
mCurrentValue.set(position1, item2);
}
}
/**
* Inflates a new check list element view.
*
* @return
*/
private View createItemView()
{
View item = mInflater.inflate(R.layout.description_field_view_element, mContainer, false);
// disable transition animations
LayoutTransition transition = ((ViewGroup) item).getLayoutTransition();
transition.disableTransitionType(LayoutTransition.CHANGE_APPEARING);
transition.disableTransitionType(LayoutTransition.CHANGE_DISAPPEARING);
transition.disableTransitionType(LayoutTransition.CHANGING);
transition.disableTransitionType(LayoutTransition.APPEARING);
transition.disableTransitionType(LayoutTransition.DISAPPEARING);
((TextView) item.findViewById(android.R.id.title)).setMovementMethod(LinkMovementMethod.getInstance());
return item;
}
private void bindItemView(final View itemView, final DescriptionItem item)
{
// set the checkbox status
CheckBox checkbox = itemView.findViewById(android.R.id.checkbox);
// make sure we don't receive our own updates
checkbox.setOnCheckedChangeListener(null);
checkbox.setChecked(item.checked && item.checkbox);
checkbox.jumpDrawablesToCurrentState();
checkbox.setOnCheckedChangeListener(DescriptionFieldView.this);
checkbox.setVisibility(item.checkbox ? VISIBLE : GONE);
// configure the title
final EditText text = itemView.findViewById(android.R.id.title);
text.setTextAppearance(getContext(), item.checked && item.checkbox ? R.style.checklist_checked_item_text : R.style.dark_text);
if (text.getTag() != null)
{
text.removeTextChangedListener((TextWatcher) text.getTag());
}
text.setText(item.text);
ColorStateList colorStateList = new ColorStateList(
new int[][] { new int[] { android.R.attr.state_focused }, new int[] { -android.R.attr.state_focused } },
new int[] { new AttributeColor(getContext(), R.attr.colorPrimary).argb(), 0 });
ViewCompat.setBackgroundTintList(text, colorStateList);
text.setOnFocusChangeListener((v, hasFocus) -> {
String newText = text.getText().toString();
if (!hasFocus && !newText.equals(item.text))
{
item.text = newText;
}
if (hasFocus)
{
addActionView(itemView, item);
setupActionView(item);
}
else
{
ActionModeLinkify.linkify(text, DescriptionFieldView.this);
((ViewGroup) itemView.findViewById(R.id.action_bar)).removeAllViews();
}
});
text.setOnKeyListener((view, i, keyEvent) -> {
// intercept DEL key so we can join lines
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyEvent.getKeyCode() == KeyEvent.KEYCODE_DEL && text.getSelectionStart() == 0)
{
int pos = mContainer.indexOfChild(itemView);
if (pos > 0)
{
EditText previousEditText = mContainer.getChildAt(pos - 1).findViewById(android.R.id.title);
String previousText = previousEditText.getText().toString();
int selectorPos = previousText.length();
String newText = previousText + text.getText().toString();
// concat content of this item to the previous one
previousEditText.setText(newText);
previousEditText.requestFocus();
mCurrentValue.get(pos - 1).text = newText;
mCurrentValue.remove(item);
mContainer.removeDragView(itemView);
mAdapter.validateAndSet(mValues, mCurrentValue);
previousEditText.setSelection(Math.min(selectorPos, previousEditText.getText().length()));
return true;
}
}
if (item.checkbox && keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)
{
// we own this event
return true;
}
if (item.checkbox && keyEvent.getAction() == KeyEvent.ACTION_UP && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)
{
if (text.getText().length() == 0)
{
// convert to unchecked text
item.checkbox = false;
new Animated(checkbox, v -> (ViewGroup) v.getParent()).process(c -> c.setVisibility(View.GONE));
text.requestFocus();
text.setSingleLine(false);
return true;
}
// split current
int sel = text.getSelectionStart();
String newText = text.getText().toString().substring(sel);
item.text = text.getText().toString().substring(0, sel);
text.setText(item.text);
text.clearFocus();
// create new item with new test
int pos = mContainer.indexOfChild(itemView);
insertItem(item.checkbox, pos + 1, newText);
EditText editText = ((EditText) mContainer.getChildAt(pos + 1).findViewById(android.R.id.title));
editText.setSelection(0);
editText.setSingleLine(true);
editText.setMaxLines(Integer.MAX_VALUE);
editText.setHorizontallyScrolling(false);
return true;
}
return false;
});
text.setSingleLine(item.checkbox);
text.setMaxLines(Integer.MAX_VALUE);
text.setHorizontallyScrolling(false);
TextWatcher watcher = new TextWatcher()
{
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
@Override
public void afterTextChanged(Editable editable)
{
item.text = editable.toString();
}
};
text.setTag(watcher);
ActionModeLinkify.linkify(text, this);
text.addTextChangedListener(watcher);
}
@Override
public boolean prepareMenu(TextView view, Uri uri, Menu menu)
{
Optional<String> optAction = actionForUri(uri);
new ForEach<>(new Joined<>(
new Mapped<>(action -> getContext().getPackageManager()
.queryIntentActivities(new Intent(action).setData(uri), PackageManager.GET_RESOLVED_FILTER | PackageManager.GET_META_DATA),
optAction)))
.process(
resolveInfo -> menu.add(titleForAction(optAction.value()))
.setIcon(resolveInfo.loadIcon(getContext().getPackageManager()))
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
);
return menu.size() > 0;
}
@Override
public boolean onClick(TextView view, Uri uri, MenuItem item)
{
new ForEach<>(actionForUri(uri)).process(
action -> getContext().startActivity(new Intent(action).setData(uri)));
return false;
}
private static Optional<String> actionForUri(Uri uri)
{
if ("http".equals(uri.getScheme()) || "https".equals(uri.getScheme()))
{
return new Present<>(Intent.ACTION_VIEW);
}
else if ("mailto".equals(uri.getScheme()))
{
return new Present<>(Intent.ACTION_SENDTO);
}
else if ("tel".equals(uri.getScheme()))
{
return new Present<>(Intent.ACTION_DIAL);
}
return absent();
}
private static int titleForAction(String action)
{
switch (action)
{
case Intent.ACTION_DIAL:
return R.string.opentasks_actionmode_call;
case Intent.ACTION_SENDTO:
return R.string.opentasks_actionmode_mail_to;
case Intent.ACTION_VIEW:
return R.string.opentasks_actionmode_open;
}
return -1;
}
/**
* Insert an empty item at the given position. Nothing will be inserted if the check list already contains an empty item at the given position. The new (or
* exiting) emtpy item will be focused and the keyboard will be opened.
*
* @param withCheckBox
* @param pos
*/
private void insertItem(boolean withCheckBox, int pos, String initialText)
{
if (mCurrentValue.size() > pos && mCurrentValue.get(pos).text.length() == 0)
{
// there already is an empty item at this pos focus it and return
View view = mContainer.getChildAt(pos);
((EditText) view.findViewById(android.R.id.title)).setText(initialText);
focusTitle(view);
return;
}
mContainer.clearFocus();
// create a new empty item
DescriptionItem item = new DescriptionItem(withCheckBox, false, initialText);
mCurrentValue.add(pos, item);
View newItem = createItemView();
bindItemView(newItem, item);
// append it to the list
mContainer.addDragView(newItem, newItem.findViewById(R.id.drag_handle), pos);
focusTitle(newItem);
}
@Override
public void onClick(View v)
{
int id = v.getId();
if (id == R.id.add_item)
{
insertItem(!mCurrentValue.isEmpty(), mCurrentValue.size(), "");
}
}
/**
* Focus the title element of the given view and open the keyboard if necessary.
*
* @param view
*/
private void focusTitle(View view)
{
View titleView = view.findViewById(android.R.id.title);
if (titleView != null)
{
titleView.requestFocus();
mImm.showSoftInput(titleView, InputMethodManager.SHOW_IMPLICIT);
}
}
private void addActionView(View itemView, DescriptionItem item)
{
// attach the action view
((ViewGroup) itemView.findViewById(R.id.action_bar)).addView(mActionView);
mActionView.findViewById(R.id.delete).setOnClickListener((view -> {
mCurrentValue.remove(item);
mContainer.removeDragView(itemView);
mAdapter.validateAndSet(mValues, mCurrentValue);
}));
}
private void setupActionView(DescriptionItem item)
{
TextView toggleCheckableButton = mActionView.findViewById(R.id.toggle_checkable);
toggleCheckableButton.setText(item.checkbox ? R.string.opentasks_hide_tick_box : R.string.opentasks_show_tick_box);
toggleCheckableButton.setCompoundDrawablesWithIntrinsicBounds(item.checkbox ? R.drawable.ic_text_24px : R.drawable.ic_list_24px, 0, 0, 0);
toggleCheckableButton.setOnClickListener(button -> {
int idx = mCurrentValue.indexOf(item);
int origidx = idx;
mCurrentValue.remove(item);
if (!item.checkbox)
{
String[] lines = item.text.split("\n");
if (lines.length == 1)
{
DescriptionItem newItem = new DescriptionItem(true, item.checked, item.text);
mCurrentValue.add(idx, newItem);
new Animated(mContainer.getChildAt(origidx), v -> (ViewGroup) v).process(v -> bindItemView(v, newItem));
setupActionView(newItem);
}
else
{
for (String i : lines)
{
DescriptionItem newItem = new DescriptionItem(true, false, i);
mCurrentValue.add(idx, newItem);
if (idx == origidx)
{
new Animated(mContainer.getChildAt(origidx), v -> (ViewGroup) v).process(v -> bindItemView(v, newItem));
}
else
{
View itemView = createItemView();
bindItemView(itemView, newItem);
mContainer.addDragView(itemView, itemView.findViewById(R.id.drag_handle), idx);
}
idx += 1;
}
}
}
else
{
DescriptionItem newItem = new DescriptionItem(false, item.checked, item.text);
mCurrentValue.add(idx, newItem);
if (idx == 0 || mCurrentValue.get(idx - 1).checkbox)
{
new Animated(mContainer.getChildAt(idx), v -> (ViewGroup) v).process(v -> bindItemView(v, newItem));
}
setupActionView(newItem);
}
mAdapter.validateAndSet(mValues, mCurrentValue);
if (mCurrentValue.size() > 0)
{
setupActionView(mCurrentValue.get(Math.min(origidx, mCurrentValue.size() - 1)));
}
});
mActionView.postDelayed(
() -> mActionView.requestRectangleOnScreen(new Rect(0, 0, mActionView.getWidth(), mActionView.getHeight()), false), 1);
}
public static final class Animated implements Procedure<Procedure<? super View>>
{
private final View mView;
private final Function<View, ViewGroup> mViewGroupFunction;
public Animated(View view, Function<View, ViewGroup> viewGroupFunction)
{
mView = view;
mViewGroupFunction = viewGroupFunction;
}
@Override
public void process(Procedure<? super View> arg)
{
LayoutTransition transition = mViewGroupFunction.value(mView).getLayoutTransition();
transition.enableTransitionType(LayoutTransition.CHANGE_APPEARING);
transition.enableTransitionType(LayoutTransition.CHANGE_DISAPPEARING);
transition.enableTransitionType(LayoutTransition.CHANGING);
transition.enableTransitionType(LayoutTransition.APPEARING);
transition.enableTransitionType(LayoutTransition.DISAPPEARING);
arg.process(mView);
transition.disableTransitionType(LayoutTransition.CHANGE_APPEARING);
transition.disableTransitionType(LayoutTransition.CHANGE_DISAPPEARING);
transition.disableTransitionType(LayoutTransition.CHANGING);
transition.disableTransitionType(LayoutTransition.APPEARING);
transition.disableTransitionType(LayoutTransition.DISAPPEARING);
}
}
}
| 36.397059 | 169 | 0.617284 |
ecbb869571966ffc4821d456be1a270f7624bb15 | 1,607 | package com.quanyan.pedometer.newpedometer;
import com.lidroid.xutils.db.annotation.Column;
import com.lidroid.xutils.db.annotation.Id;
import com.lidroid.xutils.db.annotation.NoAutoIncrement;
import com.lidroid.xutils.db.annotation.Table;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created with Android Studio.
* Title:WalkDataThresholdGag
* Description:
* Copyright:Copyright (c) 2016
* Company:quanyan
* Author:赵晓坡
* Date:16/7/2
* Time:12:15
* Version 1.1.0
*/
@Table(name = "walkdata_daily")
public class WalkDataDaily implements Serializable {
/** @Fields serialVersionUID: */
private static final long serialVersionUID = 8818101589895754246L;
/**
* 步数
*/
@Column(column = "stepCount")
public long stepCount;
/**
* 里程数
*/
@Column(column = "distance")
public double distance;
/**
* 消耗的卡路里
*/
@Column(column = "calories")
public double calories;
/**
* 目标数
*/
@Column(column = "targetStepCount")
public long targetStepCount;
/**
* 保存数据的时间
*/
@Id
@NoAutoIncrement
@Column(column = "synTime")
public long synTime;
@Override
public String toString() {
return "WalkDataDaily{" +
"stepCount=" + stepCount +
", targetStepCount=" + targetStepCount +
", distance=" + distance +
", calories=" + calories +
", synTime=" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(synTime)) +
'}';
}
}
| 22.319444 | 102 | 0.61481 |
af40a03d3a44f7d8f9e2ba79174cc5897b12f4a2 | 51 | package testDirectory.chapter33.sourceCode33.java;
| 25.5 | 50 | 0.882353 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.