blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
3b1342e6e4d022b725e2324fdf3701990b7e9dc8 | Java | 4010hrms/hrms | /src/main/java/com/king/hrmsdev/mapper/DepartmentMapper.java | UTF-8 | 806 | 1.828125 | 2 | [] | no_license | package com.king.hrmsdev.mapper;
import com.king.hrmsdev.entity.Department;
import com.king.hrmsdev.pojo.Peoplecountindepart;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @Auther:SnakeKing
* @Date: 2019-09-12
* @Description: com.king.hrmsdev.mapper
* @version:1.0
*/
@Mapper
public interface DepartmentMapper {
List<Department> findall();
List<Department> findallused();
Department findByid(int id);
List<Department> findBycondition(Department department);
int dismissdepart(int id);
int recoverdepart(int id);
int updatedepartment(Department department);
int adddepartment(Department department);
int updateemployeecount(Peoplecountindepart peoplecountindepart);
List<Peoplecountindepart> getpeoplecountindepart();
}
| true |
9cd5d092f75f258e3502e6710fba4c6f8f21d6f4 | Java | wuhaoyang99/1708Dwhy | /src/test/java/com/bawei/day/DateUtils.java | UTF-8 | 2,797 | 2.828125 | 3 | [] | no_license | package com.bawei.day;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
/**
* LocalDate ���� LocalTime ʱ�� LocalDateTime ���ں�ʱ��
*
*/
public class DateUtils {
/**
*/
public static String getDateByMonthInit(String date) {
// ÿ�µ����һ��
LocalDate monthOfLastDate = LocalDate.parse(date).with(TemporalAdjusters.firstDayOfMonth());
return monthOfLastDate.toString() + " "
+ LocalDateTime.MIN.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
}
/**
* ���ij�����ʱ�� 2017-10-15 23:59:59
* @param date
* @return
*/
public static String getEndOfDay(String date) {
// ÿ�µ����һ��
LocalDate monthOfLastDate = LocalDate.parse(date).with(TemporalAdjusters.lastDayOfMonth());
return monthOfLastDate.toString() + " "
+ LocalDateTime.MAX.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
}
/**
* ���ݴ���IJ�����ȡ����������ĩ���ڣ��������������Ϊ��2019-09-19 19:29:39�������ء�2019-09-30
* 23:59:59����ע���´���С�Լ����ꡣ
*
* @return
*/
public static String getDateByMonthLast(String date) {
// ÿ�µ����һ��
LocalDate monthOfLastDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
.with(TemporalAdjusters.lastDayOfMonth());
return monthOfLastDate.toString() + " "
+ LocalDateTime.MAX.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
}
/**
* ���ݴ�������ڻ�ȡ����yyyy-MM-dd
*
* @param date
* @return
*/
public static long getYears(String date) {// 1990-12-11
// ��ȡ��ǰϵͳʱ��
LocalDate today = LocalDate.now();// 2019-12-11
LocalDate playerDate = LocalDate.parse(date);// yyyy-MM-dd
long years = ChronoUnit.YEARS.between(playerDate, today);
return years;
}
/**
* ���ȥ����������ȥ������(��δ����������컹ʣ������)
*/
public static long getDaysByDeparted(String departed) {
// ��ȡ��ǰϵͳʱ��
LocalDate today = LocalDate.now();
//
LocalDate birthDate = LocalDate.parse(departed);
System.out.println("相差" + ChronoUnit.DAYS.between(birthDate, today));
System.out.println("相差" + Math.abs(ChronoUnit.DAYS.between(birthDate, today)));
long days = Math.abs(ChronoUnit.DAYS.between(birthDate, today));
return days;
}
}
| true |
78ca2e4e64469d4a6ea5761a426210b854d68a14 | Java | twilightDF/java-works | /demo-1/src/main/java/com/twilight/demo2/TestPloy.java | GB18030 | 1,315 | 4.0625 | 4 | [] | no_license | package com.twilight.demo2;
/**
* Զ̬
* @author ŷ
*ɶ̬
*1.Ҫм̳
*2.Ҫд
*3.øõĶ
*/
public class TestPloy {
public static void main(String[] args) {
Animal c = new Cat();
//Cat c = new Cat();ʲôͬ
c.shout();
animalCry(c);
a();
//ǰʲôͬ
animalCry(new Dog());//animalΪ࣬ڴĵĶɶ̬
//ת
/*
* 磺Animal c = new Cat();
* cCat ʵanimal
* Զת
* ʱc Լķ c.sleep
* ʱҪǿת
*/
Cat c2 = (Cat)c;
c2.sleep();
}
//hook!
static void animalCry(Animal a) {
a.shout();
}
static void a() {
System.out.println("dd");
}
}
class Animal{
public void shout(){
System.out.println("һ~~");
}
}
class Cat extends Animal{
public void shout() {
System.out.println("");
}
public void sleep() {
System.out.println("è˯");
}
}
class Dog extends Animal{
public void shout() {
System.out.println("");
}
} | true |
98038b1e3d1a277c41726ad2c215f493a2d13af6 | Java | azizsault1/CotacaoEscolar | /src/test/java/cotacaoEscolar/repository/json/JsonRepositoryTest.java | UTF-8 | 1,466 | 2.3125 | 2 | [] | no_license | package cotacaoEscolar.repository.json;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.security.GeneralSecurityException;
import org.junit.Test;
import cotacaoEscolar.repository.DescricaoMaterialEscolarRepository;
import cotacaoEscolar.repository.EscolaRepository;
import cotacaoEscolar.repository.EstabelecimentoRepository;
import cotacaoEscolar.repository.ListaMaterialRepository;
public class JsonRepositoryTest {
private final String dbTest = "src/test/resources/dbfiles/";
private final JsonRepository tamburete;
public JsonRepositoryTest() throws IOException, GeneralSecurityException {
this.tamburete = new JsonRepository(this.dbTest);
}
@Test
public void testandoCriarRepEscola() {
final EscolaRepository resultado = this.tamburete.meDaUmBancoDeEscola();
assertNotNull(resultado);
}
@Test
public void testandoCriarRepEstabelecimento() {
final EstabelecimentoRepository resultado = this.tamburete.meDaUmBancoDeestabelecimentos();
assertNotNull(resultado);
}
@Test
public void testandoCriarRepListaMaterial() {
final ListaMaterialRepository resultado = this.tamburete.meDaUmBancoDeListaMaterial();
assertNotNull(resultado);
}
@Test
public void testandoCriarRepDeDescricaoMaterial() {
final DescricaoMaterialEscolarRepository resultado = this.tamburete.meDaUmBancoDeMaterial();
assertNotNull(resultado);
}
}
| true |
5381faada8cc17ff973183d2fb5fcd425ac0b322 | Java | irinatin/National-Parks-Forecast-Capstone-Project-Module-3 | /src/test/java/com/techelevator/npgeek/cukes/SurveyResultPage.java | UTF-8 | 321 | 1.867188 | 2 | [] | no_license | package com.techelevator.npgeek.cukes;
import org.openqa.selenium.WebDriver;
public class SurveyResultPage extends SurveyInputTestPage {
private WebDriver webDriver;
public SurveyResultPage(WebDriver webDriver) {
this.webDriver = webDriver;
}
public String getTitle() {
return webDriver.getTitle();
}
}
| true |
761e65a13722babea6035ef707ff066f2dbe37c9 | Java | HausemasterIssue/novoline | /src/net/minecraft/client/resources/SimpleReloadableResourceManager$1.java | UTF-8 | 512 | 2 | 2 | [
"Unlicense"
] | permissive | package net.minecraft.client.resources;
import com.google.common.base.Function;
import net.minecraft.client.resources.IResourcePack;
import net.minecraft.client.resources.SimpleReloadableResourceManager;
class SimpleReloadableResourceManager$1 implements Function {
final SimpleReloadableResourceManager this$0;
SimpleReloadableResourceManager$1(SimpleReloadableResourceManager var1) {
this.this$0 = var1;
}
public String apply(IResourcePack var1) {
return var1.getPackName();
}
}
| true |
607538fec82159ab08b00dd33d7412108deb4c8e | Java | tiagoros/gravitee-access-management | /gravitee-am-plugins-handlers/gravitee-am-plugins-handlers-extensiongrant/src/main/java/io/gravitee/am/plugins/extensiongrant/core/impl/ExtensionGrantPluginManagerImpl.java | UTF-8 | 7,573 | 1.671875 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.am.plugins.extensiongrant.core.impl;
import io.gravitee.am.extensiongrant.api.ExtensionGrant;
import io.gravitee.am.extensiongrant.api.ExtensionGrantConfiguration;
import io.gravitee.am.extensiongrant.api.ExtensionGrantProvider;
import io.gravitee.am.identityprovider.api.AuthenticationProvider;
import io.gravitee.am.identityprovider.api.NoAuthenticationProvider;
import io.gravitee.am.plugins.extensiongrant.core.ExtensionGrantConfigurationFactory;
import io.gravitee.am.plugins.extensiongrant.core.ExtensionGrantDefinition;
import io.gravitee.am.plugins.extensiongrant.core.ExtensionGrantPluginManager;
import io.gravitee.plugin.core.api.Plugin;
import io.gravitee.plugin.core.api.PluginContextFactory;
import io.gravitee.plugin.core.internal.AnnotationBasedPluginContextConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Import;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
/**
* @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com)
* @author GraviteeSource Team
*/
public class ExtensionGrantPluginManagerImpl implements ExtensionGrantPluginManager {
private final Logger logger = LoggerFactory.getLogger(ExtensionGrantPluginManagerImpl.class);
private final static String SCHEMAS_DIRECTORY = "schemas";
private final Map<String, ExtensionGrant> extensionGrants = new HashMap<>();
private final Map<ExtensionGrant, Plugin> extensionGrantPlugins = new HashMap<>();
@Autowired
private PluginContextFactory pluginContextFactory;
@Autowired
private ExtensionGrantConfigurationFactory extensionGrantConfigurationFactory;
@Override
public void register(ExtensionGrantDefinition extensionGrantDefinition) {
extensionGrants.putIfAbsent(extensionGrantDefinition.getPlugin().id(),
extensionGrantDefinition.getExtensionGrant());
extensionGrantPlugins.putIfAbsent(extensionGrantDefinition.getExtensionGrant(),
extensionGrantDefinition.getPlugin());
}
@Override
public Collection<Plugin> getAll() {
return extensionGrantPlugins.values();
}
@Override
public Plugin findById(String identityProviderId) {
ExtensionGrant extensionGrant = extensionGrants.get(identityProviderId);
return (extensionGrant != null) ? extensionGrantPlugins.get(extensionGrant) : null;
}
@Override
public ExtensionGrantProvider create(String type, String configuration, AuthenticationProvider authenticationProvider) {
logger.debug("Looking for an extension grant provider for [{}]", type);
ExtensionGrant extensionGrant = extensionGrants.get(type);
if (extensionGrant != null) {
Class<? extends ExtensionGrantConfiguration> configurationClass = extensionGrant.configuration();
ExtensionGrantConfiguration extensionGrantConfiguration = extensionGrantConfigurationFactory.create(configurationClass, configuration);
return create0(extensionGrantPlugins.get(extensionGrant),
extensionGrant.provider(),
extensionGrantConfiguration, authenticationProvider);
} else {
logger.error("No extension grant provider is registered for type {}", type);
throw new IllegalStateException("No extension grant provider is registered for type " + type);
}
}
@Override
public String getSchema(String tokenGranterId) throws IOException {
ExtensionGrant extensionGrant = extensionGrants.get(tokenGranterId);
Path policyWorkspace = extensionGrantPlugins.get(extensionGrant).path();
File[] schemas = policyWorkspace.toFile().listFiles(
pathname -> pathname.isDirectory() && pathname.getName().equals(SCHEMAS_DIRECTORY));
if (schemas.length == 1) {
File schemaDir = schemas[0];
if (schemaDir.listFiles().length > 0) {
return new String(Files.readAllBytes(schemaDir.listFiles()[0].toPath()));
}
}
return null;
}
private <T> T create0(Plugin plugin, Class<T> extensionGrantClass, ExtensionGrantConfiguration extensionGrantConfiguration, AuthenticationProvider authenticationProvider) {
if (extensionGrantClass == null) {
return null;
}
try {
T extensionGrantObj = createInstance(extensionGrantClass);
final Import annImport = extensionGrantClass.getAnnotation(Import.class);
Set<Class<?>> configurations = (annImport != null) ?
new HashSet<>(Arrays.asList(annImport.value())) : Collections.emptySet();
ApplicationContext extensionGrantApplicationContext = pluginContextFactory.create(new AnnotationBasedPluginContextConfigurer(plugin) {
@Override
public Set<Class<?>> configurations() {
return configurations;
}
@Override
public ConfigurableApplicationContext applicationContext() {
ConfigurableApplicationContext configurableApplicationContext = super.applicationContext();
// Add extension grant configuration bean
configurableApplicationContext.addBeanFactoryPostProcessor(
new ExtensionGrantConfigurationBeanFactoryPostProcessor(extensionGrantConfiguration));
// Add extension grant identity provider bean
configurableApplicationContext.addBeanFactoryPostProcessor(
new ExtensionGrantIdentityProviderFactoryPostProcessor(authenticationProvider != null ? authenticationProvider : new NoAuthenticationProvider()));
return configurableApplicationContext;
}
});
extensionGrantApplicationContext.getAutowireCapableBeanFactory().autowireBean(extensionGrantObj);
if (extensionGrantObj instanceof InitializingBean) {
((InitializingBean) extensionGrantObj).afterPropertiesSet();
}
return extensionGrantObj;
} catch (Exception ex) {
logger.error("An unexpected error occurs while loading extension grant", ex);
return null;
}
}
private <T> T createInstance(Class<T> clazz) throws Exception {
try {
return clazz.newInstance();
} catch (InstantiationException | IllegalAccessException ex) {
logger.error("Unable to instantiate class: {}", ex);
throw ex;
}
}
}
| true |
acc5b0f7357ad7c2777f9cc87dd15474238fb405 | Java | digilogGithub/DesignPattern | /src/templateMethod/init/HyndaiMotor.java | UTF-8 | 1,216 | 3.375 | 3 | [] | no_license | package templateMethod.init;
class HyndaiMotor {
private Door door;
private MotorStatus motorStatus;
// private Motor motor;
HyndaiMotor(Door door) {
this.door = door;
motorStatus = MotorStatus.STOPPED;
}
void move(Direction direction) {
// if (getMotorStatus() == MotorStatus.STOPPED) {
// if (door.getDoorStatus() == DoorStatus.OPENED) {
// door.close();
// }
// moveHyundaiMotor(direction);
// } else
// System.out.println("Motor is already moving");
MotorStatus motorStatus = getMotorStatus();
if ( motorStatus == MotorStatus.MOVING)
return;
DoorStatus doorStatus = door.getDoorStatus();
if(doorStatus == DoorStatus.OPENED)
door.close();
moveHyundaiMotor(direction);
setMotorStatus(MotorStatus.MOVING);
}
MotorStatus getMotorStatus() {
return motorStatus;
}
private void moveHyundaiMotor(Direction direction) {
System.out.println("Start HyundaiMotor moving : " + direction);
}
private void setMotorStatus(MotorStatus motorStatus) {
this.motorStatus = motorStatus;
}
}
| true |
95e9276f5fd9354581fea6e1ce752bb2d9a50d72 | Java | nieyue/XuDeCeYiFaServer | /src/com/nieyue/controller/TestController.java | UTF-8 | 14,109 | 2.171875 | 2 | [] | no_license | package com.nieyue.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.nieyue.bean.Answer;
import com.nieyue.bean.Problem;
import com.nieyue.bean.Test;
import com.nieyue.comments.MyDateFormatter;
import com.nieyue.exception.StateResult;
import com.nieyue.service.AnswerService;
import com.nieyue.service.ProblemService;
import com.nieyue.service.TestService;
import com.nieyue.util.DateUtil;
import com.nieyue.util.FileUploadUtil;
import com.nieyue.util.UploaderPath;
/**
* 测试控制类
* @author yy
*
*/
@Controller("testController")
@RequestMapping("/test")
public class TestController {
@Resource
private TestService testService;
@Resource
private ProblemService problemService;
@Resource
private AnswerService answerService;
/**
* 根据类别测试分页浏览
* @param orderName 商品排序数据库字段
* @param orderWay 商品排序方法 asc升序 desc降序
* @return
*/
@RequestMapping(value = "/list/type", method = {RequestMethod.GET,RequestMethod.POST})
public @ResponseBody List<Test> browsePagingTestByType(
@RequestParam(value="level",required=false)Integer level,
@RequestParam(value="type")String type,
@RequestParam(value="pageNum",defaultValue="1",required=false)int pageNum,
@RequestParam(value="pageSize",defaultValue="10",required=false) int pageSize,
@RequestParam(value="orderName",required=false,defaultValue="test_id") String orderName,
@RequestParam(value="orderWay",required=false,defaultValue="desc") String orderWay,HttpSession session) {
List<Test> list = new ArrayList<Test>();
list= testService.browsePagingTestByType(level,type,pageNum, pageSize, orderName, orderWay);
return list;
}
/**
* 测试分页浏览
* @param orderName 商品排序数据库字段
* @param orderWay 商品排序方法 asc升序 desc降序
* @return
*/
@RequestMapping(value = "/list", method = {RequestMethod.GET,RequestMethod.POST})
public @ResponseBody List<Test> browsePagingTest(
@RequestParam(value="pageNum",defaultValue="1",required=false)int pageNum,
@RequestParam(value="pageSize",defaultValue="10",required=false) int pageSize,
@RequestParam(value="orderName",required=false,defaultValue="test_id") String orderName,
@RequestParam(value="orderWay",required=false,defaultValue="desc") String orderWay,HttpSession session) {
List<Test> list = new ArrayList<Test>();
list= testService.browsePagingTest(pageNum, pageSize, orderName, orderWay);
return list;
}
/**
* 测试全部查询
* @param orderName 商品排序数据库字段
* @param orderWay 商品排序方法 asc升序 desc降序
* @return
*/
@RequestMapping(value = "/list/all", method = {RequestMethod.GET,RequestMethod.POST})
public @ResponseBody List<Test> browseAllTest(
@RequestParam(value="orderName",required=false,defaultValue="test_id") String orderName,
@RequestParam(value="orderWay",required=false,defaultValue="desc") String orderWay,HttpSession session) {
List<Test> list = new ArrayList<Test>();
list= testService.browseAllTest( orderName, orderWay);
return list;
}
/**
* 测试修改
* @return
*/
@RequestMapping(value = "/update", method = {RequestMethod.GET,RequestMethod.POST})
public @ResponseBody StateResult updateTest(@ModelAttribute Test test,HttpSession session) {
boolean um = testService.updateTest(test);
return StateResult.getSR(um);
}
/**
* 后台测试测试修改
* @return
*/
@RequestMapping(value = "/update/all", method = {RequestMethod.GET,RequestMethod.POST})
public @ResponseBody StateResult updateAllTest(@RequestParam("testDTO") String testDTO,HttpSession session) {
boolean am=false;
JSONObject jsonObject = JSONObject.fromObject(testDTO);
Integer testId = (Integer) jsonObject.get("test_id");
Test test=testService.loadTest(testId);
test.setTitle((String)jsonObject.get("title"));
test.setType((String)jsonObject.get("type"));
test.setLevel((Integer)jsonObject.get("level"));
test.setImg((String)jsonObject.get("img"));
am=testService.updateTest(test);
Object problemList = jsonObject.get("problemList");
JSONArray problemListArray = JSONArray.fromObject(problemList);
Iterator<JSONObject> pi = problemListArray.iterator();
while (pi.hasNext()) {
JSONObject problemDTO = pi.next();
Problem problem=new Problem();
if(problemDTO.get("problem_id")!=null&&!problemDTO.get("problem_id").equals("")){
Integer problemId = problemDTO.getInt("problem_id");
problem=problemService.loadProblem(problemId);
}
problem.setName(problemDTO.getString("name"));
problem.setType(problemDTO.getString("type"));
problem.setImg(problemDTO.getString("img"));
problem.setOrderNumber((Integer)problemDTO.get("order_number"));
problem.setTestId(test.getTestId());
if(problemDTO.get("problem_id")!=null&&!problemDTO.get("problem_id").equals("")){
am=problemService.updateProblem(problem);
}else{
am=problemService.addProblem(problem);
}
Object answerList = problemDTO.get("answerList");
JSONArray answerListArray = JSONArray.fromObject(answerList);
Iterator<JSONObject> ai = answerListArray.iterator();
while (ai.hasNext()) {
Answer answer=new Answer();
JSONObject answerDTO = ai.next();
if(answerDTO.get("answer_id")!=null&&!answerDTO.get("answer_id").equals("")){
Integer answerId = answerDTO.getInt("answer_id");
answer=answerService.loadAnswer(answerId);
}
answer.setName(answerDTO.getString("name"));
answer.setType(answerDTO.getString("type"));
answer.setImg(answerDTO.getString("img"));
answer.setResult(answerDTO.getString("result"));
answer.setProblemId(problem.getProblemId());
if(answerDTO.get("answer_id")!=null&&!answerDTO.get("answer_id").equals("")){
am=answerService.updateAnswer(answer);
}else{
am=answerService.addAnswer(answer);
}
}
}
return StateResult.getSR(am);
}
/**
* 测试增加
* @return
*/
@RequestMapping(value = "/add", method = {RequestMethod.GET,RequestMethod.POST})
public @ResponseBody StateResult addTest(@ModelAttribute Test test, HttpSession session) {
boolean am = testService.addTest(test);
return StateResult.getSR(am);
}
/**
* 后台测试增加
* @return
*/
@RequestMapping(value = "/add/all", method = {RequestMethod.GET,RequestMethod.POST})
public @ResponseBody StateResult addAllTest(@RequestParam("testDTO") String testDTO, HttpSession session) {
boolean am=false;
Test test=new Test();
JSONObject jsonObject = JSONObject.fromObject(testDTO);
test.setTitle((String)jsonObject.get("title"));
test.setType((String)jsonObject.get("type"));
test.setLevel((Integer)jsonObject.get("level"));
test.setImg((String)jsonObject.get("img"));
am=testService.addTest(test);
Object problemList = jsonObject.get("problemList");
JSONArray problemListArray = JSONArray.fromObject(problemList);
Iterator<JSONObject> pi = problemListArray.iterator();
while (pi.hasNext()) {
Problem problem=new Problem();
JSONObject problemDTO = pi.next();
problem.setName(problemDTO.getString("name"));
problem.setType(problemDTO.getString("type"));
problem.setImg(problemDTO.getString("img"));
problem.setOrderNumber(problemDTO.getInt("order_number"));
problem.setTestId(test.getTestId());
am=problemService.addProblem(problem);
Object answerList = problemDTO.get("answerList");
JSONArray answerListArray = JSONArray.fromObject(answerList);
Iterator<JSONObject> ai = answerListArray.iterator();
while (ai.hasNext()) {
Answer answer=new Answer();
JSONObject answerDTO = ai.next();
answer.setName(answerDTO.getString("name"));
answer.setType(answerDTO.getString("type"));
answer.setImg(answerDTO.getString("img"));
answer.setResult(answerDTO.getString("result"));
answer.setProblemId(problem.getProblemId());
am=answerService.addAnswer(answer);
}
}
return StateResult.getSR(am);
}
/**
*测试 删除
* @return
*/
@RequestMapping(value = "/{testId}/delete", method = {RequestMethod.GET,RequestMethod.POST})
public @ResponseBody StateResult delTest(@PathVariable("testId") Integer testId,HttpSession session) {
List<Problem> pl = problemService.browseAllProblemByTestId(testId, "order_number", "asc");
for (int i = 0; i < pl.size(); i++) {
Problem problem = pl.get(i);
List<Answer> al = answerService.browseAllAnswerByProblemId(problem.getProblemId(), "answer_id", "asc");
for (int j = 0; j < al.size(); j++) {
answerService.delAnswer(al.get(j).getAnswerId());
}
problemService.delProblem(pl.get(i).getProblemId());
}
boolean dm = testService.delTest(testId);
return StateResult.getSR(dm);
}
/**
* 测试浏览数量
* @return
*/
@RequestMapping(value = "/count", method = {RequestMethod.GET,RequestMethod.POST})
public @ResponseBody int countAll(HttpSession session) {
int count = testService.countAll();
return count;
}
/**
* 根据类别测试浏览数量
* @return
*/
@RequestMapping(value = "/count/type", method = {RequestMethod.GET,RequestMethod.POST})
public @ResponseBody int countAllByType(@RequestParam("type")String type,HttpSession session) {
int count = testService.countAllByType(type);
return count;
}
/**
* 测试单个加载
* @return
*/
@RequestMapping(value = "/{testId}", method = {RequestMethod.GET,RequestMethod.POST})
public @ResponseBody Test loadTest(@PathVariable("testId") Integer testId,HttpSession session) {
Test test=new Test();
test = testService.loadTest(testId);
return test;
}
/**
* 测试单个加载一套
* @return
*/
@RequestMapping(value = "/{testId}/all", method = {RequestMethod.GET,RequestMethod.POST})
public @ResponseBody String loadAllTest(@PathVariable("testId") Integer testId,HttpSession session) {
Test test=new Test();
test = testService.loadTest(testId);
JSONObject jsonObj = new JSONObject();
jsonObj.put("test_id", testId);
if(test.getTitle()==null){
test.setTitle("");
}
jsonObj.put("title", test.getTitle());
if(test.getType()==null){
test.setType("");
}
jsonObj.put("type", test.getType());
if(test.getLevel()==null){
test.setLevel(10);
}
jsonObj.put("level", test.getLevel());
if(test.getImg()==null){
test.setImg("");
}
jsonObj.put("img", test.getImg());
jsonObj.put("update_date",DateUtil.getFormatDate(test.getUpdateDate()));
JSONArray problemListArray = new JSONArray();
List<Problem> pl = problemService.browseAllProblemByTestId(test.getTestId(), "order_number", "asc");
for (int i = 0; i < pl.size(); i++) {
Problem problem = pl.get(i);
JSONObject problemjsonobj = new JSONObject();
problemjsonobj.put("problem_id", problem.getProblemId());
if(problem.getName()==null){
problem.setName("");
}
problemjsonobj.put("name", problem.getName());
if(problem.getType()==null){
problem.setType("");
}
problemjsonobj.put("type", problem.getType());
if(problem.getOrderNumber()==null){
problem.setOrderNumber(1);
}
problemjsonobj.put("order_number", problem.getOrderNumber());
if(problem.getImg()==null){
problem.setImg("");
}
problemjsonobj.put("img", problem.getImg());
problemjsonobj.put("update_date", DateUtil.getFormatDate(problem.getUpdateDate()));
JSONArray answerListArray = new JSONArray();
List<Answer> al = answerService.browseAllAnswerByProblemId(problem.getProblemId(), "answer_id", "asc");
for (int j = 0; j < al.size(); j++) {
Answer answer = al.get(j);
JSONObject answerjsonobj = new JSONObject();
answerjsonobj.put("answer_id", answer.getAnswerId());
if(answer.getName()==null){
answer.setName("");
}
answerjsonobj.put("name", answer.getName());
if(answer.getType()==null){
answer.setType("");
}
answerjsonobj.put("type", answer.getType());
if(answer.getResult()==null){
answer.setResult("");
}
answerjsonobj.put("result", answer.getResult());
if(answer.getImg()==null){
answer.setImg("");
}
answerjsonobj.put("img", answer.getImg());
answerjsonobj.put("update_date", DateUtil.getFormatDate(answer.getUpdateDate()));
answerListArray.add(answerjsonobj);
}
problemjsonobj.put("answerList",answerListArray);
problemListArray.add(problemjsonobj);
}
jsonObj.put("problemList",problemListArray);
return jsonObj.toString();
}
/**
* 图片增加
* @return
* @throws IOException
*/
@RequestMapping(value = "/img/add", method = {RequestMethod.GET,RequestMethod.POST})
public @ResponseBody String addAdvertiseImg(
@RequestParam("testFileUpload") MultipartFile file,
HttpSession session ) throws IOException {
String imgUrl = null;
String imgdir=DateUtil.getImgDir();
try{
imgUrl = FileUploadUtil.FormDataMerImgFileUpload(file, session,UploaderPath.GetValueByKey(UploaderPath.ROOTPATH),UploaderPath.GetValueByKey(UploaderPath.IMG),imgdir);
}catch (IOException e) {
throw new IOException();
}
return imgUrl;
}
}
| true |
8db13cffa7380c1121cc9acfb08e827cae7e1ccf | Java | Ashrom0/Projects | /Full-Inheritance/Full-Inheritance/lab8/cscd211comparators/TeamPayrollComparator.java | UTF-8 | 425 | 3.0625 | 3 | [] | no_license | package lab8.cscd211comparators;
import java.util.Comparator;
import lab8.cscd211classes.Team;
public class TeamPayrollComparator implements Comparator<Team>
{
@Override
public int compare(final Team t1, final Team t2)
{
if(t1 == null || t2 == null)
{
throw new IllegalArgumentException("Error: " + (t1 == null ? "t1": "t2") + " is null");
}
int res = t1.getPayroll() - t2.getPayroll();
return res;
}
}
| true |
000a062a6957f58cec82ff23f7a6aa6b023f60df | Java | kacyan/testruts | /src/jp/co/ksi/incubator/oauth/GetRequestToken.java | UTF-8 | 7,367 | 2.28125 | 2 | [] | no_license | package jp.co.ksi.incubator.oauth;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import JP.co.ksi.util.URLEncoder;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;
import jp.co.ksi.eip.commons.struts.InvokeAction;
/**
* OAuthリクエスト・トークンを取得する習作
* <pre>
* (1)OAuthを生成し、セッションに保存する
* (2)requestTokenURLにリクエストを送る
* (3)レスポンスからリクエスト・トークンを取得する
* </pre>
* @author kac
* @since 2012/03/06
* @version 2012/04/10 はてな対応
* <pre>
* YahooとGoogleのOAuthが使えるようになった。
* oauth_signature_methodは、HMAC-SHA1が良いみたい
* oauthパラメータは、Authorizationリクエストヘッダーで送るのが良いみたい
* Googleのサンプルが一般的には推奨らしい。
* またGoogleにはテストツールがある
* http://googlecodesamples.com/oauth_playground/
* 問題は、以下の2点
* 1.Yahooは、scopeがあるとエラー。Googleは、scopeがないとエラー
* 2.Googleはxoauth_request_auth_url(リダイレクト先URL)を返さない
*
* [2012/04/10] はてな対応
* リクエストで送付するoauthパラメータは、URLエンコードしておく必要がある
* レスポンスで返ってくるoauthパラメータはURLデコードする
* </pre>
*/
public class GetRequestToken extends OAuthBaseBL
{
static Logger log= Logger.getLogger( GetRequestToken.class );
@Override
public String subExecute( InvokeAction action, ActionForm form,
HttpServletRequest request, HttpServletResponse response )
throws Exception
{
// (1)oauthを生成し、セッションに保存する
DynaActionForm dyna = (DynaActionForm)form;
HttpSession session= request.getSession();
oauth= new OAuthBean();
session.setAttribute( SESS_ATTR_OAUTH, oauth );
oauth.setConsumer_key( dyna.getString( "consumer_key" ) );
oauth.setConsumer_secret( dyna.getString( "consumer_secret" ) );
oauth.setOauth_callback( dyna.getString( "oauth_callback" ) );
oauth.setScope( dyna.getString( "scope" ) );
oauth.setRequestTokenURL( dyna.getString( "requestTokenURL" ) );
oauth.setAuthorizeTokenURL( dyna.getString( "authorizeTokenURL" ) );
oauth.setAccessTokenURL( dyna.getString( "accessTokenURL" ) );
log.debug( "oauth="+ oauth );
// (2)シグネチャ用パラメータを生成する
Properties oauthParam= new Properties();
oauthParam.setProperty( "oauth_callback", URLEncoder.encode( oauth.getOauth_callback(), OAuthBean.UTF8 ) );
oauthParam.setProperty( "oauth_consumer_key", URLEncoder.encode( oauth.getConsumer_key(), OAuthBean.UTF8 ) );
oauthParam.setProperty( "oauth_nonce", oauth.getOauth_nonce() );
// oauthParam.setProperty( "oauth_nonce", "4ff82451b1296c80369729c20d39492d" );
oauthParam.setProperty( "oauth_signature_method", OAUTH_SIGNATURE_METHOD );
oauthParam.setProperty( "oauth_timestamp", String.valueOf( System.currentTimeMillis() / 1000 ) );
oauthParam.setProperty( "oauth_version", "1.0" );
// (3)oauthParamからauthorizationヘッダーを生成する
// (4)signature生成用のパラメータストリングも生成する
String param= "";
String authorization= "OAuth ";
String[] names= new String[oauthParam.keySet().size()];
names= (String[])oauthParam.keySet().toArray( names );
java.util.Arrays.sort( names );
for( int i= 0; i < names.length; i++ )
{
String value= oauthParam.getProperty( names[i] );
authorization+= ""+ names[i] +"=\""+ value +"\",";
param+= "&"+ names[i] +"="+ value;
}
param= param.substring( 1 );
String url= oauth.getRequestTokenURL();
String method = "GET";
if( oauth.getScope().length() > 0 )
{
url+= "?scope="+ URLEncoder.encode( oauth.getScope(), OAuthBean.UTF8 );
param+= "&scope="+ URLEncoder.encode( oauth.getScope(), OAuthBean.UTF8 );
}
log.debug( "url="+ url );
log.debug( "param="+ param );
// signatureを生成する
String signature= oauth.getSignature( method, oauth.getRequestTokenURL(), param );
authorization+= "oauth_signature=\""+ signature +"\"";
log.debug( "authorization="+ authorization );
URL u= new URL( url );
URLConnection con= u.openConnection( proxy );
if( con instanceof HttpURLConnection )
{
HttpURLConnection http= (HttpURLConnection)con;
http.setRequestMethod( method );
http.setRequestProperty( "Authorization", authorization );
// 送信ここまで
log.debug( "responseCode="+ http.getResponseCode() );
log.debug( http.getResponseMessage() );
// レスポンスヘッダを表示する
// エラーが発生した場合、WWW-Authenticateに詳細情報が返ってくる
Map<String, java.util.List<String>> headers= http.getHeaderFields();
String[] keys= new String[headers.keySet().size()];
keys= (String[])headers.keySet().toArray( keys );
for( int i= 0; i < keys.length; i++ )
{
log.debug( "[RES_HEADER] "+ keys[i] +"="+ headers.get( keys[i] ) );
if( "WWW-Authenticate".equals( keys[i] ) )
{
String wwwAuthenticate= headers.get( keys[i] ).toString();
addError( "BL.ClsName.ERR.P001", getClass().getName(), wwwAuthenticate );
}
}
}
String resText= "";
BufferedReader reader= new BufferedReader( new InputStreamReader( con.getInputStream() ) );
String line= reader.readLine();
while( line != null )
{
log.debug( line );
resText += line;
line= reader.readLine();
}
reader.close();
log.debug( resText );
String oauthToken = OAuthBean.getResponseParamValue( "oauth_token", resText );
log.info( "oauthToken=["+ oauthToken +"]" );
oauth.setOauth_token( oauthToken );
// request.setAttribute( "oauthToken", oauthToken );
String oauthTokenSecret = OAuthBean.getResponseParamValue( "oauth_token_secret", resText );
log.info( "oauthTokenSecret=["+ oauthTokenSecret +"]" );
oauth.setOauth_token_secret( oauthTokenSecret );
// request.setAttribute( "oauthTokenSecret", oauthTokenSecret );
String oauthExpiresIn = OAuthBean.getResponseParamValue( "oauth_expires_in", resText );
log.info( "oauthExpiresIn=["+ oauthExpiresIn +"]" );
request.setAttribute( "oauthExpiresIn", oauthExpiresIn );
String xoauthRequestAuthUrl = OAuthBean.getResponseParamValue( "xoauth_request_auth_url", resText );
log.info( "xoauthRequestAuthUrl=["+ xoauthRequestAuthUrl +"]" );
oauth.setXoauth_request_auth_url( xoauthRequestAuthUrl );
// request.setAttribute( "xoauthRequestAuthUrl", xoauthRequestAuthUrl );
String oauthCallbackConfirmed = OAuthBean.getResponseParamValue( "oauth_callback_confirmed", resText );
log.info( "oauthCallbackConfirmed=["+ oauthCallbackConfirmed +"]" );
request.setAttribute( "oauthCallbackConfirmed", oauthCallbackConfirmed );
log.debug( "oauth="+ oauth );
return APL_OK;
}
}
| true |
31a01c1ab087fe7b0f89c48c16c2c66131c4e0c2 | Java | kylinmac/leetCode | /src/main/java/com/mc/code/SubsetsWithDup.java | UTF-8 | 335 | 2.015625 | 2 | [
"Apache-2.0"
] | permissive | package com.mc.code;
import java.util.Arrays;
import java.util.List;
/**
* @author macheng
* @date 2021/3/31 9:09
*/
public class SubsetsWithDup {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
return null;
}
public void huishuo(int offset,List<Integer> lists){
}
}
| true |
ba3763010e8c4aaa660996f3254ac87a1578ebe7 | Java | etnlGD/Double-Shoot | /src/com/doubleshoot/troop/UniformDeterminer.java | UTF-8 | 262 | 2.640625 | 3 | [] | no_license | package com.doubleshoot.troop;
public class UniformDeterminer<T> implements ITroopDetermin<T> {
private T mValue;
public UniformDeterminer(T uniformValue) {
mValue = uniformValue;
}
@Override
public T next(int index, T prev) {
return mValue;
}
}
| true |
8bb1274262fb6fa390053578026b77d3c59307c2 | Java | LuuLinhSon/MuaSamTrucTuyen | /app/src/main/java/com/project/luulinhson/muasamtructuyen/View/Rating/ViewRating.java | UTF-8 | 354 | 1.59375 | 2 | [] | no_license | package com.project.luulinhson.muasamtructuyen.View.Rating;
import com.project.luulinhson.muasamtructuyen.Model.Object.DanhGia;
import java.util.List;
/**
* Created by Admin on 4/12/2017.
*/
public interface ViewRating {
void ThemDanhGiaThanhCong();
void ThemDanhGiaThatBai();
void HienThiDanhSachDanhGia(List<DanhGia> danhGiaList);
}
| true |
dfbd35fc44043048c67da49fcc6c707a7e02ea54 | Java | bingoohuang/eql | /src/test/java/org/n3r/eql/eqler/TranBatchEqlerDemo.java | UTF-8 | 882 | 1.992188 | 2 | [
"Apache-2.0"
] | permissive | package org.n3r.eql.eqler;
import org.n3r.eql.Eql;
import org.n3r.eql.EqlTran;
import org.n3r.eql.impl.EqlBatch;
public class TranBatchEqlerDemo implements TranBatchEqler {
public void prepareData() {
new Eql().me().execute("xxx", "yyy");
}
@Override
public void cleanCnt() {
}
public int queryCnt() {
return new Eql().me().execute();
}
public int incrCnt(EqlTran eqlTran, int incr) {
return new Eql().me().useTran(eqlTran).params(incr).execute();
}
@Override
public int incrCntBatch(int incr, EqlTran eqlTran, EqlBatch eqlBatch) {
return new Eql().me().useTran(eqlTran).useBatch(eqlBatch).params(incr).execute();
}
@Override
public int decrCnt(int incr, EqlTran eqlTran) {
return 0;
}
public static void main(String[] args) {
new TranBatchEqlerDemo();
}
}
| true |
383a3905b2dcf8a49352db32aeee6dd563fc62d1 | Java | bellaxin2010/testJAVA | /src/BasicKnowledge/UserLogin.java | UTF-8 | 643 | 2.8125 | 3 | [] | no_license | import java.util.Scanner;
public class UserLogin {
private String[][] userBox = {{"aaa", "111"}, {"bbb", "222"}};//当属性
public String userLogin(String username, String pwd) {
String result = "wrong pwd or username";
for (int i = 0; i < userBox.length; i++) {
if (userBox[i][0].equals(username)) {
if (userBox[i][1].equals(pwd)) {
return "Login succesfully";
//flag=true;
}
break;
}
}
/* if(!flag){
System.out.println("wrong pwd");
}
*/
return result;
}
}
| true |
2e986ecc59f9dee2eb7e81159a9a84dbae69ff0e | Java | xiaobaobao007/PracticeCode | /src/Arithmetic/WhMyPeople.java | UTF-8 | 696 | 3.765625 | 4 | [] | no_license | package Arithmetic;
/**
* @author xiaobaobao
* @date 2020/4/6,21:21
* <p>
* 幼儿园45个小朋友围成一圈。从班长开始顺时针1报数,报到3出列,
* 下一个从1开始,来回这样报数后,最后剩下的是班长顺时针方向旁边第几个同学?
*/
public class WhMyPeople {
public static void main(String[] args) {
new WhMyPeople().doIt(5);
}
public void doIt(int num) {
int[] people = new int[num];
for (int i = 0, j = num - 1; i < num; j = i++) {
people[j] = i;
}
int size = num;
int point = 0;
while (--size > 0) {
int last = people[point];
point = people[last] = people[people[last]];
}
System.out.println(point);
}
}
| true |
8a540ebf4d422367f89d5824748e81cbf97651f1 | Java | hanviki/jwback | /src/main/java/com/welb/organization_check/service_impl/ResultDetailServiceImpl.java | UTF-8 | 1,537 | 1.851563 | 2 | [] | no_license | package com.welb.organization_check.service_impl;
import com.welb.organization_check.entity.ResultDetail;
import com.welb.organization_check.mapper.ResultDetailMapper;
import com.welb.organization_check.service.IResultDetailService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* @author luoyaozu
* @title: ResultDetailServiceImpl
* @projectName xh-360appraisal-interface
* @description: TODO
* @date 2019/6/2611:50
*/
@Service
@Transactional
public class ResultDetailServiceImpl implements IResultDetailService {
@Resource
ResultDetailMapper detailMapper;
@Override
public int deleteByPrimaryKey(Integer id) {
return detailMapper.deleteByPrimaryKey(id);
}
@Override
public int insertSelective(ResultDetail detail) {
return detailMapper.insertSelective(detail);
}
@Override
public ResultDetail selectByPrimaryKey(Integer id) {
return detailMapper.selectByPrimaryKey(id);
}
@Override
public int updateByPrimaryKeySelective(ResultDetail detail) {
return detailMapper.updateByPrimaryKeySelective(detail);
}
@Override
public List<ResultDetail> selectResultDetailByReportCode(Integer code) {
return detailMapper.selectResultDetailByReportCode(code);
}
@Override
public int batchDelete(List<Integer> resultDetailIds) {
return detailMapper.batchDelete(resultDetailIds);
}
}
| true |
a6b10e43f5ee2b3d49cc95ef44d0bfc16349ea96 | Java | rettes/Java-Social-Media- | /src/main/java/dao/PlotDAO.java | UTF-8 | 4,014 | 2.890625 | 3 | [] | no_license | package main.java.dao;
import main.java.socialmagnet.*;
import java.sql.*;
import java.util.*;
public class PlotDAO {
public HashMap<Integer, ArrayList<Object>> getPlots(String username) {
ConnectionManager cm = new ConnectionManager();
ArrayList<Object> data = new ArrayList<>();
data.add(username);
String sql = "select * from plot where username = ?";
ResultSet rs = (ResultSet) cm.getConnection(sql, data, false);
HashMap<Integer, ArrayList<Object>> plots = new HashMap<>();
try {
while (rs != null && rs.next()) {
ArrayList<Object> crop_info = new ArrayList<>();
if (rs.getString("crop") == null || rs.getString("time_planted") == null) {
plots.put(rs.getInt("plot_number"), crop_info);
} else {
crop_info.add(rs.getString("crop"));
crop_info.add(rs.getTimestamp("time_planted"));
plots.put(rs.getInt("plot_number"), crop_info);
}
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Plot cannot be found.");
}
return plots;
}
public boolean clearPlot(String username, int plot_number) {
ConnectionManager cm = new ConnectionManager();
ArrayList<Object> data = new ArrayList<>();
data.add(username);
data.add(plot_number);
String sql = "UPDATE plot SET crop= null ,time_planted = null where username = ? and plot_number = ?";
int rows_changed = (Integer) cm.getConnection(sql, data, true);
if (rows_changed == 1) {
return true;
}
return false;
}
public boolean plantPlot(String username, int plot_number, String cropName) {
ConnectionManager cm = new ConnectionManager();
ArrayList<Object> data = new ArrayList<>();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
data.add(cropName);
data.add(timestamp);
data.add(username);
data.add(plot_number);
String sql = "UPDATE plot SET crop= ? ,time_planted = ? where username = ? and plot_number = ?";
int rows_changed = (Integer) cm.getConnection(sql, data, true);
if (rows_changed == 1) {
return true;
}
return false;
}
public void populatePlots(Member member) {
if (member.getGold() <= 50 && member.getExperience() == 0) {
for (int i = 1; i <= 5; i++) {
ConnectionManager cm = new ConnectionManager();
ArrayList<Object> data = new ArrayList<>();
Timestamp timestamp = null;
data.add(member.getUsername());
data.add(i);
String sql = "INSERT INTO plot (username, plot_number, crop, time_planted) values (?,?,null,null)";
int rows_changed = (Integer) cm.getConnection(sql, data, true);
}
}
}
public void addPlot(Member member){
ConnectionManager cm = new ConnectionManager();
ArrayList<Object> data = new ArrayList<>();
HashMap<Integer,ArrayList<Object>> plots = getPlots(member.getUsername());
data.add(member.getUsername());
data.add(plots.size()+ 1 );
String sql = "INSERT INTO plot (username, plot_number, crop, time_planted) values (?,?,null,null)";
int rows_changed = (Integer) cm.getConnection(sql, data, true);
}
public void checkIfCorrectNumberOfPlots(Member member , HashMap<Integer, ArrayList<Object>> plots){
MemberDAO memberDAO = new MemberDAO();
String rank = memberDAO.getRank(member);
int numberOfPlots = memberDAO.getPlotsAccordingToRank(member);
if(plots.size() < numberOfPlots){
int difference = numberOfPlots - plots.size();
for(int i = 0 ; i <difference ; i++){
addPlot(member);
}
}
}
} | true |
1c6cd190e8b9c880ab0673ac2ca2967dd556540a | Java | tp-team/dreamFM | /app/src/main/java/com/dreamteam/androidproject/newapi/answer/ArtistGetInfoAnswer.java | UTF-8 | 3,004 | 1.976563 | 2 | [] | no_license | package com.dreamteam.androidproject.newapi.answer;
import com.dreamteam.androidproject.newapi.template.ObjectList;
/**
* Created by nap on 12/4/2014.
*/
public class ArtistGetInfoAnswer {
private String status;
private String name;
private String mbid;
private String url;
private String imagesmall;
private String imagemedium;
private String imagelarge;
private String streamable;
private String listeners;
private String playcount;
private ObjectList<ArtistGetInfoAnswer> similar;
private ObjectList<TagGetInfoAnswer> tags;
private String published;
private String summary;
private String content;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMbid() {
return mbid;
}
public void setMbid(String mbid) {
this.mbid = mbid;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getImagesmall() {
return imagesmall;
}
public void setImagesmall(String imagesmall) {
this.imagesmall = imagesmall;
}
public String getImagemedium() {
return imagemedium;
}
public void setImagemedium(String imagemedium) {
this.imagemedium = imagemedium;
}
public String getImagelarge() {
return imagelarge;
}
public void setImagelarge(String imagelarge) {
this.imagelarge = imagelarge;
}
public String getStreamable() {
return streamable;
}
public void setStreamable(String streamable) {
this.streamable = streamable;
}
public String getListeners() {
return listeners;
}
public void setListeners(String listeners) {
this.listeners = listeners;
}
public String getPlays() {
return playcount;
}
public void setPlays(String playcount) {
this.playcount = playcount;
}
public ObjectList<ArtistGetInfoAnswer> getSimilar() {
return similar;
}
public void setSimilar(ObjectList<ArtistGetInfoAnswer> similar) {
this.similar = similar;
}
public ObjectList<TagGetInfoAnswer> getTags() {
return tags;
}
public void setTags(ObjectList<TagGetInfoAnswer> tags) {
this.tags = tags;
}
public String getPublished() {
return published;
}
public void setPublished(String published) {
this.published = published;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
| true |
68ae26eb454bbfb00c4768a06a17095794d95ea1 | Java | kabuqinuofu/AvoidClicks | /ControlClick/src/main/java/com/yc/controlclick/ControlClick.java | UTF-8 | 386 | 1.953125 | 2 | [] | no_license | package com.yc.controlclick;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author by CNKIFU on 2020/6/12.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ControlClick {
long value() default 1000;//默认间隔时间
} | true |
d0385b932ea0c3f6b4558af0a920a39dd6a5545f | Java | jayedulhaque/AutoBot | /Auto SMS Responder/Bot Using Nexmo/maples/src/com/mapler/utility/Util.java | UTF-8 | 32,640 | 1.695313 | 2 | [] | no_license | package com.mapler.utility;
import com.mapler.model.AdModel;
import com.mapler.model.DataModel;
import com.mapler.model.SModel;
import com.mapler.model.UAModel;
import com.mapler.service.INotifier;
import com.opera.core.systems.OperaDriver;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.openqa.selenium.By;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
* @author none
*/
public class Util {
private static Logger log = Logger.getLogger(Util.class);
private static Random random;
public enum CONNSTATUS {
CONNECTED,
DISCONNECTED,
ALREADYCONNECTED,
ERROR
};
public static boolean connect(String ip, String uName, String password) {
Util.CONNSTATUS status = Util.connectVPN("C", ip, uName, password);
if (status.equals(Util.CONNSTATUS.CONNECTED)) {
return true;
}
if (status.equals(Util.CONNSTATUS.ALREADYCONNECTED)) {
status = Util.connectVPN("D", ip, uName, password);
}
if (status.equals(Util.CONNSTATUS.DISCONNECTED)) {
status = Util.connectVPN("C", ip, uName, password);
}
if (status.equals(Util.CONNSTATUS.ERROR)) {
status = Util.connectVPN("C", ip, uName, password);
}
if (status.equals(Util.CONNSTATUS.CONNECTED)) {
return true;
}
return false;
}
public static boolean disConnect(String ip, String uName, String password) {
try {
Util.CONNSTATUS status = Util.connectVPN("D", ip, uName, password);
if (status.equals(Util.CONNSTATUS.DISCONNECTED)) {
return true;
}
if (status.equals(Util.CONNSTATUS.ERROR)) {
status = Util.connectVPN("D", ip, uName, password);
}
if (status.equals(Util.CONNSTATUS.DISCONNECTED)) {
return true;
}
} catch (Throwable ex) {
ex.printStackTrace();
log.debug("disConnect:: stopped causes " + ex);
}
return false;
}
public static CONNSTATUS connectVPN(String action, String ip, String uName, String password) {
try {
String CMD;
if (action.equalsIgnoreCase("C")) {
CMD = "cmd /c rasdial.exe irobot " + uName + " " + password + " /PHONE:" + ip;
} else {
//CMD = "cmd /c rasphone.exe -h office";
CMD = "cmd /c rasdial.exe irobot /DISCONNECT";
}
// Run "netsh" Windows command
Process process = Runtime.getRuntime().exec(CMD);
// Get input streams
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
// Read command standard output
String s;
while ((s = stdInput.readLine()) != null) {
if (s.contains("Successfully connected to")) {
return CONNSTATUS.CONNECTED;
} else if (s.contains("You are already connected")) {
return CONNSTATUS.ALREADYCONNECTED;
} else if (s.contains("Remote Access error")) {
return CONNSTATUS.ERROR;
} else if (s.contains("Command completed successfully.")) {
return CONNSTATUS.DISCONNECTED;
}
}
} catch (Throwable ex) {
ex.printStackTrace();
log.debug("connectVPN:: stopped causes " + ex);
}
return CONNSTATUS.ERROR;
}
public static void addPostInfo(INotifier iNotifier, SModel sModel, String link) {
try {
iNotifier.notify("Saving posting information.");
log.debug("addPostInfo:: Saving posting confirmation link");
StringBuilder request = new StringBuilder();
request.append("<Request>");
request.append("<username>").append(sModel.getUsername()).append("</username>");
request.append("<password>").append(sModel.getPassword()).append("</password>");
request.append("<country>").append(sModel.getCountry()).append("</country>");
request.append("<link>").append(link).append("</link>");
request.append("</Request>");
String req = URLEncoder.encode(request.toString(), "UTF-8");
String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=postInfo/addPostInfo";
String param = "request=" + req;
String response = HttpHelper.post(new URL(uri), param);
Document document = DocumentHelper.parseText(response);
String errorCode = document.valueOf("Response/errorcode");
String msg = document.valueOf("Response/message");
log.debug("addPostInfo:: code :" + errorCode + " message:" + msg);
} catch (Exception ex) {
ex.printStackTrace();
iNotifier.notify("addPostInfo:: Error on saving posting information " + ex);
log.debug("addPostInfo:: stopped causes " + ex);
}
}
public static WebDriver createDriver(SModel sModel, UAModel uAModel) {
WebDriver driver = null;
Proxy proxy = null;
DesiredCapabilities capabilities = null;
if (sModel.isBrowserProxy()) {
proxy = new Proxy();
if (sModel.getProxyType()) {
proxy.setProxyType(Proxy.ProxyType.MANUAL);
} else {
proxy.setProxyType(Proxy.ProxyType.AUTODETECT);
}
if (sModel.isUseSystem()) {
proxy.setHttpProxy(sModel.getProxyServer().trim() + ":" + sModel.getProxyPort());
} else {
proxy.setHttpProxy(uAModel.getProxyIp().trim() + ":" + uAModel.getProxyPort());
proxy.setSslProxy(uAModel.getProxyIp().trim() + ":" + uAModel.getProxyPort());
//proxy.setFtpProxy(uAModel.getProxyIp().trim() + ":" + uAModel.getProxyPort());
if (uAModel.getProxyUsername() != null && !uAModel.getProxyUsername().isEmpty()) {
proxy.setSocksUsername(uAModel.getProxyUsername().trim());
}
if (uAModel.getProxyPassword() != null && !uAModel.getProxyPassword().isEmpty()) {
proxy.setSocksPassword(uAModel.getProxyPassword().trim());
}
//System.setProperty("http.proxyHost", uAModel.getProxyIp().trim());
// System.setProperty("http.proxyPort", ""+uAModel.getProxyPort());
//System.setProperty("http.proxyUser", uAModel.getProxyUsername().trim());
//System.setProperty("http.proxyPassword", uAModel.getProxyPassword().trim());
}
}
capabilities = new DesiredCapabilities();
if (proxy != null) {
capabilities.setCapability(CapabilityType.PROXY, proxy);
//capabilities.setCapability("http.proxyUser", uAModel.getProxyUsername().trim());
//capabilities.setCapability("http.proxyPassword", uAModel.getProxyPassword().trim());
}
if (sModel.getDriver().equalsIgnoreCase("IE")) {
if (StringUtils.isNotBlank(sModel.getIePath())) {
System.setProperty("webdriver.ie.driver", sModel.getIePath().trim());
} else {
String home = System.getenv("ie.home");
if (home != null && !home.isEmpty()) {
System.setProperty("webdriver.ie.driver", home);
}
}
capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
capabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
capabilities.setCapability(InternetExplorerDriver.ENABLE_ELEMENT_CACHE_CLEANUP, true);
//capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
//capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver(capabilities);
} else if (sModel.getDriver().equalsIgnoreCase("FF")) {
if (StringUtils.isNotBlank(sModel.getFfPath())) {
System.setProperty("webdriver.firefox.bin", sModel.getFfPath().trim());
} else {
String home = System.getenv("ff.home");
if (home != null && !home.isEmpty()) {
System.setProperty("webdriver.firefox.bin", home);
}
}
FirefoxProfile profile = new FirefoxProfile();
if (sModel.isResourcesHide()) {
// Disable CSS
profile.setPreference("permissions.default.stylesheet", 2);
// Disable images
profile.setPreference("permissions.default.image", 2);
// Disable Flash
profile.setPreference("dom.ipc.plugins.enabled.libflashplayer.so", "false");
}
/*if (sModel.isBrowserProxy()) {
if (sModel.getProxyType()) {
profile.setPreference("network.proxy.type", 1);
} else {
profile.setPreference("network.proxy.type", 0);
}
if (sModel.isUseSystem()) {
profile.setPreference("network.proxy.http", sModel.getProxyServer().trim());
profile.setPreference("network.proxy.http_port", sModel.getProxyPort());
} else {
profile.setPreference("network.proxy.http", uAModel.getProxyIp().trim());
profile.setPreference("network.proxy.http_port", uAModel.getProxyPort());
}
}*/
driver = new FirefoxDriver(null, profile, capabilities);
//driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
//driver. manage().timeouts().setScriptTimeout(Integer.parseInt(sModel.getMaxWaitTime()), TimeUnit.SECONDS);
//driver. manage().timeouts().pageLoadTimeout(Integer.parseInt(sModel.getMaxWaitTime()), TimeUnit.SECONDS);
} else if (sModel.getDriver().equalsIgnoreCase("GC")) {
if (StringUtils.isNotBlank(sModel.getFfPath())) {
System.setProperty("webdriver.chrome.driver", sModel.getGcPath().trim());
} else {
String home = System.getenv("chrome.home");
if (home != null && !home.isEmpty()) {
System.setProperty("webdriver.chrome.driver", home);
}
}
driver = new ChromeDriver(capabilities);
} else if (sModel.getDriver().equalsIgnoreCase("Safari")) {
if (StringUtils.isNotBlank(sModel.getSafariPath())) {
System.setProperty("OPERA_PATH", sModel.getSafariPath().trim());
} else {
String home = System.getenv("safari.home");
if (home != null && !home.isEmpty()) {
System.setProperty("OPERA_PATH", home);
}
}
// System.setProperty("webdriver.safari.noinstall", "false");
driver = new OperaDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
driver.manage().deleteAllCookies();
return driver;
}
public static void quitDriver(WebDriver driver) {
if (driver != null) {
driver.quit();
}
}
public static void wait(int sec) {
try {
if (sec <= 0) {
return;
}
Thread.sleep(sec * 1000);
} catch (Throwable ex) {
log.debug("Error in waiting." + ex);
}
}
public static void waitInMiliSecond(int sec) {
try {
if (sec <= 0) {
return;
}
Thread.sleep(sec);
} catch (Throwable ex) {
log.debug("Error in waiting." + ex);
}
}
public static void fireException() throws Exception {
throw new Exception("Unable to find specific component or problem in execution.");
}
public static void fireException(String message) throws Exception {
throw new Exception(message);
}
public static void byButton(WebDriver driver, String tName, String aName, String aValue) throws Exception {
boolean isOff = true;
List<WebElement> elements = driver.findElements(By.tagName(tName));
for (WebElement elementLink : elements) {
if (elementLink.getAttribute(aName) != null
&& elementLink.getAttribute(aName).equalsIgnoreCase(
aValue)) {
elementLink.submit();
isOff = false;
break;
}
}
if (isOff) {
Util.fireException();
}
}
public static void byButton(WebDriver driver, String tId) throws Exception {
WebElement element = driver.findElement(By.id(tId));
element.submit();
}
public static void byClickName(WebDriver driver, String tName, String aName, String aValue) throws Exception {
boolean isOff = true;
List<WebElement> elements = driver.findElements(By.name(tName));
for (WebElement elementLink : elements) {
if (elementLink.getAttribute(aName) != null
&& elementLink.getAttribute(aName).equalsIgnoreCase(
aValue)) {
elementLink.click();
isOff = false;
break;
}
}
if (isOff) {
Util.fireException();
}
}
public static void byClickTag(WebDriver driver, String tName, String aName, String aValue) throws Exception {
boolean isOff = true;
List<WebElement> elements = driver.findElements(By.tagName(tName));
for (WebElement elementLink : elements) {
if (elementLink.getAttribute(aName) != null
&& elementLink.getAttribute(aName).equalsIgnoreCase(
aValue)) {
elementLink.click();
isOff = false;
break;
}
}
if (isOff) {
Util.fireException();
}
}
public static void byClickTag(WebDriver driver, String tID) throws Exception {
WebElement element = driver.findElement(By.id(tID));
if (element == null) {
log.debug(tID + " element not found");
Util.fireException();
}
element.click();
}
public static void sendKeysById(WebDriver driver, String aId, String aValue) throws Exception {
WebElement element = driver.findElement(By.id(aId));
if (element == null) {
log.debug(aId + "element not found.");
Util.fireException();
}
element.sendKeys(aValue);
}
public static void deleteFXTmpDirectory() {
try {
String home = System.getenv("ff.tmpdir");
if (home == null || home.isEmpty()) {
log.debug("Firefox temp directory is not set");
return;
}
File directory = new File(home);
File[] files = directory.listFiles();
for (File file : files) {
if (file.getName().endsWith("webdriver-profile")) {
try {
FileUtils.deleteDirectory(file);
} catch (Throwable ex) {
log.debug("Error on deleting directory named " + file.getName() + " Error " + ex);
}
}
}
} catch (Throwable ex) {
log.debug("Error on deleting directory " + ex);
}
}
public static void updateWorking(SModel sModel, String clID, int work) {
try {
StringBuilder request = new StringBuilder();
request.append("<Request>");
request.append("<username>").append(sModel.getUsername()).append("</username>");
request.append("<password>").append(sModel.getPassword()).append("</password>");
request.append("<country>").append(sModel.getCountry()).append("</country>");
request.append("<id>").append(clID).append("</id>");
request.append("<working>").append(work).append("</working>");
request.append("</Request>");
String req = URLEncoder.encode(request.toString(), "UTF-8");
String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=account/updateWorking";
String param = "request=" + req;
String response = HttpHelper.post(new URL(uri), param);
Document document = DocumentHelper.parseText(response);
String errorCode = document.valueOf("Response/errorcode");
String msg = document.valueOf("Response/message");
log.debug("updateWorking:: update " + msg);
} catch (Throwable ex) {
log.debug("updateWorking: Error " + ex);
}
}
public static void updateNGFXWorking(SModel sModel, String clID, int work) {
try {
StringBuilder request = new StringBuilder();
request.append("<Request>");
request.append("<username>").append(sModel.getUsername()).append("</username>");
request.append("<password>").append(sModel.getPassword()).append("</password>");
request.append("<country>").append(sModel.getCountry()).append("</country>");
request.append("<id>").append(clID).append("</id>");
request.append("<working>").append(work).append("</working>");
request.append("</Request>");
String req = URLEncoder.encode(request.toString(), "UTF-8");
String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=ngfxaccount/updateWorking";
String param = "request=" + req;
String response = HttpHelper.post(new URL(uri), param);
Document document = DocumentHelper.parseText(response);
String errorCode = document.valueOf("Response/errorcode");
String msg = document.valueOf("Response/message");
log.debug("updateWorking:: update " + msg);
} catch (Throwable ex) {
log.debug("updateWorking: Error " + ex);
}
}
public static void updateNetellerWorking(SModel sModel, String clID, int work) {
try {
StringBuilder request = new StringBuilder();
request.append("<Request>");
request.append("<username>").append(sModel.getUsername()).append("</username>");
request.append("<password>").append(sModel.getPassword()).append("</password>");
request.append("<country>").append(sModel.getCountry()).append("</country>");
request.append("<id>").append(clID).append("</id>");
request.append("<working>").append(work).append("</working>");
request.append("</Request>");
String req = URLEncoder.encode(request.toString(), "UTF-8");
String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=netellerAccount/updateWorking";
String param = "request=" + req;
String response = HttpHelper.post(new URL(uri), param);
Document document = DocumentHelper.parseText(response);
String errorCode = document.valueOf("Response/errorcode");
String msg = document.valueOf("Response/message");
log.debug("updateWorking:: update " + msg);
} catch (Throwable ex) {
log.debug("updateWorking: Error " + ex);
}
}
public static Message[] readGmail(String email, String emailPass, INotifier iNotifier) throws Exception {
try {
if (email.contains("+")) {
String[] ee = email.split("\\+");
email = ee[0] + "@gmail.com";
}
if (email == null || email.isEmpty()) {
log.debug("run:: Email address is empty. ");
Util.fireException("Email address is empty.");
}
if (emailPass == null || emailPass.isEmpty()) {
log.debug("run:: Email password is empty. ");
Util.fireException("Email password is empty.");
}
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
/* Create the session and get the store for read the mail. */
//iNotifier.notify("Going to connect mail server");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", email, emailPass);
/* Mention the folder name which you want to read. */
Folder inbox = store.getFolder("Inbox");
int unReadMCount = inbox.getUnreadMessageCount();
//iNotifier.notify("No of Unread Messages : " + unReadMCount);
if (unReadMCount == 0) {
Util.fireException("No of Unread Messages : " + unReadMCount);
}
/* Open the inbox using store. */
//inbox.open(Folder.READ_ONLY);
inbox.open(Folder.READ_WRITE);
/* Get the messages which is unread in the Inbox */
Message messages[] = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
/* Use a suitable FetchProfile */
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.CONTENT_INFO);
inbox.fetch(messages, fp);
try {
inbox.setFlags(messages, new Flags(Flags.Flag.SEEN), true);
inbox.close(true);
store.close();
} catch (Throwable ex) {
log.debug("readMail :: unable to close inbox " + ex);
//iNotifier.notify("Unable to close inbox");
Util.fireException("readMail :: unable to close inbox " + ex);
}
return messages;
} catch (NoSuchProviderException ex) {
log.debug("readMail :: Error on NoSuchProviderException " + ex);
//iNotifier.notify("Exception arise at the time of read mail");
Util.fireException("readMail :: Error on NoSuchProviderException " + ex);
} catch (MessagingException ex) {
log.debug("readMail :: Error on MessagingException " + ex);
//iNotifier.notify("Error on MessagingException "+ex);
Util.fireException("readMail :: Error on MessagingException " + ex);
} catch (Throwable ex) {
log.debug("readMail :: Exception arise at the time of read mai " + ex);
//iNotifier.notify("Exception arise at the time of read mail");
Util.fireException("readMail :: Exception arise at the time of read mail " + ex);
}
return null;
}
public static List<Node> readWebGmail(String email, String emailPass, String wsName, INotifier iNotifier, SModel sModel) throws Exception {
try {
if (email.contains("+")) {
String[] ee = email.split("\\+");
email = ee[0] + "@gmail.com";
}
if (email == null || email.isEmpty()) {
log.debug("run:: Email address is empty. ");
Util.fireException("Email address is empty.");
}
if (emailPass == null || emailPass.isEmpty()) {
log.debug("run:: Email password is empty. ");
Util.fireException("Email password is empty.");
}
StringBuilder param = new StringBuilder();
param.append("username=").append(sModel.getUsername());
param.append("&password=").append(sModel.getPassword());
param.append("&email=").append(email);
param.append("&epassword=").append(emailPass);
String uri = "http://" + IConstant.WEBHOSTNAME + "/maplew/" + wsName;
String response = HttpHelper.post(new URL(uri), param.toString());
Document document = DocumentHelper.parseText(response);
String errorCode = document.valueOf("Response/errorcode");
String msg = document.valueOf("Response/message");
if (!errorCode.equalsIgnoreCase("000")) {
String isLink = document.valueOf("Response/links/mailfound");
if (isLink.equals("0")) {
iNotifier.notify("Posting link not found");
Util.fireException("Posting link not found");
}
return document.selectNodes("/Response/links/link");
} else {
iNotifier.notify("Error " + msg);
Util.fireException("Error on service call " + msg);
}
} catch (Throwable ex) {
log.debug("updateWorking: Error " + ex);
Util.fireException("Error on service call " + ex.getMessage());
}
return null;
}
public static Random getRandom() {
if (random == null) {
random = new Random();
}
return random;
}
public static String getInetAddress() {
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
return sb.toString();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}
return "";
}
public static String getSystemUUID() {
String uuid = "";
try {
// wmic DISKDRIVE get SerialNumber | wmic csproduct get uuid
//Process process = Runtime.getRuntime().exec(new String[] { "wmic", "bios", "get", "serialnumber" });
Process process = Runtime.getRuntime().exec(new String[]{"wmic", "csproduct", "get", "UUID"});
process.getOutputStream().close();
Scanner sc = new Scanner(process.getInputStream());
String property = sc.next();
uuid = sc.next();
} catch (Throwable ex) {
log.error("getMacAddress: " + ex.getMessage());
ex.printStackTrace();
}
return uuid;
}
public static boolean isLoginByMac(String mac) {
try {
String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=userAccount/isLoginByMac&mac=" + mac;
String response = HttpHelper.post(new URL(uri), "");
Document document = DocumentHelper.parseText(response);
String message = document.valueOf("Response/message");
if (message.contains("login")) {
return true;
}
} catch (Throwable ex) {
ex.printStackTrace();
log.error(ex.getMessage());
}
return false;
}
/*
* 0 means only one irobot process alive
* 1 means only one java process alive
* 2 means only multiple irobot process alive
* 3 means multiple java process alive
*/
public static int isAppsRunning() {
try {
int countJavaP = 0;
int countIRobotP = 0;
String line;
Process p = Runtime.getRuntime().exec(System.getenv("windir") + "\\system32\\" + "tasklist.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
if (line.toLowerCase().contains("irobot")) {
countIRobotP = countIRobotP + 1;
}
if (line.toLowerCase().contains("java.exe") || line.toLowerCase().contains("javaw.exe")) {
countJavaP = countJavaP + 1;
}
}
input.close();
if (countIRobotP == 0) {
return 0;
} else if (countIRobotP == 1 && countJavaP <= 3) {
return 1;
} else if (countJavaP == 1) {
return 2;
} else if (countIRobotP > 1) {
return 3;
} else if (countJavaP > 3) {
return 5;
}
} catch (Exception err) {
err.printStackTrace();
}
return 5;
}
public ArrayList<DataModel> readFile(String filePath, INotifier iNotifier) throws Exception {
ArrayList<DataModel> data = new ArrayList<DataModel>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(filePath));
while ((sCurrentLine = br.readLine()) != null) {
DataModel dataModel = new DataModel();
String[] aButes = sCurrentLine.split("\\|");
if (aButes.length == 1) {
dataModel.setCode(aButes[0]);
}
if (aButes.length == 1) {
dataModel.setName(aButes[1]);
}
}
} catch (IOException e) {
e.printStackTrace();
iNotifier.notify("readfile Stopped for error: " + e.getMessage());
log.error("readfile Stopped causes..." + e);
throw new Exception(e);
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return data;
}
public static boolean deleteAdd(SModel _sModel, AdModel adModel, INotifier iNotifier) {
try {
StringBuilder request = new StringBuilder();
request.append("<Request>");
request.append("<id>").append(adModel.getId()).append("</id>");
request.append("<username>").append(_sModel.getUsername()).append("</username>");
request.append("<password>").append(_sModel.getPassword()).append("</password>");
request.append("</Request>");
String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=advertisement/deleteAdvertisement&request=" + request.toString();
String response = HttpHelper.post(new URL(uri), "");
Document document = DocumentHelper.parseText(response);
String errorCode = document.valueOf("Response/errorcode");
String msg = document.valueOf("Response/message");
if (errorCode.equalsIgnoreCase("000")) {
iNotifier.notify("Unable to delete the post.");
return false;
} else {
iNotifier.notify("Post deleted successfully!");
return true;
}
} catch (Exception ex) {
log.debug("Error " + ex);
}
return false;
}
}
| true |
b1c0fb411bb5f890719457aa73dc8cf747141205 | Java | aliceforstudies/ktp_java | /zadachi uroven' 4/U4Z7.java | UTF-8 | 783 | 3.46875 | 3 | [] | no_license | public class U4Z7
{
public static void main(String[] args)
{
System.out.println(toStarShorthand("aaahhhhh888"));
}
public static String toStarShorthand(String str)
{
if (str.isEmpty())
return "";
int j = 1;
char c = str.charAt(0);
String text = "";
for (int i = 1; i < str.length(); i++)
{
if (str.charAt(i) == c)
j++;
else
{
if (j >1 )
text += c + "*"+j;
else
text += c;
c = str.charAt(i);
j = 1;
}
}
if (j>1)
text += c + "*" + j;
else
text += c;
return text;
}
} | true |
3316508b8f4c301e57327a173f721ea07e177a3a | Java | ob1modak/mySpring | /Library/src/main/java/com/hasan/library/user/User.java | UTF-8 | 1,239 | 2.296875 | 2 | [] | no_license | package com.hasan.library.user;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import com.hasan.library.book.Book;
@Entity
public class User {
@Id
@GeneratedValue
private long id;
@Column(name="first_name")
private String fName;
@Column(name="last_name") // only if you want to give a different table name
private String lName;
private String email;
private Integer uType;
@OneToMany(mappedBy="user")
private List<Book> books;
public User() {
}
public long getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getuType() {
return uType;
}
public void setuType(Integer uType) {
this.uType = uType;
}
}
| true |
ad930c5e5c1100458e29387ce2df051c68d5e7ef | Java | pickerss/pmd_STANly | /src/main/java/net/sourceforge/pmd/lang/java/rule/stanly/metrics/MethodMetric.java | UTF-8 | 392 | 2.15625 | 2 | [] | no_license | package net.sourceforge.pmd.lang.java.rule.stanly.metrics;
public class MethodMetric {
private int LOC;
private int CC;
public int getLOC() {
return LOC;
}
public void setLOC(int lOC) {
LOC = lOC;
}
public int getCC() {
return CC == 0 ? 1 : CC;
}
public void addCC(int cC) {
CC += cC;
}
public void addLOC(int i) {
// TODO Auto-generated method stub
LOC += i;
}
}
| true |
d34f6ddeb5e3a30a0aa8fe82fd5e6677df1c2ec1 | Java | inessgil/moviedbapp | /data/src/main/java/com/ia/data/repository/datasource/local/room/model/daos/GenreDAO.java | UTF-8 | 724 | 2.1875 | 2 | [] | no_license | package com.ia.data.repository.datasource.local.room.model.daos;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import com.ia.data.repository.datasource.local.room.model.entities.GenreEntity;
import java.util.List;
@Dao
public interface GenreDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
public void insertGenre (GenreEntity genreEntity);
@Insert(onConflict = OnConflictStrategy.REPLACE)
public void insertGenreList (List<GenreEntity> genreEntityList);
@Query("SELECT * FROM GenreEntity WHERE id = :id")
public GenreEntity getGenre (int id);
}
| true |
e8b24f306380760f848a4424b6004a25244300cb | Java | skillsapphire/rent-collect-be | /src/main/java/com/rentcompany/rentcollect/exception/ResourceAlreadyExist.java | UTF-8 | 373 | 2.296875 | 2 | [] | no_license | package com.rentcompany.rentcollect.exception;
public class ResourceAlreadyExist extends Exception {
private Error error;
public ResourceAlreadyExist(){
}
public ResourceAlreadyExist(String code, String msg){
error = new Error();
error.setErrorCode(code);
error.setErrorMessage(msg);
}
public Error getError() {
return error;
}
} | true |
c41d6b679a8a43298a61bfbf24b1dea1e5b5e628 | Java | zhangwuji123/test | /src/main/java/com/cloud/operation/action/CiStorageSubAction.java | UTF-8 | 11,177 | 1.835938 | 2 | [] | no_license | package com.cloud.operation.action;
import java.io.ByteArrayOutputStream;
import javax.annotation.Resource;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cloud.operation.core.action.BaseAction;
import com.cloud.operation.core.exception.ServiceException;
import com.cloud.operation.core.form.CiStorageSubForm;
import com.cloud.operation.core.page.Page;
import com.cloud.operation.core.utils.MessageUtil;
import com.cloud.operation.core.vo.DataVO;
import com.cloud.operation.db.entity.business.CiExtProperty;
import com.cloud.operation.db.entity.business.CiStorageSub;
import com.cloud.operation.db.entity.business.CiStorageSubRecord;
import com.cloud.operation.service.ICiStorageSubService;
/**
* 配置存储子表控制器
*
* @author syd
*
*/
@Controller
@RequestMapping("/ciStorageSub")
public class CiStorageSubAction extends
BaseAction<CiStorageSubForm, CiStorageSub> {
@Resource
private ICiStorageSubService ciStorageSubService;
@Override
@ResponseBody
@RequestMapping(value = "/pageList", method = RequestMethod.POST)
@RequiresPermissions("ciStorageSub:read")
public Page<CiStorageSub> pageList(@RequestBody CiStorageSubForm f) {
Page<CiStorageSub> page = new Page<CiStorageSub>();
try {
page = ciStorageSubService.findPageList(f);
page.setState(ResponseState.SUCCESS.getValue());
return page;
} catch (ServiceException e) {
logger.error(e.getMessage(), e);
page.setState(ResponseState.FAILURE.getValue());
page.setMessage(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage(), e);
page.setState(ResponseState.FAILURE.getValue());
page.setMessage(MessageUtil.SYS_EXCEPTION);
}
return page;
}
@Override
@ResponseBody
@RequestMapping(value = "/list", method = RequestMethod.POST)
@RequiresPermissions("ciStorageSub:read")
public DataVO<CiStorageSub> list(@RequestBody CiStorageSubForm f) {
DataVO<CiStorageSub> vo = new DataVO<CiStorageSub>();
try {
vo.setList(ciStorageSubService.findList(f));
vo.setState(ResponseState.SUCCESS.getValue());
return vo;
} catch (ServiceException e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(MessageUtil.SYS_EXCEPTION);
}
return vo;
}
@Override
@ResponseBody
@RequestMapping(value = "/load", method = RequestMethod.POST)
@RequiresPermissions("ciStorageSub:read")
public DataVO<CiStorageSub> load(@RequestBody CiStorageSubForm f) {
DataVO<CiStorageSub> vo = new DataVO<CiStorageSub>();
try {
vo.setT(ciStorageSubService.findById(f.getUuid()));
vo.setState(ResponseState.SUCCESS.getValue());
} catch (ServiceException e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(MessageUtil.SYS_EXCEPTION);
}
return vo;
}
@Override
@ResponseBody
@RequestMapping(value = "/save", method = RequestMethod.POST)
@RequiresPermissions("ciStorageSub:write")
public DataVO<CiStorageSub> save(@RequestBody CiStorageSubForm f) {
DataVO<CiStorageSub> vo = new DataVO<CiStorageSub>();
try {
if (RequestAction.INSERT.getValue().equalsIgnoreCase(f.getAction())) {
ciStorageSubService.insert(f);
vo.setState(ResponseState.SUCCESS.getValue());
vo.setMessage("添加存储子表成功");
} else if (RequestAction.UPDATE.getValue().equalsIgnoreCase(
f.getAction())) {
ciStorageSubService.updateFromForm(f);
vo.setState(ResponseState.SUCCESS.getValue());
vo.setMessage("修改存储子表成功");
}
} catch (ServiceException e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(MessageUtil.SYS_EXCEPTION);
}
return vo;
}
@Override
@ResponseBody
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@RequiresPermissions("ciStorageSub:write")
public DataVO<CiStorageSub> delete(@RequestBody CiStorageSubForm f) {
DataVO<CiStorageSub> vo = new DataVO<CiStorageSub>();
try {
ciStorageSubService.deleteById(f.getUuid());
vo.setState(ResponseState.SUCCESS.getValue());
vo.setMessage("删除存储子表成功");
} catch (ServiceException e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(MessageUtil.SYS_EXCEPTION);
}
return vo;
}
@Override
@ResponseBody
@RequestMapping(value = "/deletes", method = RequestMethod.POST)
@RequiresPermissions("ciStorageSub:write")
public DataVO<CiStorageSub> deletes(@RequestBody CiStorageSubForm f) {
DataVO<CiStorageSub> vo = new DataVO<CiStorageSub>();
try {
ciStorageSubService.deletes(f.getUuids());
vo.setState(ResponseState.SUCCESS.getValue());
vo.setMessage("删除存储子表成功");
} catch (ServiceException e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(MessageUtil.SYS_EXCEPTION);
}
return vo;
}
@Override
public Boolean validate(CiStorageSubForm f) {
return null;
}
@ResponseBody
@RequestMapping(value = "/imports", method = RequestMethod.POST)
@RequiresPermissions("ciStorageSub:write")
public DataVO<CiStorageSub> imports(@RequestBody CiStorageSubForm f) {
DataVO<CiStorageSub> vo = new DataVO<CiStorageSub>();
try {
ciStorageSubService.imports(f);
vo.setState(ResponseState.SUCCESS.getValue());
vo.setMessage("存储子表导入成功");
} catch (ServiceException e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(MessageUtil.SYS_EXCEPTION);
}
return vo;
}
@ResponseBody
@RequestMapping(value = "/exports", method = RequestMethod.POST)
public ResponseEntity<byte[]> exports(CiStorageSubForm f) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
String filename = ciStorageSubService.exports(f, os);
headers.setContentDispositionFormData("attachment", new String(
filename.getBytes(), "iso-8859-1"));
return new ResponseEntity<byte[]>(os.toByteArray(), headers,
HttpStatus.CREATED);
} catch (Exception e) {
e.printStackTrace();
}
return new ResponseEntity<byte[]>(os.toByteArray(), headers,
HttpStatus.CREATED);
}
@ResponseBody
@RequestMapping(value = "/empty", method = RequestMethod.POST)
@RequiresPermissions("ciStorageSub:write")
public DataVO<CiStorageSub> empty() {
DataVO<CiStorageSub> vo = new DataVO<CiStorageSub>();
try {
ciStorageSubService.empty();
vo.setState(ResponseState.SUCCESS.getValue());
vo.setMessage("存储子表清空成功");
} catch (ServiceException e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(MessageUtil.SYS_EXCEPTION);
}
return vo;
}
@ResponseBody
@RequestMapping(value = "/recordList", method = RequestMethod.POST)
@RequiresPermissions("ciStorageSub:read")
public DataVO<CiStorageSubRecord> recordList(
@RequestBody CiStorageSubForm f) {
DataVO<CiStorageSubRecord> vo = new DataVO<CiStorageSubRecord>();
try {
vo.setData(ciStorageSubService.recordList(f));
vo.setState(ResponseState.SUCCESS.getValue());
} catch (ServiceException e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(MessageUtil.SYS_EXCEPTION);
}
return vo;
}
@ResponseBody
@RequestMapping(value = "/recordPageList", method = RequestMethod.POST)
@RequiresPermissions("ciStorageSub:read")
public Page<CiStorageSubRecord> recordPageList(@RequestBody CiStorageSubForm f) {
Page<CiStorageSubRecord> page = new Page<CiStorageSubRecord>();
try {
page = ciStorageSubService.recordPageList(f);
page.setState(ResponseState.SUCCESS.getValue());
return page;
} catch (ServiceException e) {
logger.error(e.getMessage(), e);
page.setState(ResponseState.FAILURE.getValue());
page.setMessage(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage(), e);
page.setState(ResponseState.FAILURE.getValue());
page.setMessage(MessageUtil.SYS_EXCEPTION);
}
return page;
}
@ResponseBody
@RequestMapping(value = "/recordExports", method = RequestMethod.POST)
public ResponseEntity<byte[]> recordExports() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
String filename = ciStorageSubService.recordExports(os);
headers.setContentDispositionFormData("attachment", new String(
filename.getBytes(), "iso-8859-1"));
return new ResponseEntity<byte[]>(os.toByteArray(), headers,
HttpStatus.CREATED);
} catch (Exception e) {
e.printStackTrace();
}
return new ResponseEntity<byte[]>(os.toByteArray(), headers,
HttpStatus.CREATED);
}
@ResponseBody
@RequestMapping(value = "/initExtProperty", method = RequestMethod.POST)
@RequiresPermissions("ciStorageSub:read")
public DataVO<CiExtProperty> initExtProperty() {
DataVO<CiExtProperty> vo = new DataVO<CiExtProperty>();
try {
vo.setList(ciStorageSubService.initExtProperty());
vo.setState(ResponseState.SUCCESS.getValue());
} catch (ServiceException e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage(), e);
vo.setState(ResponseState.FAILURE.getValue());
vo.setMessage(MessageUtil.SYS_EXCEPTION);
}
return vo;
}
}
| true |
7ce03e8297cbff023951254e48800b5d2722fcbf | Java | joeltorres4/Big-Numbers-Calculator | /p2_4035_152/src/stack/IntStack.java | UTF-8 | 1,903 | 4.0625 | 4 | [] | no_license | package stack;
import exceptions.EmptyStackException;
import exceptions.FullStackException;
/**
* Represent IntStack objects, a similar implementation of Stack
*
* @author Pedro I. Rivera Vega
*
*/
public class IntStack {
private static final int DS = 10; // stack's default capacity
private int[] element; // the stack's content
private int top;
/**
* Default constructor
*/
public IntStack() {
element = new int[DS];
top = -1;
}
/**
* IntStack constructor with parameter size
*
* @param s
* size to set to stack
*/
public IntStack(int s) {
if (s <= 0)
s = DS;
element = new int[s];
top = -1;
}
/**
* Determines if "stack" is empty
*
* @return true if empty, false otherwise
*/
public boolean isEmpty() {
return top == -1;
}
/**
* Returns current size of "stack"
*
* @return current size
*/
public int size() {
return top + 1;
}
/**
* Removes top element
*
* @return element at top
* @throws EmptyStackException
* thrown when working with an empty stack
*/
public int pop() throws EmptyStackException {
if (isEmpty())
throw new EmptyStackException();
return element[top--];
}
/**
* Push new element
*
* @param n
* element to push
* @throws FullStackException
* thrown when working with full stack
*/
public void push(int n) throws FullStackException {
if (top == element.length - 1)
throw new FullStackException("Full stack in push...");
else
element[++top] = n;
}
/**
* Returns top element
*
* @return top element
* @throws EmptyStackException
* thrown when working with empty stack
*/
public int top() throws EmptyStackException {
if (isEmpty())
throw new EmptyStackException();
return element[top];
}
}
| true |
ca245d4a82c04b2751b2643bb930daefbf538f96 | Java | codehaus/drools | /drools/drools-jsr94/src/main/org/drools/jsr94/rules/RuleExecutionSetMetadataImpl.java | UTF-8 | 3,916 | 2.1875 | 2 | [] | no_license | package org.drools.jsr94.rules;
/*
* $Id: RuleExecutionSetMetadataImpl.java,v 1.7 2004-11-28 03:34:05 simon Exp $
*
* Copyright 2004 (C) The Werken Company. All Rights Reserved.
*
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain copyright statements and
* notices. Redistributions must also contain a copy of this document.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name "drools" must not be used to endorse or promote products derived
* from this Software without prior written permission of The Werken Company.
* For written permission, please contact bob@werken.com.
*
* 4. Products derived from this Software may not be called "drools" nor may
* "drools" appear in their names without prior written permission of The Werken
* Company. "drools" is a registered trademark of The Werken Company.
*
* 5. Due credit should be given to The Werken Company.
* (http://drools.werken.com/).
*
* THIS SOFTWARE IS PROVIDED BY THE WERKEN COMPANY AND CONTRIBUTORS ``AS IS''
* AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE WERKEN COMPANY OR ITS CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
import javax.rules.RuleExecutionSetMetadata;
/**
* The Drools implementation of the <code>RuleExecutionSetMetadata</code>
* interface which exposes some simple properties of the
* <code>RuleExecutionSet</code> to the runtime user.
*
* @see RuleExecutionSetMetadata
*/
public class RuleExecutionSetMetadataImpl implements RuleExecutionSetMetadata
{
/** The URI for this <code>RuleExecutionSet</code>. */
private final String uri;
/** The name of this RuleExecutionSet. */
private final String name;
/** The description of this <code>RuleExecutionSet</code>. */
private final String description;
/**
* Constructs an instance of <code>RuleExecutionSetMetadata</code>.
*
* @param uri The URI for this <code>RuleExecutionSet</code>.
* @param name The name of this <code>RuleExecutionSet</code>.
* @param description The description of this <code>RuleExecutionSet</code>.
*/
public RuleExecutionSetMetadataImpl(
String uri, String name, String description )
{
this.uri = uri;
this.name = name;
this.description = description;
}
/**
* Get the URI for this <code>RuleExecutionSet</code>.
*
* @return The URI for this <code>RuleExecutionSet</code>.
*/
public String getUri( )
{
return this.uri;
}
/**
* Get the name of this <code>RuleExecutionSet</code>.
*
* @return The name of this <code>RuleExecutionSet</code>.
*/
public String getName( )
{
return this.name;
}
/**
* Get a short description about this <code>RuleExecutionSet</code>.
*
* @return The description of this <code>RuleExecutionSet</code>
* or <code>null</code>.
*/
public String getDescription( )
{
return this.description;
}
}
| true |
a9ce960315052198b5bb3570cc0d18f8d9b46ae3 | Java | italiangrid/storm | /src/test/java/it/grid/storm/balancer/cache/ResponsivenessCacheTest.java | UTF-8 | 2,124 | 2.1875 | 2 | [] | no_license | package it.grid.storm.balancer.cache;
import static it.grid.storm.balancer.cache.Responsiveness.RESPONSIVE;
import static it.grid.storm.balancer.cache.Responsiveness.UNRESPONSIVE;
import static it.grid.storm.config.Configuration.CONFIG_FILE_PATH;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import it.grid.storm.balancer.BalancerUtils;
import it.grid.storm.balancer.Node;
public class ResponsivenessCacheTest extends BalancerUtils {
static {
System.setProperty(CONFIG_FILE_PATH, "storm.properties");
}
private final ResponsivenessCache CACHE = ResponsivenessCache.INSTANCE;
@Before
public void initCache() {
CACHE.invalidate();
}
@Test
public void testCaching() {
Node https1 = getResponsiveHttpsNode(1, "dav01.example.org", 8443);
Node https2 = getUnresponsiveHttpsNode(2, "dav02.example.org", 8443);
Node http1 = getResponsiveHttpNode(3, "dav01.example.org", 8085);
Node http2 = getUnresponsiveHttpNode(4, "dav02.example.org", 8085);
Node ftp1 = getResponsiveFtpNode(5, "ftp01.example.org", 2811);
Node ftp2 = getUnresponsiveFtpNode(6, "ftp02.example.org", 2811);
assertFalse(CACHE.isCached(https1));
assertFalse(CACHE.isCached(https2));
assertFalse(CACHE.isCached(http1));
assertFalse(CACHE.isCached(http2));
assertFalse(CACHE.isCached(ftp1));
assertFalse(CACHE.isCached(ftp2));
assertEquals(RESPONSIVE, CACHE.getResponsiveness(https1));
assertTrue(CACHE.isCached(https1));
assertEquals(UNRESPONSIVE, CACHE.getResponsiveness(https2));
assertTrue(CACHE.isCached(https2));
assertEquals(RESPONSIVE, CACHE.getResponsiveness(http1));
assertTrue(CACHE.isCached(http1));
assertEquals(UNRESPONSIVE, CACHE.getResponsiveness(http2));
assertTrue(CACHE.isCached(http2));
assertEquals(RESPONSIVE, CACHE.getResponsiveness(ftp1));
assertTrue(CACHE.isCached(ftp1));
assertEquals(UNRESPONSIVE, CACHE.getResponsiveness(ftp2));
assertTrue(CACHE.isCached(ftp2));
}
}
| true |
b18af71965f7484cdcaf5021d6d4dd4d75d77e4f | Java | telmperez/linkedin-j-modified | /core/src/test/java/com/google/code/linkedinapi/schema/xml/TestXMLFiles.java | UTF-8 | 3,016 | 1.828125 | 2 | [] | no_license | /*
* Copyright 2010-2011 Nabeel Mukhtar
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.google.code.linkedinapi.schema.xml;
import java.io.IOException;
import java.util.Properties;
/**
* @author Nabeel Mukhtar
*
*/
public final class TestXMLFiles {
/** Field description */
public static final String TEST_XML_FILES = "TestXMLFiles.properties";
/** Field description */
private static final Properties testXmlFiles = new Properties();
static {
try {
testXmlFiles.load(TestXMLFiles.class.getResourceAsStream(TEST_XML_FILES));
} catch (IOException e) {
e.printStackTrace();
}
}
/** Field description */
public static final String LINKED_IN_SCHEMA_UPDATE_STATUS_XML =
testXmlFiles.getProperty("com.google.code.linkedinapi.schema.xml.updateCurrentStatus");
/** Field description */
public static final String LINKED_IN_SCHEMA_UPDATE_NETWORK_UPDATE_XML =
testXmlFiles.getProperty("com.google.code.linkedinapi.schema.xml.updateNetworkUpdate");
/** Field description */
public static final String LINKED_IN_SCHEMA_UPDATE_COMMENT_XML =
testXmlFiles.getProperty("com.google.code.linkedinapi.schema.xml.updateComment");
/** Field description */
public static final String LINKED_IN_SCHEMA_SEND_MESSAGE_XML =
testXmlFiles.getProperty("com.google.code.linkedinapi.schema.xml.sendMessage");
/** Field description */
public static final String LINKED_IN_SCHEMA_SEND_INVITE_XML =
testXmlFiles.getProperty("com.google.code.linkedinapi.schema.xml.sendInvite");
/** Field description */
public static final String LINKED_IN_SCHEMA_SEARCH_XML =
testXmlFiles.getProperty("com.google.code.linkedinapi.schema.xml.search");
/** Field description */
public static final String LINKED_IN_SCHEMA_PROFILE_XML =
testXmlFiles.getProperty("com.google.code.linkedinapi.schema.xml.profile");
/** Field description */
public static final String LINKED_IN_SCHEMA_NETWORK_UPDATES_XML =
testXmlFiles.getProperty("com.google.code.linkedinapi.schema.xml.networkUpdates");
/** Field description */
public static final String LINKED_IN_SCHEMA_CONNECTIONS_XML =
testXmlFiles.getProperty("com.google.code.linkedinapi.schema.xml.connections");
/**
* Constructs ...
*
*/
private TestXMLFiles() {}
}
| true |
58ac77e5d79c8729754797a7e57dc1b84b4a9325 | Java | yzx2786404067/bookInfo | /src/main/java/com/ycjw/bookInfo/controller/book/OpBookController.java | UTF-8 | 1,663 | 2.25 | 2 | [] | no_license | package com.ycjw.bookInfo.controller.book;
import com.ycjw.bookInfo.exception.ExceptionZyc;
import com.ycjw.bookInfo.model.response.Response;
import com.ycjw.bookInfo.service.book.OpBookService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("opBook")
public class OpBookController {
@Autowired
OpBookService opBookService;
@ApiOperation("借书")
@PostMapping("borrow")
public Response borrowBook(@RequestParam("userId") String userId,
@RequestParam("bookId") String bookId) throws ExceptionZyc{
return new Response("借书成功", opBookService.borrowBook(userId, bookId));
}
@ApiOperation("还书")
@PostMapping("return")
public Response returnBook(@RequestParam("borrowRecordId") String borrowRecordId) throws ExceptionZyc{
return new Response("还书成功",opBookService.returnBook(borrowRecordId));
}
@ApiOperation("赔付")
@PostMapping("pay")
public Response payBookMoney(@RequestParam("borrowRecordId") String borrowRecordId,
@RequestParam("payMoney")double payMoney) throws ExceptionZyc{
return new Response("赔付成功",opBookService.payBookMoney(borrowRecordId,payMoney));
}
@ApiOperation("查询未处理的借阅列表")
@GetMapping("findAllBorrowBooks")
public Response getAllBorrowBooks(@RequestParam("userId") String userId) throws ExceptionZyc{
return new Response("查询成功",opBookService.getAllBorrowBooks(userId));
}
}
| true |
b102639d83bb20ca5936fafb11af8b524a9503de | Java | VeraAPACS3000/2020-05-otus-spring-project-work-mrykina | /FinancialDistribution/src/main/java/ru/otus/spring/FinancialDistribution/configuration/SwaggerConfig.java | UTF-8 | 1,918 | 1.929688 | 2 | [] | no_license | package ru.otus.spring.FinancialDistribution.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.Arrays;
//http://localhost:8080/swagger-ui/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("ru.otus.spring.FinancialDistribution.restcontrollers"))
.build()
// .securityContexts(Arrays.asList(securityContext()))
// .securitySchemes(Arrays.asList(basicAuthScheme()))
.apiInfo(apiInfo());
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(Arrays.asList(basicAuthReference()))
.build();
}
private SecurityScheme basicAuthScheme() {
return new BasicAuth("basicAuth");
}
private SecurityReference basicAuthReference() {
return new SecurityReference("basicAuth", new AuthorizationScope[0]);
}
private ApiInfo apiInfo() {
Contact contact = new Contact("Vera Mrykina", "", "LeraZoom@yahoo.com");
return new ApiInfoBuilder().title("API by Mrykina")
.description("API Project Financial Distribution")
.termsOfServiceUrl("https://otus.ru")
.contact(contact).version("1.0").build();
}
} | true |
9883d99300e933afc2d277e8e3d3b9664b0e381f | Java | lukinocomm/Ristorante | /src/CalcolaOrdinazioniInCorso.java | UTF-8 | 460 | 2.5 | 2 | [] | no_license |
public class CalcolaOrdinazioniInCorso implements IOperazioneSuOrdinazione {
private Contatore contatore;
public CalcolaOrdinazioniInCorso(Contatore contatore){
this.contatore=contatore;
}
@Override
public void applicaOperazione(OrdinazioneInCorso oic) {
this.contatore.incrementaContatoreDiUnUnita();
}
@Override
public void applicaOperazione(OrdinazioneNonInCorso onic) {
// TODO Auto-generated method stub
}
}
| true |
4b07055b46f22f95b498372c98e108c7423a6c02 | Java | raejun/mini_prj | /java_gui/prj1/src/gui2/MyPanel1.java | UHC | 1,517 | 3.078125 | 3 | [] | no_license | package gui2;
import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
public class MyPanel1 extends JPanel implements MouseListener {
JTable table;
public MyPanel1() {
setLayout(new BorderLayout());
String[] columns = {"", "а", ""};
String[][] data = {
{ "ȫ浿", "", "Java" },
{ "", "ڰ", "XML" },
{ "", "", "Spring" }
};
DefaultTableModel model = new DefaultTableModel(data, columns);
table = new JTable(model);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.addMouseListener(this);
JScrollPane pane = new JScrollPane(table);
add(pane, BorderLayout.CENTER);
}//
@Override
public void mouseClicked(MouseEvent e) {
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
System.out.println("row=" + row + ", column=" + column);
String str = (String) table.getValueAt(row, column);
System.out.println("=" + str);
if(str.equals("ȫ浿")) {
System.out.println("aaaa");
}
}//mouseClicked
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
}//end | true |
7ce5c9ddb1a22ad9f749c77e033dc006c733fa6e | Java | Direct-Entry-Program-Dulanga/DataStructure-LinkedList | /src/Singly.java | UTF-8 | 2,035 | 3.71875 | 4 | [] | no_license | public class Singly {
//create first object
private Node firstNode;
private Node lastNode;
int c = 0;
public void add(int number){
Node newnode = new Node(number);
if(firstNode==null){
firstNode = newnode;
lastNode = newnode;
}else{
lastNode.next = newnode;
lastNode = newnode;
}
}
public void add(int index,int number){
Node newnode2 = new Node(number);
if(index > size() || index < 0){
throw new RuntimeException("Invalid linked exception");
}
for (int i = 0; i < size(); i++) {
if(i <= index){
firstNode.next = newnode2;
newnode2.next = lastNode;
}
}
}
public void remove(int index){
if(index >= size() || index< 0){
throw new RuntimeException("Invalid list index");
}
if (size() ==0){
clear();
return;
}
}
public int get(int index){
int temp = 0;
if (index >= size() || index < 0){
throw new RuntimeException("Invalid index");
}
while(size() != index){
temp = firstNode.number;
System.out.println(temp);
}
return temp;
}
public void print(){
Node currentNode = firstNode;
if(firstNode == null){
System.out.println("List of Empty");
}
System.out.print("Singly linked list: [ ");
while (currentNode != null){
System.out.print(currentNode.number + " ");
currentNode = currentNode.next;
c=c+1;
}
System.out.println("]");
}
public void clear(){
lastNode = null;
firstNode = null;
}
public int size(){
return c;
}
public boolean contains(int number){
return true;
}
public boolean empty(){
return (firstNode == null);
}
}
| true |
3c0bf85a5a333d25449d1c72006ca7249af70e9d | Java | dalzymendoza/twu-biblioteca-dalzy | /src/com/twu/biblioteca/representations/LibraryItem.java | UTF-8 | 1,645 | 3.015625 | 3 | [
"Apache-2.0"
] | permissive | package com.twu.biblioteca.representations;
import com.twu.biblioteca.exceptions.AvailableLibraryItemException;
import com.twu.biblioteca.exceptions.UnavailableLibraryItemException;
public abstract class LibraryItem {
private int id;
private String title;
private boolean availability;
private User checkedOutBy;
public LibraryItem(int id, String title) {
this.id = id;
this.title = title;
this.availability = true;
this.checkedOutBy = null;
}
public abstract String getExtraDetailsPrintFormat();
public String getLibraryItemOptionPrintFormat() {
return "[" + id + "] " + title;
}
public boolean getAvailability() {
return availability;
}
public String getTitle(){
return title;
}
public User getCheckedOutBy() {
return checkedOutBy;
}
public int getId() {
return id;
}
public void checkoutItem(User checkedOutBy) throws UnavailableLibraryItemException {
if(availability) {
this.availability = false;
this.checkedOutBy = checkedOutBy;
}
else {
throw new UnavailableLibraryItemException();
}
}
public void returnItem() throws AvailableLibraryItemException {
if (availability) {
throw new AvailableLibraryItemException();
}
else {
this.availability = true;
this.checkedOutBy = null;
}
}
public String getAdminDetailsPrintFormat() {
return "Title: " + title + "\n" + "Checked out by: " + checkedOutBy.getUsername() + "\n";
}
}
| true |
a8a6c8a248d5f7824709dd1535801073ec4d1340 | Java | Faceunity/FUZegoLiveDemoDroid | /joinLive/src/main/java/com/zego/joinlive/ui/JoinLiveAudienceUI.java | UTF-8 | 27,236 | 1.8125 | 2 | [] | no_license | package com.zego.joinlive.ui;
import android.app.Activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;
import com.zego.common.ZGBaseHelper;
import com.zego.common.entity.SDKConfigInfo;
import com.zego.common.ui.BaseActivity;
import com.zego.common.util.AppLogger;
import com.zego.common.util.ZegoUtil;
import com.zego.common.widgets.CustomDialog;
import com.zego.joinlive.R;
import com.zego.joinlive.ZGJoinLiveHelper;
import com.zego.joinlive.constants.JoinLiveView;
import com.zego.joinlive.databinding.ActivityJoinLiveAudienceBinding;
import com.zego.zegoliveroom.callback.IZegoAudioRouteCallback;
import com.zego.zegoliveroom.callback.IZegoLivePlayerCallback;
import com.zego.zegoliveroom.callback.IZegoLivePublisherCallback;
import com.zego.zegoliveroom.callback.IZegoLoginCompletionCallback;
import com.zego.zegoliveroom.callback.IZegoRoomCallback;
import com.zego.zegoliveroom.constants.ZegoConstants;
import com.zego.zegoliveroom.constants.ZegoVideoViewMode;
import com.zego.zegoliveroom.entity.ZegoPlayStreamQuality;
import com.zego.zegoliveroom.entity.ZegoPublishStreamQuality;
import com.zego.zegoliveroom.entity.ZegoStreamInfo;
import java.util.ArrayList;
import java.util.HashMap;
/**
* 观众界面以及拉主播流/连麦者流、推流的一些操作
* 1. 此 demo 未展示观众向主播申请连麦的一个过程,观众点击"视频连麦"则和主播进行连麦,不用经过主播的同意
* 用户可根据自己的实际业务需求,增加观众向主播进行连麦申请的操作(发送信令实现),在收到主播同意连麦的信令后再推流。
* 2. 此 demo 未展示主播邀请观众连麦的过程,只能观众自行上麦即推流
* 用户可根据业务需求,增加主播邀请观众连麦信令的收发处理,比如主播向观众发送邀请连麦的信令后,观众在收到主播的邀请连麦信令同意之后才推流,实现观众与主播连麦。
*/
public class JoinLiveAudienceUI extends BaseActivity {
private ActivityJoinLiveAudienceBinding binding;
// SDK配置,麦克风和摄像头
private SDKConfigInfo sdkConfigInfo = new SDKConfigInfo();
// 主播房间ID
private String mRoomID;
// 主播ID
private String mAnchorID;
// 推流流名
private String mPublishStreamID = ZegoUtil.getPublishStreamID();
// 是否连麦
private boolean isJoinedLive = false;
// 已拉流流名列表
private ArrayList<String> mPlayStreamIDs = new ArrayList<>();
// 大view
private JoinLiveView mBigView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_join_live_audience);
binding.setConfig(sdkConfigInfo);
mRoomID = getIntent().getStringExtra("roomID");
mAnchorID = getIntent().getStringExtra("anchorID");
// 设置当前 UI 界面左上角的点击事件,点击之后结束当前 Activity 并停止拉流/推流、退出房间
binding.goBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
// 监听摄像头开关
binding.swCamera.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isPressed()) {
sdkConfigInfo.setEnableCamera(isChecked);
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().enableCamera(isChecked);
}
}
});
// 监听麦克风开关
binding.swMic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isPressed()) {
sdkConfigInfo.setEnableMic(isChecked);
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().enableMic(isChecked);
}
}
});
// 设置拉流的视图列表
initViewList();
// 设置SDK相关的回调监听
initSDKCallback();
// 登录房间并拉流
startPlay();
}
@Override
public void finish(){
super.finish();
// 停止正在拉的流
if (mPlayStreamIDs.size() > 0) {
for (String streamID : mPlayStreamIDs) {
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().stopPlayingStream(streamID);
}
}
// 清空拉流列表
mPlayStreamIDs.clear();
// 退出页面时如果是连麦状态则停止推流
if (isJoinedLive) {
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().stopPublishing();
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().stopPreview();
isJoinedLive = false;
}
// 设置所有视图可用
ZGJoinLiveHelper.sharedInstance().freeAllJoinLiveView();
// 退出房间
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().logoutRoom();
// 去除SDK相关的回调监听
releaseSDKCallback();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
// 设置拉流的视图列表
protected void initViewList(){
// 全屏视图用于展示主播流
mBigView = new JoinLiveView(binding.playView, false, "");
mBigView.setZegoLiveRoom(ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom());
// 添加可用的连麦者视图,共三个视图
ArrayList<JoinLiveView> mJoinLiveView = new ArrayList<>();
final JoinLiveView view1 = new JoinLiveView(binding.audienceViewOne, false, "");
view1.setZegoLiveRoom(ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom());
final JoinLiveView view2 = new JoinLiveView(binding.audienceViewTwo, false, "");
view2.setZegoLiveRoom(ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom());
final JoinLiveView view3 = new JoinLiveView(binding.audienceViewThree, false, "");
view3.setZegoLiveRoom(ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom());
mJoinLiveView.add(mBigView);
mJoinLiveView.add(view1);
mJoinLiveView.add(view2);
mJoinLiveView.add(view3);
ZGJoinLiveHelper.sharedInstance().addTextureView(mJoinLiveView);
/**
* 设置视图的点击事件
* 点击小视图时,切换到大视图上展示画面,大视图的画面展示到小视图上
*/
view1.textureView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
view1.exchangeView(mBigView);
}
});
view2.textureView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
view2.exchangeView(mBigView);
}
});
view3.textureView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
view3.exchangeView(mBigView);
}
});
}
/**
* 连麦/结束连麦
* 此 demo 中不展示观众向主播申请连麦的一个过程,观众点击连麦则和主播进行连麦,不用经过主播的同意
* 用户可根据自己的实际业务需求,增加观众向主播进行连麦申请的操作(发送信令实现),在收到主播同意连麦的信令后再推流
*/
public void onClickApplyJoinLive(View view){
if (binding.btnApplyJoinLive.getText().toString().equals(getString(R.string.tx_joinLive))){
// button 说明为"视频连麦"时,执行推流的操作
if (mPlayStreamIDs.size() == ZGJoinLiveHelper.MaxJoinLiveNum + 1){
// 判断连麦人数是否达到上限,此demo只支持展示三人连麦;达到连麦上限时的拉流总数 = 1条主播流 + 三条连麦者的流
Toast.makeText(JoinLiveAudienceUI.this, getString(R.string.join_live_count_overflow), Toast.LENGTH_SHORT).show();
} else {
// 不满足上述情况则开始连麦,即推流
// 获取可用的视图
JoinLiveView freeView = ZGJoinLiveHelper.sharedInstance().getFreeTextureView();
if (freeView != null){
// 设置预览视图模式,此处采用 SDK 默认值--等比缩放填充整View,可能有部分被裁减。
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().setPreviewViewMode(ZegoVideoViewMode.ScaleAspectFill);
// 设置预览 view
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().setPreviewView(freeView.textureView);
// 启动预览
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().startPreview();
// 开始推流,flag 使用连麦场景
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().startPublishing(mPublishStreamID, "audienceJoinLive", ZegoConstants.PublishFlag.JoinPublish);
// 修改视图信息
freeView.streamID = mPublishStreamID;
freeView.isPublishView = true;
ZGJoinLiveHelper.sharedInstance().modifyTextureViewInfo(freeView);
} else {
Toast.makeText(JoinLiveAudienceUI.this, getString(R.string.has_no_textureView), Toast.LENGTH_LONG).show();
}
}
} else {
// button 说明为"结束连麦"时,停止推流
// 停止推流
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().stopPublishing();
// 停止预览
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().stopPreview();
isJoinedLive = false;
// 设置视图可用
ZGJoinLiveHelper.sharedInstance().setJoinLiveViewFree(mPublishStreamID);
// 修改 button 的说明为"视频连麦"
binding.btnApplyJoinLive.setText(getString(R.string.tx_joinLive));
AppLogger.getInstance().i(JoinLiveAudienceUI.class, "观众结束连麦");
}
}
// 登录房间并拉流
public void startPlay(){
AppLogger.getInstance().i(JoinLiveAudienceUI.class, "登录房间 %s", mRoomID);
// 防止用户点击,弹出加载对话框
CustomDialog.createDialog("登录房间中...", this).show();
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().setZegoAudioRouteCallback(new IZegoAudioRouteCallback() {
@Override
public void onAudioRouteChange(int i) {
String devices = "";
switch (i) {
case com.zego.zegoavkit2.ZegoConstants.AudioRouteType.Bluetooth:
devices = String.format("onAudioRouteChange回调:%s", "蓝牙");
break;
case com.zego.zegoavkit2.ZegoConstants.AudioRouteType.EarPhone:
devices = String.format("onAudioRouteChange回调:%s", "耳机");
break;
case com.zego.zegoavkit2.ZegoConstants.AudioRouteType.LoudSpeaker:
devices = String.format("onAudioRouteChange回调:%s", "扬声器");
break;
case com.zego.zegoavkit2.ZegoConstants.AudioRouteType.Receiver:
devices = String.format("onAudioRouteChange回调:%s", "听筒");
break;
case com.zego.zegoavkit2.ZegoConstants.AudioRouteType.UsbAudio:
devices = String.format("onAudioRouteChange回调:%s", "USB设备");
break;
}
AppLogger.getInstance().e(JoinLiveAudienceUI.class, devices);
}
});
// 开始拉流前需要先登录房间,此处是观众登录主播所在的房间
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().loginRoom(mRoomID, ZegoConstants.RoomRole.Audience, new IZegoLoginCompletionCallback() {
@Override
public void onLoginCompletion(int errorCode, ZegoStreamInfo[] zegoStreamInfos) {
CustomDialog.createDialog(JoinLiveAudienceUI.this).cancel();
if (errorCode == 0) {
AppLogger.getInstance().i(JoinLiveAudienceUI.class, "登录房间成功 roomId : %s", mRoomID);
// 筛选主播流,主播流采用全屏的视图
for (ZegoStreamInfo streamInfo:zegoStreamInfos){
if (streamInfo.userID.equals(mAnchorID)){
// 主播流采用全屏的视图,开始拉流
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().startPlayingStream(streamInfo.streamID, mBigView.textureView);
// 设置拉流视图模式,此处采用 SDK 默认值--等比缩放填充整View,可能有部分被裁减。
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().setViewMode(ZegoVideoViewMode.ScaleAspectFill, streamInfo.streamID);
// 向拉流流名列表中添加流名
mPlayStreamIDs.add(streamInfo.streamID);
// 修改视图信息
mBigView.streamID = streamInfo.streamID;
ZGJoinLiveHelper.sharedInstance().modifyTextureViewInfo(mBigView);
// 将 "视频连麦" button 置为可见
binding.btnApplyJoinLive.setVisibility(View.VISIBLE);
break;
}
}
// 拉副主播流(即连麦者的流)
for (ZegoStreamInfo streamInfo:zegoStreamInfos) {
if (!streamInfo.userID.equals(mAnchorID)){
// 获取可用的视图
JoinLiveView freeView = ZGJoinLiveHelper.sharedInstance().getFreeTextureView();
if (freeView != null) {
// 开始拉流
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().startPlayingStream(streamInfo.streamID, freeView.textureView);
// 设置拉流视图模式,此处采用 SDK 默认值--等比缩放填充整个 View,可能有部分被裁减。
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().setViewMode(ZegoVideoViewMode.ScaleAspectFill, streamInfo.streamID);
// 向拉流流名列表中添加流名
mPlayStreamIDs.add(streamInfo.streamID);
// 修改视图信息
freeView.streamID = streamInfo.streamID;
ZGJoinLiveHelper.sharedInstance().modifyTextureViewInfo(freeView);
}
}
}
} else {
AppLogger.getInstance().i(JoinLiveAudienceUI.class, "登录房间失败, errorCode : %d", errorCode);
Toast.makeText(JoinLiveAudienceUI.this, getString(com.zego.common.R.string.tx_login_room_failure), Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* 供其他Activity调用,进入本专题模块的方法
*
* @param activity
*/
public static void actionStart(Activity activity, String roomID, String anchorID) {
Intent intent = new Intent(activity, JoinLiveAudienceUI.class);
intent.putExtra("roomID", roomID);
intent.putExtra("anchorID", anchorID);
activity.startActivity(intent);
}
// 设置 SDK 相关回调的监听
public void initSDKCallback(){
// 设置房间回调监听
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().setZegoRoomCallback(new IZegoRoomCallback() {
@Override
public void onKickOut(int reason, String roomID, String customReason) {
}
@Override
public void onDisconnect(int errorcode, String roomID) {
}
@Override
public void onReconnect(int errorcode, String roomID) {
}
@Override
public void onTempBroken(int errorcode, String roomID) {
}
@Override
public void onStreamUpdated(int type, ZegoStreamInfo[] zegoStreamInfos, String roomID) {
// 房间流列表更新
if (roomID.equals(mRoomID)){
// 当登录房间成功后,如果房间内中途有人推流或停止推流。房间内其他人就能通过该回调收到流更新通知。
for (ZegoStreamInfo streamInfo : zegoStreamInfos) {
// 当有流新增的时候,拉流
if (type == ZegoConstants.StreamUpdateType.Added) {
AppLogger.getInstance().i(JoinLiveAudienceUI.class, "房间内收到流新增通知. streamID : %s, userName : %s, extraInfo : %s", streamInfo.streamID, streamInfo.userName, streamInfo.extraInfo);
// 获取可用的视图
JoinLiveView freeView = ZGJoinLiveHelper.sharedInstance().getFreeTextureView();
if (freeView != null) {
if (!streamInfo.userID.equals(mAnchorID)) {
// 开始拉流
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().startPlayingStream(streamInfo.streamID, freeView.textureView);
// 设置拉流视图模式,此处采用 SDK 默认值--等比缩放填充整个View,可能有部分被裁减。
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().setViewMode(ZegoVideoViewMode.ScaleAspectFill, streamInfo.streamID);
// 向拉流流名列表中添加流名
mPlayStreamIDs.add(streamInfo.streamID);
// 修改视图信息
freeView.streamID = streamInfo.streamID;
ZGJoinLiveHelper.sharedInstance().modifyTextureViewInfo(freeView);
} else {
// 开始拉流,此处处理主播中途断流后重新推流
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().startPlayingStream(streamInfo.streamID, mBigView.textureView);
// 设置拉流视图模式,此处采用 SDK 默认值--等比缩放填充整个View,可能有部分被裁减。
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().setViewMode(ZegoVideoViewMode.ScaleAspectFill, streamInfo.streamID);
// 向拉流流名列表中添加流名
mPlayStreamIDs.add(streamInfo.streamID);
// 修改视图信息
mBigView.streamID = streamInfo.streamID;
ZGJoinLiveHelper.sharedInstance().modifyTextureViewInfo(mBigView);
}
}
}
// 当有其他流关闭的时候,停止拉流
else if (type == ZegoConstants.StreamUpdateType.Deleted) {
AppLogger.getInstance().i(JoinLiveAudienceUI.class, "房间内收到流删除通知. streamID : %s, userName : %s, extraInfo : %s", streamInfo.streamID, streamInfo.userName, streamInfo.extraInfo);
for (String playStreamID:mPlayStreamIDs){
if (playStreamID.equals(streamInfo.streamID)){
// 停止拉流
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().stopPlayingStream(streamInfo.streamID);
mPlayStreamIDs.remove(streamInfo.streamID);
// 修改视图信息
ZGJoinLiveHelper.sharedInstance().setJoinLiveViewFree(streamInfo.streamID);
// 判断该条关闭流是否为主播
if (streamInfo.userID.equals(mAnchorID)) {
// 界面提示主播已停止直播
Toast.makeText(JoinLiveAudienceUI.this, getString(R.string.tx_anchor_stoppublish), Toast.LENGTH_SHORT).show();
// 在已连麦的情况下,主播停止直播连麦观众也停止推流
if (isJoinedLive) {
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().stopPublishing();
// 停止预览
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().stopPreview();
isJoinedLive = false;
// 设置视图可用
ZGJoinLiveHelper.sharedInstance().setJoinLiveViewFree(mPublishStreamID);
}
// 将 "视频连麦" button 置为不可见
binding.btnApplyJoinLive.setVisibility(View.INVISIBLE);
}
break;
}
}
}
}
}
}
@Override
public void onStreamExtraInfoUpdated(ZegoStreamInfo[] zegoStreamInfos, String roomID) {
// 流的额外信息更新
}
@Override
public void onRecvCustomCommand(String userID, String userName, String content, String roomID) {
// 收到自定义信息
}
});
// 设置拉流回调监听
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().setZegoLivePlayerCallback(new IZegoLivePlayerCallback() {
@Override
public void onPlayStateUpdate(int stateCode, String streamID) {
// 拉流状态更新,errorCode 非0 则说明拉流失败
// 拉流常见错误码请看文档: <a>https://doc.zego.im/CN/491.html</a>
if (stateCode == 0) {
AppLogger.getInstance().i(JoinLiveAudienceUI.class, "拉流成功, streamID : %s", streamID);
Toast.makeText(JoinLiveAudienceUI.this, getString(com.zego.common.R.string.tx_play_success), Toast.LENGTH_SHORT).show();
} else {
AppLogger.getInstance().i(JoinLiveAudienceUI.class, "拉流失败, streamID : %s, errorCode : %d", streamID, stateCode);
Toast.makeText(JoinLiveAudienceUI.this, getString(com.zego.common.R.string.tx_play_fail), Toast.LENGTH_SHORT).show();
// 解除视图占用
ZGJoinLiveHelper.sharedInstance().setJoinLiveViewFree(streamID);
// 从已拉流列表中移除该流名
mPlayStreamIDs.remove(streamID);
}
}
@Override
public void onPlayQualityUpdate(String streamID, ZegoPlayStreamQuality zegoPlayStreamQuality) {
}
@Override
public void onInviteJoinLiveRequest(int seq, String fromUserID, String fromUserName, String roomID) {
}
@Override
public void onRecvEndJoinLiveCommand(String fromUserID, String fromUserName, String roomID ) {
}
@Override
public void onVideoSizeChangedTo(String streamID, int i, int i1) {
}
});
// 设置推流回调监听
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().setZegoLivePublisherCallback(new IZegoLivePublisherCallback() {
@Override
public void onPublishStateUpdate(int errorCode, String streamID, HashMap<String, Object> hashMap) {
// 推流状态更新,errorCode 非0 则说明推流失败
// 推流常见错误码请看文档: <a>https://doc.zego.im/CN/308.html</a>
if (errorCode == 0) {
AppLogger.getInstance().i(JoinLiveAudienceUI.class, "推流成功, streamID : %s", streamID);
Toast.makeText(JoinLiveAudienceUI.this, getString(R.string.tx_publish_success), Toast.LENGTH_SHORT).show();
isJoinedLive = true;
// 修改button的标识为 结束连麦
binding.btnApplyJoinLive.setText(getString(R.string.tx_end_join_live));
} else {
AppLogger.getInstance().i(JoinLiveAudienceUI.class, "推流失败, streamID : %s, errorCode : %d", streamID, errorCode);
Toast.makeText(JoinLiveAudienceUI.this, getString(R.string.tx_publish_fail), Toast.LENGTH_SHORT).show();
// 解除视图占用
ZGJoinLiveHelper.sharedInstance().setJoinLiveViewFree(streamID);
}
}
@Override
public void onJoinLiveRequest(int i, String s, String s1, String s2) {
}
@Override
public void onPublishQualityUpdate(String s, ZegoPublishStreamQuality zegoPublishStreamQuality) {
}
@Override
public void onCaptureVideoSizeChangedTo(int i, int i1) {
}
@Override
public void onCaptureVideoFirstFrame() {
}
@Override
public void onCaptureAudioFirstFrame() {
}
});
}
// 去除SDK相关的回调监听
public void releaseSDKCallback(){
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().setZegoLivePublisherCallback(null);
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().setZegoLivePlayerCallback(null);
ZGJoinLiveHelper.sharedInstance().getZegoLiveRoom().setZegoRoomCallback(null);
}
}
| true |
3f88446e3f3f960f1bf01ed2407fed76f33a9c73 | Java | Oscar2019/Trabalho-JVM | /tests/inteiro/neg.java | UTF-8 | 147 | 1.914063 | 2 | [] | no_license | class neg{
public static void main(String[] args){
int pi1 = 12;
int pi2 = -pi1;
System.out.println(pi2);
}
} | true |
a73de2a5a30aa5a4ed0462441308d57416cdad0e | Java | longhuoshi/lhsbcsx | /src/main/java/m_thread/second/chapter1/Demo17Interrupt.java | UTF-8 | 1,099 | 3.984375 | 4 | [] | no_license | package m_thread.second.chapter1;
import java.util.LinkedList;
/**
* @author l
* @date 2021/9/2 11:49
* @description
*利用interrupt停止线程2
* interrupt只对 执行任务的线程里有 Thread.sleep(20000); 才会终止线程并抛异常InterruptedException。
*/
public class Demo17Interrupt {
public static void main(String[] args) throws InterruptedException {
Thread t = new Demo17InterruptThread();
t.start();
Thread.sleep(11);
t.interrupt();
}
}
class Demo17InterruptThread extends Thread{
public void run(){
try {
for (int i = 0; i <Integer.MAX_VALUE ; i++) {
String s = new String(); //如果 是空字符串,java会直接忽略 循环体
// System.out.println("i="+i);
}
System.out.println("开始线程。");
Thread.sleep(20000); //只有执行到这里interrupt 才会抛异常
System.out.println("结束线程。");
} catch (Exception e) {//InterruptedException
e.printStackTrace();
}
}
}
| true |
587c051ba57574dde0c3ec9eb3503b27d3dac0de | Java | ApollinManenok/Java-FinalProject | /src/test/java/by/itacademy/finalproject/menus/operable/search/searchable/GroupSearchTest.java | UTF-8 | 1,769 | 2.578125 | 3 | [] | no_license | package by.itacademy.finalproject.menus.operable.search.searchable;
import by.itacademy.finalproject.domain.School;
import by.itacademy.finalproject.domain.group.Student;
import by.itacademy.finalproject.menus.serialize.serialization.json.ReadLocalGsonTest;
import by.itacademy.finalproject.menus.serializing.serialization.json.ReadLocalGson;
import org.junit.Test;
import java.io.File;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class GroupSearchTest {
private GroupSearch searcher = new GroupSearch();
private School school = new School();
private String fileName = "TestSchool.json";
private ReadLocalGson reader = new ReadLocalGson(school, new File(ReadLocalGsonTest.class
.getClassLoader().getResource(fileName).getFile()));
{
reader.serialize();
}
@Test
public void checkSearcherFindStudentsFromGroupWithNameRose() {
searcher.setName("Rose");
Set<Student> students = searcher.search(school.getGroups());
assertEquals(1, students.size());
}
@Test
public void checkSearcherFindStudentsFromGroupWithNameStar() {
Set<Student> correctStudents = school.getGroupByName("Star").getStudents();
searcher.setName("Star");
Set<Student> students = searcher.search(school.getGroups());
assertEquals(3, students.size());
for (Student student : correctStudents) {
assertTrue(students.contains(student));
}
}
@Test
public void checkSearcherDoesNotFindStudentsFromGroupWithNameRock() {
searcher.setName("Rock");
Set<Student> students = searcher.search(school.getGroups());
assertEquals(0, students.size());
}
}
| true |
92bf4461d5a8f3642854c91157629358ad5e9dd5 | Java | gi0o0/quasar_fire | /src/main/java/co/com/mercadolibre/service/IMensajeService.java | UTF-8 | 194 | 1.71875 | 2 | [] | no_license | package co.com.mercadolibre.service;
import java.util.List;
import co.com.mercadolibre.entities.Satelite;
public interface IMensajeService {
String getMessage(List<Satelite> satelites);
}
| true |
0b1aa06850381fd3734231c722a6ca9927b5586a | Java | fafeichter/UDPChat | /src/fff/triplef/udpchat/client/gui/WindowClosing.java | UTF-8 | 800 | 2.375 | 2 | [] | no_license | package fff.triplef.udpchat.client.gui;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import fff.triplef.udpchat.exception.UDPChatException;
import fff.triplef.udpchat.message.Message;
public class WindowClosing extends WindowAdapter {
ClientGUI clientGUI = null;
public WindowClosing(ClientGUI clientGUI) {
this.clientGUI = clientGUI;
}
public void windowClosing(WindowEvent e) {
if (clientGUI.actualUsername != null) {
try {
clientGUI.client.sendMessage(new Message(
clientGUI.actualUsername, Message.ID_ALL,
Message.ID_LOGOUT, null, null));
} catch (IOException e1) {
UDPChatException.behandleException(clientGUI, e1);
}
}
clientGUI.client.close(clientGUI.receiveMsgThread);
System.exit(0);
}
} | true |
9ad080f1b3e73244cdb7f3269fc3eb71bf740a42 | Java | fuujiro/LeetCodeHot100 | /src/T121.java | UTF-8 | 402 | 2.828125 | 3 | [] | no_license | public class T121 {
class Solution {
public int maxProfit(int[] prices) {
int max = 0, l = 0;
for (int i = 1; i < prices.length; i++) {
if(prices[i] > prices[l]) {
max = Math.max(max, prices[i]-prices[l]);
} else {
l=i;
}
}
return max;
}
}
}
| true |
c05b184aa96dab5e08e8c158c44e68daa295aeee | Java | LIKESCX/cpmtDto | /src/main/java/com/cpit/cpmt/dto/exchange/operator/EquipmentInfoShow.java | UTF-8 | 12,861 | 1.992188 | 2 | [] | no_license | package com.cpit.cpmt.dto.exchange.operator;
import com.cpit.common.TimeConvertor;
import com.cpit.cpmt.dto.exchange.basic.ConnectorInfo;
import com.cpit.cpmt.dto.exchange.basic.EquipmentInfo;
import com.cpit.cpmt.dto.system.User;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
/**
* @author
*/
public class EquipmentInfoShow extends EquipmentInfo {
private static final long serialVersionUID = 1L;
private String eid;
private String sid;
/**
* 充电站id
*/
private String stationId;
/**
* 补贴状态 0:未申请 1:申请中;2 审核中;3:待补贴;4:已补贴; 5:审核不通过
*/
private String allowanceStatus;
/*
* 补贴金额
* */
private String allowancePrice;
/*
* 补贴时间
* */
@JsonFormat(pattern=TimeConvertor.FORMAT_MINUS_DAY,timezone = "GMT+8")
private Date allowanceDate;
/*
*使用期限 单位:年
* */
private Integer periodUse;
/*
* 入库时间
* */
@JsonFormat(pattern=TimeConvertor.FORMAT_MINUS_DAY,timezone = "GMT+8")
private Date inDate;
/*
* 报废时间
* */
@JsonFormat(pattern=TimeConvertor.FORMAT_MINUS_DAY,timezone = "GMT+8")
private Date worthDate;
/**
* 检测状态 1:未检测;2:检测通过;3:检测不通过
*/
private String checkoutStatus;
/**
* 额定输入电压 单位:kV
*/
private String ratedInVoltage;
/**
* 额定输出电压 单位:V
*/
private String ratedOutVoltage;
/**
* 额定容量 单位:kVA
*/
private String ratedPower;
/**
* 馈线开关数量 个
*/
private Integer feedNum;
/**
* 枪数
*/
private Integer gunSum;
//充电站对象
private StationInfoShow stationInfo;
//运营商id集合
private List<String> operatorIdList;
//areacode集合
private List<String> areaCodeList;
private List<String> chargeIdList;
private Integer numbers;
/*
* 设备接口列表
* */
private List<ConnectorInfoShow> connectorShowInfos;
//动态-累计充电量
private String chargeElecticSum;
//累计放电量
private String disChargeEleticsSum;
//当月充电量
private String chargeElecticByMonth;
//累计充电次数
private Integer chargTimes;
//实时功率
private String realTimePower;
//累计故障次数
private Integer chargeErrorTimes;
//使用率
private String UseRate;
//故障率
private String errorRate;
//抽查检验
private String selectCheck;
//通过数量
private String passNum;
//充电电能
private String chargeElectricEnergy;
//放电电能
private String disChargeElectricEnergy;
//累计使用时间
private String totalUseTime;
//充电设备接口累计充电量
private String connectorElecticSum;
//累计放电量
private String disConnectorEleticsSum;
//备注
private String note;
//用户
private User user;
//补贴状态list
private List<Object> statusList;
/*
*操作类型 1.新增 2.变更
* */
private Integer operateType;
//stationTypeList
private List<Integer> stationTypeList;
/**
* 充电站省市辖区编码
*/
private String areaCode;
public Date getWorthDate() {
return worthDate;
}
public void setWorthDate(Date worthDate) {
this.worthDate = worthDate;
}
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public List<Integer> getStationTypeList() {
return stationTypeList;
}
public void setStationTypeList(List<Integer> stationTypeList) {
this.stationTypeList = stationTypeList;
}
public Integer getPeriodUse() {
return periodUse;
}
public void setPeriodUse(Integer periodUse) {
this.periodUse = periodUse;
}
public Integer getOperateType() {
return operateType;
}
public void setOperateType(Integer operateType) {
this.operateType = operateType;
}
public List<Object> getStatusList() {
return statusList;
}
public void setStatusList(List<Object> statusList) {
this.statusList = statusList;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public Date getAllowanceDate() {
return allowanceDate;
}
public void setAllowanceDate(Date allowanceDate) {
this.allowanceDate = allowanceDate;
}
public Date getInDate() {
return inDate;
}
public void setInDate(Date inDate) {
this.inDate = inDate;
}
public Integer getNumbers() {
return numbers;
}
public void setNumbers(Integer numbers) {
this.numbers = numbers;
}
public List<ConnectorInfoShow> getConnectorShowInfos() {
return connectorShowInfos;
}
public void setConnectorShowInfos(List<ConnectorInfoShow> connectorShowInfos) {
this.connectorShowInfos = connectorShowInfos;
}
public List<String> getChargeIdList() {
return chargeIdList;
}
public void setChargeIdList(List<String> chargeIdList) {
this.chargeIdList = chargeIdList;
}
public List<String> getOperatorIdList() {
return operatorIdList;
}
public void setOperatorIdList(List<String> operatorIdList) {
this.operatorIdList = operatorIdList;
}
public List<String> getAreaCodeList() {
return areaCodeList;
}
public void setAreaCodeList(List<String> areaCodeList) {
this.areaCodeList = areaCodeList;
}
public String getChargeElecticSum() {
return chargeElecticSum;
}
public void setChargeElecticSum(String chargeElecticSum) {
this.chargeElecticSum = chargeElecticSum;
}
public String getDisChargeEleticsSum() {
return disChargeEleticsSum;
}
public void setDisChargeEleticsSum(String disChargeEleticsSum) {
this.disChargeEleticsSum = disChargeEleticsSum;
}
public String getChargeElecticByMonth() {
return chargeElecticByMonth;
}
public void setChargeElecticByMonth(String chargeElecticByMonth) {
this.chargeElecticByMonth = chargeElecticByMonth;
}
public Integer getChargTimes() {
return chargTimes;
}
public void setChargTimes(Integer chargTimes) {
this.chargTimes = chargTimes;
}
public String getRealTimePower() {
return realTimePower;
}
public void setRealTimePower(String realTimePower) {
this.realTimePower = realTimePower;
}
public Integer getChargeErrorTimes() {
return chargeErrorTimes;
}
public void setChargeErrorTimes(Integer chargeErrorTimes) {
this.chargeErrorTimes = chargeErrorTimes;
}
public String getUseRate() {
return UseRate;
}
public void setUseRate(String useRate) {
UseRate = useRate;
}
public String getErrorRate() {
return errorRate;
}
public void setErrorRate(String errorRate) {
this.errorRate = errorRate;
}
public String getSelectCheck() {
return selectCheck;
}
public void setSelectCheck(String selectCheck) {
this.selectCheck = selectCheck;
}
public String getPassNum() {
return passNum;
}
public void setPassNum(String passNum) {
this.passNum = passNum;
}
public String getChargeElectricEnergy() {
return chargeElectricEnergy;
}
public void setChargeElectricEnergy(String chargeElectricEnergy) {
this.chargeElectricEnergy = chargeElectricEnergy;
}
public String getDisChargeElectricEnergy() {
return disChargeElectricEnergy;
}
public void setDisChargeElectricEnergy(String disChargeElectricEnergy) {
this.disChargeElectricEnergy = disChargeElectricEnergy;
}
public String getTotalUseTime() {
return totalUseTime;
}
public void setTotalUseTime(String totalUseTime) {
this.totalUseTime = totalUseTime;
}
public String getConnectorElecticSum() {
return connectorElecticSum;
}
public void setConnectorElecticSum(String connectorElecticSum) {
this.connectorElecticSum = connectorElecticSum;
}
public String getDisConnectorEleticsSum() {
return disConnectorEleticsSum;
}
public void setDisConnectorEleticsSum(String disConnectorEleticsSum) {
this.disConnectorEleticsSum = disConnectorEleticsSum;
}
public String getStationId() {
return stationId;
}
public void setStationId(String stationId) {
this.stationId = stationId;
}
public String getAllowanceStatus() {
return allowanceStatus;
}
public void setAllowanceStatus(String allowanceStatus) {
this.allowanceStatus = allowanceStatus;
}
public String getAllowancePrice() {
return allowancePrice;
}
public void setAllowancePrice(String allowancePrice) {
this.allowancePrice = allowancePrice;
}
public String getCheckoutStatus() {
return checkoutStatus;
}
public void setCheckoutStatus(String checkoutStatus) {
this.checkoutStatus = checkoutStatus;
}
public String getRatedInVoltage() {
return ratedInVoltage;
}
public void setRatedInVoltage(String ratedInVoltage) {
this.ratedInVoltage = ratedInVoltage;
}
public String getRatedOutVoltage() {
return ratedOutVoltage;
}
public void setRatedOutVoltage(String ratedOutVoltage) {
this.ratedOutVoltage = ratedOutVoltage;
}
public String getRatedPower() {
return ratedPower;
}
public void setRatedPower(String ratedPower) {
this.ratedPower = ratedPower;
}
public Integer getFeedNum() {
return feedNum;
}
public void setFeedNum(Integer feedNum) {
this.feedNum = feedNum;
}
public Integer getGunSum() {
return gunSum;
}
public void setGunSum(Integer gunSum) {
this.gunSum = gunSum;
}
public StationInfoShow getStationInfo() {
return stationInfo;
}
public void setStationInfo(StationInfoShow stationInfo) {
this.stationInfo = stationInfo;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EquipmentInfoShow)) return false;
if (!super.equals(o)) return false;
EquipmentInfoShow that = (EquipmentInfoShow) o;
return Objects.equals(stationId, that.stationId) &&
Objects.equals(allowanceStatus, that.allowanceStatus) &&
Objects.equals(allowancePrice, that.allowancePrice) &&
Objects.equals(checkoutStatus, that.checkoutStatus) &&
Objects.equals(ratedInVoltage, that.ratedInVoltage) &&
Objects.equals(ratedOutVoltage, that.ratedOutVoltage) &&
Objects.equals(ratedPower, that.ratedPower) &&
Objects.equals(feedNum, that.feedNum) &&
Objects.equals(gunSum, that.gunSum) &&
Objects.equals(stationInfo, that.stationInfo);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), stationId, allowanceStatus, allowancePrice, checkoutStatus, ratedInVoltage, ratedOutVoltage, ratedPower, feedNum, gunSum, stationInfo);
}
@Override
public String toString() {
return "EquipmentInfoShow{" +
"stationId='" + stationId + '\'' +
", allowanceStatus='" + allowanceStatus + '\'' +
", allowancePrice='" + allowancePrice + '\'' +
", checkoutStatus='" + checkoutStatus + '\'' +
", ratedInVoltage='" + ratedInVoltage + '\'' +
", ratedOutVoltage='" + ratedOutVoltage + '\'' +
", ratedPower='" + ratedPower + '\'' +
", feedNum=" + feedNum +
", gunSum=" + gunSum +
", stationInfo=" + stationInfo +
'}';
}
} | true |
43372a50bd8629926dee95ba3be76be59bd8581d | Java | Crune/MiPlatform-Spring-MyBatis | /src/main/java/com/jlab/mi/platform/MiDTO.java | UHC | 4,884 | 2.21875 | 2 | [] | no_license | package com.jlab.mi.platform;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.*;
import com.tobesoft.platform.data.*;
public class MiDTO implements Serializable {
private static final long serialVersionUID = 5374424584879470680L;
private Map<String, String> variableListMap;
public Map<String, String> getVList() { return variableListMap; }
/**
* dataSetListMap = Map<DSĪ, DS>
* DS = Map<з(C, R, U, D), CRUDƮ>
* CRUDƮ = List<Column, Value>
*/
@SuppressWarnings("rawtypes")
private Map<String, Map> dataSetListMap;
@SuppressWarnings("rawtypes")
public Map<String, Map> getDSList() { return dataSetListMap; }
/** VariableList */
private VariableList variableList;
public VariableList getVariableList() {
variableList.clear();
for (String key : getVList().keySet()) {
variableList.addVariable(key, get(key));
}
return variableList;
}
public String get(String name) {
if (variableListMap != null) {
return variableListMap.get(name);
} else {
return null;
}
}
public void setVariableList(VariableList vList) {
this.variableList = vList;
variableListMap = new HashMap<String, String>();
for (int i = 0; i < vList.size(); i++) {
variableListMap.put(
vList.getVariable(i).getID(),
vList.getVariable(i).getValue().getString()
);
}
}
/** DatasetList */
private DatasetList datasetList;
public DatasetList getDatasetList(Class<?> voCls) {
datasetList.clear();
for (String dsName : getDSList().keySet()) {
Map<?, ?> curDS = getDSList().get(dsName);
for (Object dsMapName : curDS.keySet()) {
Map<?, ?> dsMap = (Map<?, ?>) curDS.get(dsMapName);
List<?> list = (List<?>) dsMap.get("select");
Dataset ds = Mi.list2ds(dsName, list);
datasetList.addDataset(ds);
}
}
return datasetList;
}
@SuppressWarnings({ "rawtypes" })
public void setDatasetList(DatasetList dsList) {
this.datasetList = dsList;
Map<String, Map> rst = new HashMap<String, Map>();
for (int dsCount=0; dsCount<dsList.size(); dsCount++) {
HashMap<String, List<Map>> crudMap = new HashMap<String, List<Map>>();
List<Map> insert = new ArrayList<Map>();
List<Map> select = new ArrayList<Map>();
List<Map> update = new ArrayList<Map>();
List<Map> delete = new ArrayList<Map>();
Map<String, String> hm;
Dataset ds = (Dataset) dsList.getDataset(dsCount);
for (int i = 0; i < ds.getRowCount(); i++) {
hm = new HashMap<String, String>();
for (int j = 0; j < ds.getColumnCount(); j++) {
hm.put(ds.getColumnID(j), ds.getColumnAsString(i, j));
}
if ("update".equals(ds.getRowStatus(i))) {
update.add(hm);
} else if ("insert".equals(ds.getRowStatus(i))) {
insert.add(hm);
} else {
select.add(hm);
}
}
for (int i = 0; i < ds.getDeleteRowCount(); i++) {
hm = new HashMap<String, String>();
for (int j = 0; j < ds.getColumnCount(); j++) {
String value = ds.getDeleteColumn(i, ds.getColumnID(j)).getString();
hm.put(ds.getColumnID(j), value);
}
delete.add(hm);
}
crudMap.put("insert", insert);
crudMap.put("select", select);
crudMap.put("update", update);
crudMap.put("delete", delete);
rst.put(ds.getDataSetID(), crudMap);
this.dataSetListMap = rst;
}
}
public List<?> getInsert(String dsName) {
return ((List<?>) getDSList().get(dsName).get("insert"));
}
public List<?> getSelect(String dsName) {
return ((List<?>) getDSList().get(dsName).get("select"));
}
public List<?> getUpdate(String dsName) {
return ((List<?>) getDSList().get(dsName).get("update"));
}
public List<?> getDelete(String dsName) {
return ((List<?>) getDSList().get(dsName).get("delete"));
}
public void exe(String dsName, Object dao, Class<? extends Object> argCls, String insert, String update, String delete) {
runQuery(dsName, insert, dao, argCls, getInsert(dsName));
runQuery(dsName, update, dao, argCls, getUpdate(dsName));
runQuery(dsName, delete, dao, argCls, getDelete(dsName));
}
private void runQuery(String dsName, String mName, Object runner, Class<? extends Object> argCls, List<?> list) {
if (mName != null && !mName.isEmpty()) {
try {
Method m = runner.getClass().getMethod(mName, argCls);
for (Object map : list) {
Object arg = Mi.map2vo((Map<?, ?>)map, argCls);
m.invoke(runner, arg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public String toString() {
return "MiDTO [variableListMap=" + variableListMap + ", dataSetListMap=" + dataSetListMap + ", variableList="
+ variableList + ", datasetList=" + datasetList + "]";
}
}
| true |
5cfc4301fb15313577a465f8f2efe3e8355af6bc | Java | NardiE/OrdiniRemoti | /app/src/main/java/com/example/edoardo/ordiniremoti/Activity/Sincronizza.java | UTF-8 | 1,187 | 1.9375 | 2 | [] | no_license | package com.example.edoardo.ordiniremoti.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.example.edoardo.ordiniremoti.R;
import com.example.edoardo.ordiniremoti.classivarie.TipiConfigurazione;
import com.example.edoardo.ordiniremoti.importazione.AsyncFTPDownloader;
import java.io.File;
import java.util.ArrayList;
public class Sincronizza extends AppCompatActivity {
public Context context;
public ProgressDialog barProgressDialog = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sincronizza);
}
public void importaAnagrafiche(View view) {
Intent i = new Intent(this, ImportaAnagrafiche.class);
startActivity(i);
}
public void esportaOrdini(View view) {
Intent i = new Intent(this,EsportaOrdini.class);
startActivity(i);
}
}
| true |
c50574b18e54744d4ed0b43669a32d9575f1cf99 | Java | chirhotec/gurella | /core/src/com/gurella/engine/math/ModelIntesector.java | UTF-8 | 9,838 | 2.203125 | 2 | [] | no_license | package com.gurella.engine.math;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.model.MeshPart;
import com.badlogic.gdx.graphics.g3d.model.Node;
import com.badlogic.gdx.graphics.g3d.model.NodePart;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.math.collision.Ray;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
public class ModelIntesector {
private final BoundingBox bounds = new BoundingBox();
private final Matrix4 transform = new Matrix4();
private final Ray invRay = new Ray();
private final Vector3 intersection = new Vector3();
private ModelInstance closestModelInstance; //TODO unused
private final Vector3 closestIntersection = new Vector3();
private float closestDistance = Float.MAX_VALUE;
private final Vector3 closestNodeIntersection = new Vector3();
private float closestNodeDistance = Float.MAX_VALUE;
private final Vector3 closestPartIntersection = new Vector3();
private float closestPartDistance = Float.MAX_VALUE;
private final Vector3 t1 = new Vector3();
private final Vector3 t2 = new Vector3();
private final Vector3 t3 = new Vector3();
private final Vector3 cameraPosition = new Vector3();
private final Vector3 cameraPositionInv = new Vector3();
private final Ray ray = new Ray();
private ModelInstance modelInstance;
public boolean getIntersection(Vector3 cameraPosition, Ray ray, ModelInstance modelInstance,
Intersection intersection) {
init(cameraPosition, ray);
process(modelInstance);
intersection.distance = closestDistance;
return extractResult(intersection.location);
}
public boolean getIntersection(Vector3 cameraPosition, Ray ray, ModelInstance modelInstance, Vector3 intersection) {
init(cameraPosition, ray);
process(modelInstance);
return extractResult(intersection);
}
void init(Vector3 cameraPosition, Ray ray) {
this.cameraPosition.set(cameraPosition);
this.ray.set(ray);
closestIntersection.set(Float.NaN, Float.NaN, Float.NaN);
closestDistance = Float.MAX_VALUE;
}
boolean process(ModelInstance modelInstance) {
this.modelInstance = modelInstance;
Array<Node> nodes = modelInstance.nodes;
for (int i = 0; i < nodes.size; i++) {
Node node = nodes.get(i);
if (getIntersection(node)) {
float distance = closestNodeIntersection.dst2(cameraPositionInv);
if (closestDistance > distance) {
closestDistance = distance;
closestIntersection.set(closestNodeIntersection);
closestModelInstance = modelInstance;
}
//TODO else if(closestDistance == distance) {pick the object with closest center}
}
}
return closestModelInstance == modelInstance;
}
boolean extractResult(Vector3 intersection) {
modelInstance = null;
if (closestModelInstance != null) {
closestModelInstance = null;
intersection.set(closestIntersection);
return true;
} else {
return false;
}
}
private boolean getIntersection(Node node) {
closestNodeIntersection.set(Float.NaN, Float.NaN, Float.NaN);
closestNodeDistance = Float.MAX_VALUE;
node.calculateWorldTransform();
node.extendBoundingBox(bounds.inf(), true);
bounds.mul(modelInstance.transform);
if (Intersector.intersectRayBoundsFast(ray, bounds)) {
transform.set(modelInstance.transform).mul(node.globalTransform);
if (Matrix4.inv(transform.val)) {
invRay.set(ray);
invRay.mul(transform);
cameraPositionInv.set(cameraPosition).mul(transform);
}
Array<NodePart> parts = node.parts;
for (int i = 0, n = parts.size; i < n; i++) {
NodePart nodePart = parts.get(i);
if (nodePart.enabled) {
MeshPart meshPart = nodePart.meshPart;
int primitiveType = meshPart.primitiveType;
Mesh mesh = meshPart.mesh;
int offset = meshPart.offset;
int count = meshPart.size;
if (getIntersection(mesh, primitiveType, offset, count)) {
float distance = closestPartIntersection.dst2(cameraPositionInv);
if (closestNodeDistance > distance) {
closestNodeDistance = distance;
closestNodeIntersection.set(closestPartIntersection);
}
}
}
}
for (int i = 0, n = node.getChildCount(); i < n; i++) {
Node child = node.getChild(i);
if (getIntersection(child)) {
float distance = closestNodeIntersection.dst2(cameraPositionInv);
if (closestDistance > distance) {
closestDistance = distance;
closestIntersection.set(closestNodeIntersection);
closestModelInstance = modelInstance;
}
}
}
}
return closestNodeDistance != Float.MAX_VALUE;
}
private boolean getIntersection(Mesh mesh, int primitiveType, int offset, int count) {
closestPartIntersection.set(Float.NaN, Float.NaN, Float.NaN);
closestPartDistance = Float.MAX_VALUE;
t1.setZero();
t2.setZero();
t3.setZero();
final int numIndices = mesh.getNumIndices();
final int numVertices = mesh.getNumVertices();
final int max = numIndices == 0 ? numVertices : numIndices;
if (offset < 0 || count < 1 || offset + count > max) {
return false;
}
final FloatBuffer verts = mesh.getVerticesBuffer();
final ShortBuffer index = mesh.getIndicesBuffer();
final VertexAttribute posAttrib = mesh.getVertexAttribute(Usage.Position);
final int posoff = posAttrib.offset / 4;
final int vertexSize = mesh.getVertexAttributes().vertexSize / 4;
final int end = offset + count;
switch (posAttrib.numComponents) {
case 1:
if (numIndices > 0) {
for (int i = offset; i < end;) {
int idx = index.get(i++) * vertexSize + posoff;
t1.set(verts.get(idx), 0, 0);
idx = index.get(i++) * vertexSize + posoff;
t2.set(verts.get(idx), 0, 0);
idx = index.get(i++) * vertexSize + posoff;
t3.set(verts.get(idx), 0, 0);
if (Intersector.intersectRayTriangle(invRay, t1, t2, t3, intersection)) {
float distance = intersection.dst2(cameraPositionInv);
if (closestPartDistance > distance) {
closestPartDistance = distance;
closestPartIntersection.set(intersection);
}
}
}
} else {
for (int i = offset; i < end;) {
int idx = i++ * vertexSize + posoff;
t1.set(verts.get(idx), 0, 0);
idx = i++ * vertexSize + posoff;
t2.set(verts.get(idx), 0, 0);
idx = i++ * vertexSize + posoff;
t3.set(verts.get(idx), 0, 0);
if (Intersector.intersectRayTriangle(invRay, t1, t2, t3, intersection)) {
float distance = intersection.dst2(cameraPositionInv);
if (closestPartDistance > distance) {
closestPartDistance = distance;
closestPartIntersection.set(intersection);
}
}
}
}
break;
case 2:
if (numIndices > 0) {
for (int i = offset; i < end;) {
int idx = index.get(i++) * vertexSize + posoff;
t1.set(verts.get(idx), verts.get(idx + 1), 0);
idx = index.get(i++) * vertexSize + posoff;
t2.set(verts.get(idx), verts.get(idx + 1), 0);
idx = index.get(i++) * vertexSize + posoff;
t3.set(verts.get(idx), verts.get(idx + 1), 0);
if (Intersector.intersectRayTriangle(invRay, t1, t2, t3, intersection)) {
float distance = intersection.dst2(cameraPositionInv);
if (closestPartDistance > distance) {
closestPartDistance = distance;
closestPartIntersection.set(intersection);
}
}
}
} else {
for (int i = offset; i < end;) {
int idx = i++ * vertexSize + posoff;
t1.set(verts.get(idx), verts.get(idx + 1), 0);
idx = i++ * vertexSize + posoff;
t2.set(verts.get(idx), verts.get(idx + 1), 0);
idx = i++ * vertexSize + posoff;
t3.set(verts.get(idx), verts.get(idx + 1), 0);
if (Intersector.intersectRayTriangle(invRay, t1, t2, t3, intersection)) {
float distance = intersection.dst2(cameraPositionInv);
if (closestPartDistance > distance) {
closestPartDistance = distance;
closestPartIntersection.set(intersection);
}
}
}
}
break;
case 3:
if (numIndices > 0) {
for (int i = offset; i < end;) {
int idx = index.get(i++) * vertexSize + posoff;
t1.set(verts.get(idx), verts.get(idx + 1), verts.get(idx + 2));
idx = index.get(i++) * vertexSize + posoff;
t2.set(verts.get(idx), verts.get(idx + 1), verts.get(idx + 2));
idx = index.get(i++) * vertexSize + posoff;
t3.set(verts.get(idx), verts.get(idx + 1), verts.get(idx + 2));
if (Intersector.intersectRayTriangle(invRay, t1, t2, t3, intersection)) {
float distance = intersection.dst2(cameraPositionInv);
if (closestPartDistance > distance) {
closestPartDistance = distance;
closestPartIntersection.set(intersection);
}
}
}
} else {
for (int i = offset; i < end;) {
int idx = i++ * vertexSize + posoff;
t1.set(verts.get(idx), verts.get(idx + 1), verts.get(idx + 2));
idx = i++ * vertexSize + posoff;
t2.set(verts.get(idx), verts.get(idx + 1), verts.get(idx + 2));
idx = i++ * vertexSize + posoff;
t3.set(verts.get(idx), verts.get(idx + 1), verts.get(idx + 2));
if (Intersector.intersectRayTriangle(invRay, t1, t2, t3, intersection)) {
float distance = intersection.dst2(cameraPositionInv);
if (closestPartDistance > distance) {
closestPartDistance = distance;
closestPartIntersection.set(intersection);
}
}
}
}
break;
default:
throw new GdxRuntimeException("Unsupported posAttrib.numComponents");
}
return closestPartDistance != Float.MAX_VALUE;
}
}
| true |
25453e19af6c98d91c26c27c33bf9f7ca2b08fa8 | Java | UnderTheMistletoe/IntroductionToAlgorithms | /src/Chapter1/SelectSort.java | UTF-8 | 587 | 3.21875 | 3 | [] | no_license | package Chapter1;
/**
* Created by zt199 on 4/4/2017.
*/
public class SelectSort {
public static void sort(int[] array) {
for (int i = 0; i < array.length; i++) {
int key = array[i];
int index = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < key) {
key = array[j];
index = j;
}
}
//swap array[i] array[index]
key = array[i];
array[i] = array[index];
array[index] = key;
}
}
}
| true |
578d6573bb95a2181c9bdaa7f26010e690b4785c | Java | qlong8807/MyJavaTest | /src/main/java/bean/User.java | UTF-8 | 1,513 | 2.578125 | 3 | [] | no_license | package bean;
public class User {
private int id;
private String firstName;
private String lastName;
private int sex;
private float height;
private float weight;
private String bloodType;
private String homeAddress;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
public String getBloodType() {
return bloodType;
}
public void setBloodType(String bloodType) {
this.bloodType = bloodType;
}
public String getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
@Override
public String toString() {
return "User [id=" + id + ", firstName=" + firstName + ", lastName="
+ lastName + ", sex=" + sex + ", height=" + height
+ ", weight=" + weight + ", bloodType=" + bloodType
+ ", homeAddress=" + homeAddress + "]";
}
}
| true |
e16e7c4a33b84cefc09b7b4954d2235e43d70430 | Java | ewinds/hzero-admin | /src/main/java/org/hzero/admin/app/service/MaintainService.java | UTF-8 | 1,229 | 2.109375 | 2 | [
"Apache-2.0"
] | permissive | package org.hzero.admin.app.service;
import io.choerodon.core.domain.Page;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;
import org.hzero.admin.domain.entity.Maintain;
import java.util.List;
/**
* @author XCXCXCXCX
* @date 2020/6/1 1:30 下午
*/
public interface MaintainService {
/**
* 更新运维状态,从UNUSED -> ACTIVE 或 从ACTIVE -> USED
* @param maintainId
*/
void updateState(Long maintainId, String from, String to);
/**
* 分页查询
* @param setState
* @param pageRequest
* @return
*/
Page<Maintain> page(PageRequest pageRequest, Maintain setState);
/**
* 根据主键查询
* @param maintainId
* @return
*/
Maintain selectByPrimaryKey(Long maintainId);
/**
* 插入
* @param maintain
*/
void insertSelective(Maintain maintain);
/**
* 更新
* @param maintain
*/
void updateByPrimaryKeySelective(Maintain maintain);
/**
* 删除
* @param maintainId
*/
void deleteByPrimaryKey(Long maintainId);
/**
* 获取运维服务列表
* @param maintainId
* @return
*/
List<String> getServices(Long maintainId);
}
| true |
f15de90058df59b015f0c5645ba36d921ed029a0 | Java | rohsin47/saga-orchestrator | /orchestrator-core/src/main/java/com/bfm/cii/orchestrator/kafka/consumer/SagaKafkaConsumer.java | UTF-8 | 1,497 | 2.03125 | 2 | [] | no_license | package com.bfm.cii.orchestrator.kafka.consumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import com.bfm.cii.orchestrator.events.InstructionEventInfo;
import com.bfm.cii.orchestrator.kafka.KafkaGateway;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
public class SagaKafkaConsumer {
@Autowired
KafkaGateway kafkaGateway;
@KafkaListener(topics = "${app.topic.consumer.order-replies}",
containerFactory = "orderRepliesKafkaListenerContainerFactory")
public void consume(@Payload InstructionEventInfo message,
@Header(name = KafkaHeaders.RECEIVED_MESSAGE_KEY, required = false) String key,
@Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition,
@Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
@Header(KafkaHeaders.RECEIVED_TIMESTAMP) long ts) {
log.info("Consumed message: {}, with key : {}, from topic : {}, partition : {}",
message.getPayload(),
key,
topic,
partition);
kafkaGateway.publishInstructionEvent(message.getPayload());
}
}
| true |
6449eb97533e7aede6d7e91823fb5d65b7869e82 | Java | SpicyZinc/underestimate | /leetcode/JumpGameII/JumpGame.java | UTF-8 | 3,135 | 3.65625 | 4 | [] | no_license | /*
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2.
(Jump 1 step from index 0 to 1, then 3 steps to the last index.)
idea:
1. https://www.cnblogs.com/lichen782/p/leetcode_Jump_Game_II.html
O(n)
2. DP
*/
public class JumpGame {
// Sat Jun 15 15:12:42 2019
// i now think this is easy to understand
// steps = maxReachIndex - i
public int jump(int[] nums) {
if (nums.length <= 1) {
return 0;
}
// 已经跳了一次
int jumps = 1;
// 一个 jump 包含的步数 steps
// i 增加 会消耗掉 steps
int steps = nums[0];
int maxReachIndex = 0 + nums[0]; // index + nums[index]
for (int i = 1; i < nums.length; i++) {
if (i == nums.length - 1) {
return jumps;
}
// update maxReachIndex
maxReachIndex = Math.max(maxReachIndex, i + nums[i]);
steps--;
if (steps == 0) {
// steps == 0, need to another jump
jumps++;
steps = maxReachIndex - i;
}
}
return jumps;
}
// dp[i] The minimum number of jumps to reach i
// why TLE
public int jump(int[] nums) {
if (nums.length <= 1) {
return 0;
}
int size = nums.length;
int[] dp = new int[size];
for (int i = 1; i < size; i++) {
// min number of jumps to reach i
int min = Integer.MAX_VALUE;
for (int j = 0; j < i; j++) {
// if min number of jumps to j < i already > steps to i, no need to compare
if (dp[j] >= min) {
continue;
}
if (j + nums[j] >= i) {
min = Math.min(min, dp[j] + 1);
}
}
dp[i] = min;
}
return dp[dp.length - 1];
}
// best version, greedy algorithm
public int jump(int[] nums) {
int n = nums.length;
int prevReachedPos = 0; // 上一个可以reach到的 position
int minSteps = 0;
int maxReach = 0;
for (int i = 0; i < n - 1; i++) {
maxReach = Math.max(maxReach, i + nums[i]);
// Once the current point reaches curEnd, then trigger another jump
if (i == prevReachedPos) {
minSteps++;
prevReachedPos = maxReach;
if (prevReachedPos == n - 1) {
break;
}
}
}
return minSteps;
}
/*
each time select the max reachable position to jump to
then for loop from last max+1 through this new max
this for loop is one jump, anywhere in this for loop we can choose to be startPosition to jump start
of course this way can guarantee the minimum jump count to reach last index
because each step is maximum jump length
*/
public int jump(int[] A) {
int jumpCnt = 0;
int startPos = 0;
int max = 0;
// int max = 0 + A[0]; // wrong
int newMax = 0;
while (max < A.length - 1) {
jumpCnt++;
for (int i = startPos; i <= max; i++) {
newMax = Math.max(newMax, i + A[i]);
}
startPos = max + 1;
// cannot reach last index
// cannot jump, always stay where it is, A[i] == 0
if (newMax <= max) {
return -1;
}
max = newMax;
}
return jumpCnt;
}
}
| true |
2a36d16291362c96575b16d9da3fca9546a30857 | Java | FruitBrother/computer-network | /MyHttpProxy/ProxyServer_zou/src/ClientToServerThread.java | UTF-8 | 541 | 2.703125 | 3 | [] | no_license | import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by feihu on 2017/5/2.
*/
public class ClientToServerThread extends Thread {
private final int BUFFER_SIZE = (2 << 10)*5;
private InputStream clientIn;
private OutputStream serverOut;
private byte[] buffer = new byte[BUFFER_SIZE];
public ClientToServerThread(InputStream in, OutputStream out) {
this.clientIn = in;
this.serverOut = out;
}
@Override
public void run() {
Utils.pipe(clientIn, serverOut);
}
}
| true |
300ef9da8eb018d456377f7fd1642e3e2a056521 | Java | camel-tooling/camel-language-server | /src/main/java/com/github/cameltooling/lsp/internal/telemetry/Memory.java | UTF-8 | 573 | 2.34375 | 2 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | package com.github.cameltooling.lsp.internal.telemetry;
/**
* JVM memory information
*
* Mostly duplicated from Eclipse Lemminx, the xml language server
*/
public class Memory {
private final long free;
private final long total;
private final long max;
Memory() {
super();
this.free = Runtime.getRuntime().freeMemory();
this.total = Runtime.getRuntime().totalMemory();
this.max = Runtime.getRuntime().maxMemory();
}
public long getFree() {
return free;
}
public long getTotal() {
return total;
}
public long getMax() {
return max;
}
}
| true |
dceec0c5403951aa6fba9c0c6a7516c980743aa4 | Java | tangcco0011/191117 | /src/main/java/cn/kgc/tangcco/tcbd1017/lihaozhe/action/LoginHandler.java | UTF-8 | 1,052 | 2.140625 | 2 | [] | no_license | package cn.kgc.tangcco.tcbd1017.lihaozhe.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.kgc.tangcco.tcbd1017.lihaozhe.service.UserService;
import cn.kgc.tangcco.tcbd1017.lihaozhe.service.impl.UserServiceImpl;
/**
* Servlet implementation class LoginHandler
*/
@WebServlet("/login.action")
public class LoginHandler extends HttpServlet {
private static final long serialVersionUID = -7745510595361767547L;
private static UserService userService = new UserServiceImpl();
/**
* @see HttpServlet#HttpServlet()
*/
public LoginHandler() {
super();
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
userService.saveUser();
}
}
| true |
d4ebc9485fca21eb662831cdbf4a0e222a340c15 | Java | nazrul/basis | /ncra/src/gov/ncra/service/NCRARecordServiceImpl.java | UTF-8 | 848 | 1.90625 | 2 | [] | no_license | package gov.ncra.service;
import gov.ec.ws.NIDService;
import gov.ncra.dao.NCRARecordDao;
import gov.police.ws.PoliceService;
/**
* Created by IntelliJ IDEA.
* User: nazrul
* Date: Jan 20, 2011
* Time: 5:13:30 PM
* To change this template use File | Settings | File Templates.
*/
public class NCRARecordServiceImpl implements NCRARecordService {
private NIDService nIDServiceClient;
private PoliceService policeServiceClient;
private NCRARecordDao ncraRecord;
public void setNcraRecord(NCRARecordDao ncraRecord) {
this.ncraRecord = ncraRecord; }
public void setnIDServiceClient(NIDService nIDServiceClient) {
this.nIDServiceClient = nIDServiceClient;
}
public void setPoliceServiceClient(PoliceService policeServiceClient) {
this.policeServiceClient = policeServiceClient;
}
}
| true |
90def21eb55c0dfbe6b3173399167f7d37dba096 | Java | miarevalo10/ReporteReddit | /reddit-decompilada/com/twitter/sdk/android/tweetui/internal/SpanClickHandler.java | UTF-8 | 4,313 | 2.0625 | 2 | [] | no_license | package com.twitter.sdk.android.tweetui.internal;
import android.annotation.SuppressLint;
import android.text.Layout;
import android.text.Spanned;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;
public class SpanClickHandler {
final View f24232a;
Layout f24233b = null;
float f24234c;
float f24235d;
HighlightedClickableSpan f24236e;
public static void m25958a(TextView textView) {
final SpanClickHandler spanClickHandler = new SpanClickHandler(textView);
textView.setOnTouchListener(new OnTouchListener() {
@SuppressLint({"ClickableViewAccessibility"})
public final boolean onTouch(View view, MotionEvent motionEvent) {
TextView textView = (TextView) view;
Layout layout = textView.getLayout();
if (layout == null) {
return false;
}
spanClickHandler.f24233b = layout;
spanClickHandler.f24234c = (float) (textView.getTotalPaddingLeft() + textView.getScrollX());
spanClickHandler.f24235d = (float) (textView.getTotalPaddingTop() + textView.getScrollY());
view = spanClickHandler;
CharSequence text = view.f24233b.getText();
Spanned spanned = text instanceof Spanned ? (Spanned) text : null;
if (spanned != null) {
int action = motionEvent.getAction() & 255;
int x = (int) (motionEvent.getX() - view.f24234c);
motionEvent = (int) (motionEvent.getY() - view.f24235d);
if (x >= 0 && x < view.f24233b.getWidth() && motionEvent >= null) {
if (motionEvent < view.f24233b.getHeight()) {
motionEvent = view.f24233b.getLineForVertical(motionEvent);
float f = (float) x;
if (f >= view.f24233b.getLineLeft(motionEvent)) {
if (f <= view.f24233b.getLineRight(motionEvent)) {
if (action == 0) {
motionEvent = view.f24233b.getOffsetForHorizontal(motionEvent, f);
HighlightedClickableSpan[] highlightedClickableSpanArr = (HighlightedClickableSpan[]) spanned.getSpans(motionEvent, motionEvent, HighlightedClickableSpan.class);
if (highlightedClickableSpanArr.length > 0) {
motionEvent = highlightedClickableSpanArr[0];
motionEvent.mo5509a(true);
view.f24236e = motionEvent;
view.m25961b();
return true;
}
} else if (action == 1) {
motionEvent = view.f24236e;
if (motionEvent != null) {
motionEvent.onClick(view.f24232a);
view.m25960a();
return true;
}
}
}
}
view.m25960a();
}
}
view.m25960a();
}
return false;
}
});
}
private SpanClickHandler(View view) {
this.f24232a = view;
}
final void m25960a() {
HighlightedClickableSpan highlightedClickableSpan = this.f24236e;
if (highlightedClickableSpan != null && highlightedClickableSpan.mo5510a()) {
highlightedClickableSpan.mo5509a(false);
this.f24236e = null;
m25961b();
}
}
final void m25961b() {
this.f24232a.invalidate((int) this.f24234c, (int) this.f24235d, ((int) this.f24234c) + this.f24233b.getWidth(), ((int) this.f24235d) + this.f24233b.getHeight());
}
}
| true |
ef08f6ddfbb834ef827fec474ea24994c6707941 | Java | itrid-technologies/BusniessApp | /app/src/main/java/com/itridtechnologies/resturantapp/models/orderHistory/ItemsItem.java | UTF-8 | 1,105 | 2.234375 | 2 | [
"MIT"
] | permissive | package com.itridtechnologies.resturantapp.models.orderHistory;
import com.google.gson.annotations.SerializedName;
public class ItemsItem{
@SerializedName("date_added")
private String dateAdded;
@SerializedName("date_modified")
private String dateModified;
@SerializedName("item_price")
private String itemPrice;
@SerializedName("item_name")
private String itemName;
@SerializedName("item_total")
private String itemTotal;
@SerializedName("id")
private int id;
@SerializedName("item_tax")
private String itemTax;
@SerializedName("order_id")
private int orderId;
@SerializedName("item_qty")
private int itemQty;
public String getDateAdded(){
return dateAdded;
}
public String getDateModified(){
return dateModified;
}
public String getItemPrice(){
return itemPrice;
}
public String getItemName(){
return itemName;
}
public String getItemTotal(){
return itemTotal;
}
public int getId(){
return id;
}
public String getItemTax(){
return itemTax;
}
public int getOrderId(){
return orderId;
}
public int getItemQty(){
return itemQty;
}
} | true |
9ed4c389d975e96ccea43f915aa35e3a9993f064 | Java | newbigTech/hryj-mall | /compent/entity-model/src/main/java/com/hryj/entity/vo/staff/user/response/StaffAccountResponseVO.java | UTF-8 | 534 | 1.78125 | 2 | [] | no_license | package com.hryj.entity.vo.staff.user.response;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author 李道云
* @className: StaffAccountResponseVO
* @description: 添加员工响应VO
* @create 2018-07-03 19:04
**/
@Data
@ApiModel(value = "添加员工响应VO")
public class StaffAccountResponseVO {
@ApiModelProperty(value = "员工账号")
private String staff_account;
@ApiModelProperty(value = "密码")
private String login_pwd;
}
| true |
e220e10c39568d28e8d7c2a4a659598516661747 | Java | Ontides/Jigsaw-android | /app/src/main/java/com/example/ontidz/jigsaw/activity/RankActivity.java | UTF-8 | 1,642 | 1.984375 | 2 | [] | no_license | package com.example.ontidz.jigsaw.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.example.ontidz.jigsaw.R;
import com.example.ontidz.jigsaw.common.Grade;
import com.example.ontidz.jigsaw.common.Login;
/**
* Created by ontidz on 2017/4/12.
*/
public class RankActivity extends AppCompatActivity {
private String userName = Login.getUserName();
private String[] data = {
"",
"",
"",
"",
"",
""
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rank);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle("排行榜");
Grade.setGrade(userName, data, RankActivity.this, true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId){
case android.R.id.home:
finish();
break;
case R.id.logout:
Login.setIsLogin(false);
Login.setUserName("");
finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
}
| true |
575c43527229bf24a38cfb08cb97e2c0e07c3e5f | Java | damenac/puzzle | /plugins/fr.inria.diverse.generator.pcm/src/fr/inria/diverse/generator/pcm/SimpleSolver.java | UTF-8 | 2,407 | 2.46875 | 2 | [] | no_license | package fr.inria.diverse.generator.pcm;
import static choco.Choco.eq;
import static choco.Choco.gt;
import static choco.Choco.implies;
import static choco.Choco.makeIntVar;
import java.util.HashMap;
import java.util.Map;
import choco.cp.model.CPModel;
import choco.cp.solver.CPSolver;
import choco.kernel.model.Model;
import choco.kernel.model.constraints.Constraint;
import choco.kernel.model.variables.integer.IntegerVariable;
import choco.kernel.solver.Solver;
import choco.kernel.solver.variables.integer.IntDomainVar;
public class SimpleSolver {
Map<String,IntegerVariable> variables ;
Model p ;
public SimpleSolver(){
p = new CPModel();
variables = new HashMap<String,IntegerVariable>();
}
public void createMandatory(String feature) {
p.addConstraint(eq(variables.get(feature),1));
}
private IntegerVariable createVariable(String feature){
int[] domain = {0,1};
IntegerVariable var = makeIntVar(feature, domain);
variables.put(feature, var);
return var;
}
private IntegerVariable getVariable(String feature){
if(variables.containsKey(feature)){
return variables.get(feature);
}else{
return createVariable(feature);
}
}
public void createRequires(String from, String to){
IntegerVariable originVar = getVariable(from);
IntegerVariable destinationVar = getVariable(to);
Constraint requiresConstraint = implies(gt(originVar, 0), gt(destinationVar, 0));
p.addConstraint(requiresConstraint);
}
public void createExcludes(String from, String to){
IntegerVariable originVar = getVariable(from);
IntegerVariable destinationVar = getVariable(to);
Constraint excludesConstraint = implies(gt(originVar, 0), eq(destinationVar, 0));
p.addConstraint(excludesConstraint);
}
public String solve(){
String PCM = "\"Product\",";
Solver solver = new CPSolver();
solver.read(p);
for(int i = 0; i < p.getNbIntVars(); i ++) {
PCM += solver.getVar(p.getIntVar(i)).getName() + ",";
}
PCM += "\n";
int n=0;
if (solver.solve() == Boolean.TRUE && solver.isFeasible()) {
do {
PCM += "\"P" + (n++) + "\",";
for(int i = 0; i < p.getNbIntVars(); i ++) {
IntDomainVar aux = solver.getVar(p.getIntVar(i));
if(aux.getVal()>0){
PCM += "\"YES\",";
}else{
PCM += "\"NO\",";
}
}
PCM += "\n";
} while(solver.nextSolution() == Boolean.TRUE);
}
return PCM;
}
}
| true |
7001db15d82febd697588d38b47ebfde0aac7a73 | Java | voyage-task-manager/task | /app/src/main/java/database/WorkSchema.java | UTF-8 | 2,799 | 2.453125 | 2 | [] | no_license | package database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import models.Setting;
import models.Task;
import models.Work;
/**
* Created by felipe on 09/10/17.
*/
public class WorkSchema {
public static final String TABLE = "works";
public static final String ID = "_id";
public static final String PAYLOAD = "payload";
public static final String PAYLOADTYPE = "payload_type"; // Hours, days...
public static final String DONE = "done";
public static final String EVENT = "event_id";
public static final String REFERENCES = "reference_id";
private static Database db;
private static SQLiteDatabase conn;
public WorkSchema (Context context) {
db = Database.getInstance(context);
}
public boolean record (Work model) {
conn = db.getWritableDatabase();
ContentValues content = getContent(model);
long res = conn.insert(TABLE, null, content);
conn.close();
return res != -1;
}
private ContentValues getContent (Work model) {
ContentValues content = new ContentValues();
content.put(WorkSchema.EVENT, model.getTask());
content.put(WorkSchema.PAYLOAD, model.getPayload());
content.put(WorkSchema.PAYLOADTYPE, model.getPayloadType());
content.put(WorkSchema.REFERENCES, model.getReference() == -1 ? null : model.getReference());
return content;
}
public static List<Work> find(Context context, String where) {
Cursor cursor;
String[] campos = {
ID, // 0
PAYLOAD, // 1
EVENT, // 2
REFERENCES, // 3
PAYLOADTYPE // 4
};
db = Database.getInstance(context);
conn = db.getReadableDatabase();
cursor = conn.query(TABLE, campos, where, null, null, null, null, null);
List<Work> list = new ArrayList<>();
while (cursor.moveToNext())
list.add(parse(cursor, context));
conn.close();
db.close();
return list;
}
private static Work parse(Cursor cursor, Context context) {
Work work = new Work(context);
work.setID(cursor.getLong(0));
work.setPayload(cursor.getInt(1));
work.setPayloadType(cursor.getInt(4));
work.setTask(cursor.getLong(2));
long ref = cursor.getLong(3);
work.setReference(ref == 0 ? -1 : ref);
return work;
}
public static int delete(Context context, String filter) {
conn = db.getWritableDatabase();
int n = conn.delete(TABLE, filter, null);
conn.close();
return n;
}
}
| true |
bed27ea6c7bdad4720a6eaa4950a6464ced907e6 | Java | DavinderSohal/java | /EpicPatterns.java | UTF-8 | 11,954 | 4.15625 | 4 | [] | no_license | /* -----------------------------------------------------
Assignment # 1
The program when executed will prompt the user to select one of the 4 patterns they want to print and after receiving
valid input, user would have to enter the required number of rows for their pattern and the project will print that
pattern.
For this project we used while, if-else, switch and for loops and imported Scanner java package to take input from the
user.If the input is incorrect or not in expected range, an error message will be displayed accordingly and would
ask the individual to re-enter their values.To handle exceptions we used try and catch method.
-----------------------------------------------------*/
/*
Write a Java program that prints one of the following patterns based on the user choice of a pattern number, which
must be between 1 and 4, or 5 to quit (See examples below), and an input value, which must be larger than 0 and
smaller than 10, and according to the following:
A) If the user enters any invalid pattern number, then the program should display a message indicating that input was
invalid and request the user to either enters a correct pattern number or 5 to quit the entire program. That is, an
entry of 5 would simply terminate the program.
B) Once the pattern number is correctly supplied, the program requests the user to enter the input value. If the user
enters any invalid value that is not within the expected range, then the program should reject this entry and asks
the user to re-enter another value; this would repeat indefinitely until a good value is entered.
C) Upon the entry of a good input value, the program must check whether this value is odd or even. If the user enters
an odd number, then the program would draw a pattern that is similar to the following (i.e. the shown pattern is
drawn if the user enters 5. You should notice that this is only an example; your program must allow for the general
case for different appropriate values as indicated above.) You should notice that the patterns are actually quite
similar whether the input is odd or even, with the exception of pattern # 4. See below:
If the user enters an even number, the pattern would look as one of the following (i.e. the shown pattern is drawn if
the user enters 4. Again this is just an example; your program must work for the general case.)
*/
import java.util.Scanner;
class EpicPatterns /*created class named EpicPatterns*/{
public static void main(String[] args){
System.out.println("\n----Welcome to Davinder (2092836) and Navneet's (2092453) Pattern Generator Program----");
Scanner sc = new Scanner(System.in); /*created scanner object*/
try /*using try and catch method to handle exceptions, like if a string value is entered instead of int or to
deal with any other sort of error.*/{
while(true) /*using while to create an infinite loop.*/{
System.out.println(
"---------------------------------------------------------------------------------------");
System.out.println("\nWhich pattern do you want to print?\n");/*show patterns for user to select from*/
System.out.println("1) 5 4 3 2 1 2) 1 3) 1 2 3 4 5 4) 1 ");
System.out.println(" 5 4 3 2 1 2 2 3 4 5 1 2 3 ");
System.out.println(" 5 4 3 1 2 3 3 4 5 1 2 3 4 5 ");
System.out.println(" 5 4 1 2 3 4 4 5 1 2 3 ");
System.out.println(" 5 1 2 3 4 5 5 1 ");
System.out.print("\nEnter your choice (5 to Quit) : "); /*requesting input from user*/
int choice = sc.nextInt(); /*Read user input*/
if(choice < 1 || choice > 5) /*checking whether option selected is within valid value frame.*/{
System.out.println("\nERROR: \"" + choice + "\" is an invalid entry."); /*display error message.*/
System.out.print("\t\tTry again and please enter a number between 1 and 5(inclusive) only.\n");
continue; /*Skips the remaining code and re-run the while loop.*/
}else if(choice == 5) /*terminating the project if 5 is pressed.*/{
System.out.println("\nBye, have a nice day! \( ・_・) ");
sc.close(); /*closing Scanner object before terminating program.*/
System.exit(0); /*exit program.*/
}
System.out.print("Please enter number of rows(between 0 to 10) you would like to print: ");
/*asking user to enter number of rows*/
int rows = sc.nextInt(); /*Reading input form user.*/
while(rows < 1 || rows > 9) /*checking whether input is valid or not.If invalid, request for a correct
value until received.*/{
System.out.println("\nERROR: \"" + rows + "\" is an invalid entry. Try again.\n"); /*Error message*/
System.out.print("Please enter number of rows(between 0 to 10) you would like to print: ");
rows = sc.nextInt(); /*Reading user input.*/
}
switch(choice) /*switch statement to create different patterns as per the value of choice which we
took from the user.*/{
case 1:{ /*case 1 to print 1st pattern*/
System.out.printf("\nYou chose pattern number 1 with %d row(s).\n", rows);
System.out.println("Here is your pattern:\n");
for(int i = 1; i <= rows; i++)/*Using for loop to print rows and columns of desired pattern*/{
int num = rows;
for(int j = rows; j >= i; j--){
System.out.print(num + " "); /*prints the pattern*/
num--; /*decrementing the value of variable num.*/
}
System.out.println(); /*to goto next line*/
}
}
break; /*Skip the rest of cases and end switch*/
case 2:{ /*case 2 to print 2nd pattern*/
System.out.printf("\nYou chose pattern number 2 with %d row(s).\n", rows);
System.out.println("Here is your pattern:\n");
for(int i = 1; i <= rows; i++){
for(int j = rows - 1; j >= i; j--){
System.out.print(" "); /*To print white space*/
}
int num = 1;
for(int k = 1; k <= i; k++){
System.out.print(num + " "); /*prints the integer values of pattern*/
num++; /*incrementing the value of variable num.*/
}
System.out.println(); /*next line*/
}
}
break; /*Skip the rest of cases and end switch*/
case 3:{ /*case 3 to print 3rd pattern.*/
System.out.printf("\nYou chose pattern number 3 with %d row(s).\n", rows);
System.out.println("Here is your pattern:\n");
for(int i = 1; i <= rows; i++){
for(int j = 2; j <= i; j++){
System.out.print(" "); /*print white space.*/
}
for(int k = i; k <= rows; k++){
System.out.print(k + " "); /*print integer values.*/
}
System.out.println(); /*Move to next line*/
}
}
break; /*Skip the rest of cases and end switch*/
case 4:{ /*case 4 to print 4th pattern.*/
System.out.printf("\nYou chose pattern number 4 with %d row(s).\n", rows);
System.out.println("Here is your pattern:\n");
for(int i = 1; i <= rows; i += 2){
for(int j = rows - 1; j >= i; j--){
System.out.print(" "); /*print white space.*/
}
int num = 1;
for(int k = 1; k <= i; k++){
System.out.print(num + " "); /*print integer values.*/
num++; /*incrementing the value of variable num.*/
}
System.out.println();
}
if(rows % 2 == 0) /*Checking if number of rows entered are odd or even.*/{
for(int i = rows - 1; i >= 1; i -= 2) /*if even execute this block*/{
for(int j = rows - 1; j >= i; j--){
System.out.print(" "); /*print white space*/
}
int num = 1;
for(int k = 1; k <= i; k++){
System.out.print(num + " "); /*print integer values for pattern*/
num++; /*incrementing the value of variable num.*/
}
System.out.println();
}
}else{
for(int i = rows - 2; i >= 1; i -= 2) /*if odd execute this block*/{
for(int j = rows - 1; j >= i; j--){
System.out.print(" "); /*print white space*/
}
int num = 1;
for(int k = 1; k <= i; k++){
System.out.print(num + " "); /*print integer values for the pattern*/
num++; /*incrementing the value of variable num.*/
}
System.out.println();
}
}
}
break; /*Skip the rest of cases and end switch*/
default:
throw new IllegalStateException("Unexpected value: " + choice); /* throwing an error message
for an unexpected state*/
}
System.out.print("\nPress ENTER key to continue..... "); /*prompting user to press ENTER key*/
sc.nextLine(); /* will end the nextInt() that was used before*/
sc.nextLine(); /*read input*/
}
}catch(Exception e) /*catch to used to manage any error encountered and display an error message.*/{
System.out.println("\nERROR: Unexpected value. Please enter only valid integer value (spaces or other " +
"String values are not allowed)");
System.out.print("\nPress ENTER key to restart. ");
sc.nextLine(); /*will end the nextInt() or nextLine() that was used before*/
sc.nextLine();/*read input*/
main(args); /*re-run the program by making recursive call to main method.*/
}
}
}
/* Last Modified on December 5th,2020 9:50PM IST.
Thank you */
| true |
9b85bd0d824826797b48e5aeadca601d73175ccf | Java | rodixxi/automate | /Gestar/src/main/java/com/harriague/automate/web/control/Attachment.java | UTF-8 | 290 | 1.835938 | 2 | [] | no_license | package com.harriague.automate.web.control;
import org.openqa.selenium.By;
public interface Attachment{
By getInputButton();
By getAddButton();
By getDeleteButton();
By getCloseButton();
By getAttachButton();
By getAttatchName();
By getCssSelector();
}
| true |
b672830f1e8a907fcf9fd8e127195a2a775ab2bb | Java | xujing1123/miaosha | /miaosha_1/src/main/java/com/xujing/miaosha/controller/GoodsController.java | UTF-8 | 7,543 | 2.078125 | 2 | [] | no_license | package com.xujing.miaosha.controller;
import com.xujing.miaosha.entity.MiaoshaUser;
import com.xujing.miaosha.redis.GoodsKey;
import com.xujing.miaosha.redis.RedisService;
import com.xujing.miaosha.result.Result;
import com.xujing.miaosha.service.GoodsService;
import com.xujing.miaosha.service.MiaoshaUserService;
import com.xujing.miaosha.vo.GoodsDetailVO;
import com.xujing.miaosha.vo.GoodsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.spring4.context.SpringWebContext;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Controller
@RequestMapping("/goods")
public class GoodsController {
@Autowired
MiaoshaUserService miaoshaUserService;
@Autowired
RedisService redisService;
@Autowired
GoodsService goodsService;
@Autowired
ThymeleafViewResolver thymeleafViewResolver;
@Autowired
ApplicationContext applicationContext;
/* @RequestMapping("/toList")
public String toList(Model model,MiaoshaUser user){
// 查询商品列表
List<GoodsVo> goodsList = goodsService.listGoodsVo();
model.addAttribute("goodsList", goodsList);
model.addAttribute("user", user);
return "goods_list";
}*/
/**
* 2.3压力测试
*
* */
@RequestMapping(value = "/toList",produces = "text/html")
@ResponseBody
public String toList(HttpServletRequest request, HttpServletResponse response, Model model, MiaoshaUser user){
model.addAttribute("user", user);
//从缓存中取值
String html = redisService.get(GoodsKey.getGoodsList, "", String.class);
if(!StringUtils.isEmpty(html)){
return html;
}
//return "goods_list";
// 查询商品列表
List<GoodsVo> goodsList = goodsService.listGoodsVo();
model.addAttribute("goodsList", goodsList);
// 手动渲染
SpringWebContext ctx = new SpringWebContext(request, response, request.getServletContext(),
request.getLocale(), model.asMap(), applicationContext);
html = thymeleafViewResolver.getTemplateEngine().process("goods_list",ctx);
if(!StringUtils.isEmpty(html)){
redisService.set(GoodsKey.getGoodsList,"",html);
}
return html;
}
/* @RequestMapping("/to_detail/{goodsId}")
public String detail(Model model,MiaoshaUser user,
@PathVariable("goodsId")long goodsId) {
GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
long startAt = goods.getStartDate().getTime();
long endAt = goods.getEndDate().getTime();
long now = System.currentTimeMillis();
int miaoshaStatus = 0;
int remainSeconds = 0; // 计算多少秒结束
if(now <startAt){ // 活动未开始
miaoshaStatus = 0;
remainSeconds = (int)((startAt-now)/1000);
}else if( now> endAt) // 活动结束
{
miaoshaStatus =2;
remainSeconds = -1;
}else // 正常秒杀
{
miaoshaStatus = 1;
remainSeconds = 0;
}
model.addAttribute("user", user);
model.addAttribute("goods", goods);
model.addAttribute("miaoshaStatus", miaoshaStatus);
model.addAttribute("remainSeconds", remainSeconds);
return "goods_detail";
}*/
/**
* 页面缓存
*
* */
@RequestMapping(value = "/to_detail2/{goodsId}",produces = "text/html")
@ResponseBody
public String detail2(HttpServletRequest request, HttpServletResponse response,Model model,MiaoshaUser user,
@PathVariable("goodsId")long goodsId) {
String html = redisService.get(GoodsKey.getGoodsDetail, ""+goodsId, String.class);
if(!StringUtils.isEmpty(html)){
return html;
}
GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
long startAt = goods.getStartDate().getTime();
long endAt = goods.getEndDate().getTime();
long now = System.currentTimeMillis();
int miaoshaStatus = 0;
int remainSeconds = 0; // 计算多少秒结束
if(now <startAt){ // 活动未开始
miaoshaStatus = 0;
remainSeconds = (int)((startAt-now)/1000);
}else if( now> endAt) // 活动结束
{
miaoshaStatus =2;
remainSeconds = -1;
}else // 正常秒杀
{
miaoshaStatus = 1;
remainSeconds = 0;
}
model.addAttribute("user", user);
model.addAttribute("goods", goods);
model.addAttribute("miaoshaStatus", miaoshaStatus);
model.addAttribute("remainSeconds", remainSeconds);
// 手动渲染
SpringWebContext ctx = new SpringWebContext(request, response, request.getServletContext(),
request.getLocale(), model.asMap(), applicationContext);
html = thymeleafViewResolver.getTemplateEngine().process("goods_detail",ctx);
if(!StringUtils.isEmpty(html)){
redisService.set(GoodsKey.getGoodsDetail,""+goodsId,html);
}
return html;
//return "goods_detail";
}
/**
* 前后端分离
*
* */
@RequestMapping(value = "/detail/{goodsId}")
@ResponseBody
public Result<GoodsDetailVO> detail(HttpServletRequest request, HttpServletResponse response,Model model,MiaoshaUser user,
@PathVariable("goodsId")long goodsId) {
GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
long startAt = goods.getStartDate().getTime();
long endAt = goods.getEndDate().getTime();
long now = System.currentTimeMillis();
int miaoshaStatus = 0;
int remainSeconds = 0; // 计算多少秒结束
if(now <startAt){ // 活动未开始
miaoshaStatus = 0;
remainSeconds = (int)((startAt-now)/1000);
}else if( now> endAt) // 活动结束
{
miaoshaStatus =2;
remainSeconds = -1;
}else // 正常秒杀
{
miaoshaStatus = 1;
remainSeconds = 0;
}
GoodsDetailVO detailVO = new GoodsDetailVO();
detailVO.setUser(user);
detailVO.setGoods(goods);
detailVO.setMiaoshaStatus(miaoshaStatus);
detailVO.setRemainSeconds(remainSeconds);
return Result.success(detailVO);
}
@GetMapping("/getById/{goodsId}")
public ResponseEntity<GoodsVo> getById(@PathVariable("goodsId") Integer goodsId) {
GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
String version = UUID.randomUUID().toString();
return ResponseEntity.ok().cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
.eTag(version).body(goods);
}
}
| true |
f080901617c4070c8a6b50f9d690db0ec853a83d | Java | kiaha1230/StaffManagement | /src/main/java/com/team3/repository/RecordRepository.java | UTF-8 | 205 | 1.679688 | 2 | [] | no_license | package com.team3.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.team3.model.Record;
public interface RecordRepository extends JpaRepository<Record, Integer> {
}
| true |
c0450a19494edb39a8f1ca7235062ebdae5d1d5a | Java | Suedo/SpringJpaPs | /conference-demo/src/main/java/com/pluralsight/conferencedemo/repositories/TicketPriceJpaRepository.java | UTF-8 | 475 | 1.710938 | 2 | [] | no_license | package com.pluralsight.conferencedemo.repositories;
import com.pluralsight.conferencedemo.models.Speaker;
import com.pluralsight.conferencedemo.models.TicketPrice;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
public interface TicketPriceJpaRepository extends JpaRepository<TicketPrice, Long> {
}
| true |
8ff134cd6c772b120857da0212f2e80947391ebc | Java | borisstojanovic/GeRuDok | /src/gerudok/actions/RedoAction.java | UTF-8 | 923 | 2.203125 | 2 | [] | no_license | package gerudok.actions;
import gerudok.app.MyJFrame;
import gerudok.errorhandler.ErrorHandlerSimpleFactory;
import gerudok.errorhandler.ExceptionEnum;
import gerudok.model.Page;
import gerudok.view.PageView;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class RedoAction extends MyAbstractAction {
public RedoAction(){
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(
KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
putValue(NAME, "Redo");
putValue(SMALL_ICON, loadIcon("Redo-icon.png"));
putValue(SHORT_DESCRIPTION, "Redo");
}
@Override
public void actionPerformed(ActionEvent e) {
try {
MyJFrame.getInstance().getCommandManager().doCommand();
}catch (NullPointerException e1){
ErrorHandlerSimpleFactory.generateError(ExceptionEnum.NO_SELECTED_PAGE);
}
}
}
| true |
806fd299008d742b89105bb3bfbd6a8b56d50d63 | Java | pjyothsna/JSONRW | /src/main/java/com/comcast/json/lulzInterface.java | UTF-8 | 274 | 1.921875 | 2 | [] | no_license | package com.comcast.json;
import java.util.HashMap;
import java.util.Map;
public interface lulzInterface {
//Map<String, Integer> lulzMap = new HashMap<String,Integer>();
public Map<String, Integer> getLulzMap();
public void setLulMap(Map<String, Integer> lulzMap);
}
| true |
2ef49112e530330b4a278b695c63301b0651c4f5 | Java | rahulmen/MultiThreading | /src/main/java/com/learning/InterviewPreparation/DesignPattern/FactoryPatternDemo2/MiniCar.java | UTF-8 | 304 | 3.0625 | 3 | [] | no_license | package com.learning.InterviewPreparation.DesignPattern.FactoryPatternDemo2;
public class MiniCar extends Car {
MiniCar(CarType carType){
super(carType);
carfeature();
}
@Override
public void carfeature(){
System.out.print("MINI CAR IS A AVERAGE CAR");
}
}
| true |
e555021a9f5eca06e7346ec8e46b83167c0c0a55 | Java | TheWizardNik/archproject | /src/main/java/com/arhproject/start/jpa/domain/Publication.java | UTF-8 | 1,549 | 2.0625 | 2 | [] | no_license | package com.arhproject.start.jpa.domain;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "publication")
@Getter
@Setter
public class Publication {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "title", nullable = false)
private String title;
@Column(name = "text", nullable = false)
private String text;
@Column(name = "image", nullable = false)
private String image;
@OneToMany(mappedBy = "publication", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private List<Comment> comments = new ArrayList<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "publication_user",
joinColumns = {@JoinColumn(name = "publication_id", referencedColumnName = "id", nullable = false)},
inverseJoinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id", nullable = false)}
)
private List<User> authors = new ArrayList<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "publication_tag",
joinColumns = {@JoinColumn(name = "publication_id", referencedColumnName = "id", nullable = false)},
inverseJoinColumns = {@JoinColumn(name = "tag_id", referencedColumnName = "id", nullable = false)}
)
private List<Tag> tags = new ArrayList<>();
@Embedded
private AuditEmbeddable audit = new AuditEmbeddable();
}
| true |
3f958b81fab7c96f1a23371e68c3a1852129b4a8 | Java | raghavgh/Miwok | /app/src/main/java/com/example/miwok/WordAdapter.java | UTF-8 | 2,706 | 2.53125 | 3 | [] | no_license | package com.example.miwok;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class WordAdapter extends ArrayAdapter<Word> {
private int color;
public WordAdapter(Context context, ArrayList<Word> words,int color)
{
super(context,0,words);
this.color = color;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView;
listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
// Get the {@link AndroidFlavor} object located at this position in the list
Word word = getItem(position);
// Find the TextView in the list_item.xml layout with the ID version_name
TextView nameTextView = listItemView.findViewById(R.id.trans);
// Get the version name from the current AndroidFlavor object and
// set this text on the name TextView
nameTextView.setText(word != null ? word.getMiwokTranslation() : null);
// Find the TextView in the list_item.xml layout with the ID version_number
TextView numberTextView = listItemView.findViewById(R.id.name);
// Get the version number from the current AndroidFlavor object and
// set this text on the number TextView
numberTextView.setText(word != null ? word.getDefaultTranslation() : null);
// Find the ImageView in the list_item.xml layout with the ID list_item_icon
ImageView imageView= listItemView.findViewById(R.id.image);
//ImageView iconView = (ImageView) listItemView.findViewById(R.id.list_item_icon);
// Get the image resource ID from the current AndroidFlavor object and
// set the image to iconView
if(word.hasImage()){
imageView.setImageResource(word.getImageResourceId());
}
else {
imageView.setVisibility(View.GONE);
}
//iconView.setImageResource(currentAndroidFlavor.getImageResourceId());
// Return the whole list item layout (containing 2 TextViews and an ImageView)
// so that it can be shown in the ListView
View textcontainer = listItemView.findViewById(R.id.text_container);
int col = ContextCompat.getColor(getContext(),color);
textcontainer.setBackgroundColor(col);
return listItemView;
}
}
| true |
0d8db976f8b1316358452f26ec69d9122805f3f9 | Java | annihilator01/server-api-university-practice | /src/main/java/com/universitypractice/springapplication/services/interfaces/baseoperations/UpdateService.java | UTF-8 | 165 | 2.03125 | 2 | [] | no_license | package com.universitypractice.springapplication.services.interfaces.baseoperations;
public interface UpdateService<T, F> {
T update(F filter, T updateInfo);
}
| true |
34ea173a1fac0ecb231ba3be116fa5ef2c487ee9 | Java | trifonnt/SpringBootMultiTenancy | /SpringBootMultiTenancy/src/main/java/de/bytefish/multitenancy/web/configuration/JerseyConfig.java | UTF-8 | 1,064 | 1.914063 | 2 | [
"MIT"
] | permissive | // Copyright (c) Philipp Wagner. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package de.bytefish.multitenancy.web.configuration;
import de.bytefish.multitenancy.web.filters.TenantNameFilter;
import de.bytefish.multitenancy.web.resources.CustomerResource;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.context.annotation.Configuration;
/**
* Jersey Configuration (Resources, Modules, Filters, ...)
*/
@Configuration
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
// Register the Filters:
register(TenantNameFilter.class);
// Register the Resources:
register(CustomerResource.class);
// Uncomment to disable WADL Generation:
//property("jersey.config.server.wadl.disableWadl", true);
// Uncomment to add Request Tracing:
//property("jersey.config.server.tracing.type", "ALL");
//property("jersey.config.server.tracing.threshold", "TRACE");
}
}
| true |
db222037025717f614ae5db41bad6618efd1ac22 | Java | zjt0428/emms_GXDD | /emms_GXDD/src/com/knight/emms/web/action/IndisNoticeAction.java | UTF-8 | 3,076 | 2.03125 | 2 | [] | no_license | /**
*====================================================
* 文件名称: IndisNoticeAction.java
* 修订记录:
* No 日期 作者(操作:具体内容)
* 1. 2016年8月26日 chenxy(创建:创建文件)
*====================================================
* 类描述:(说明未实现或其它不应生成javadoc的内容)
*/
package com.knight.emms.web.action;
import java.util.List;
import javax.annotation.Resource;
import com.knight.core.filter.QueryFilter;
import com.knight.core.log.ActionLog;
import com.knight.core.util.GsonUtil;
import com.knight.core.web.action.BaseAction;
import com.knight.emms.model.IndisNotice;
import com.knight.emms.model.IndisSchema;
import com.knight.emms.service.IndisNoticeService;
import com.knight.emms.service.IndisSchemaService;
import lombok.Getter;
import lombok.Setter;
/**
* @ClassName: IndisNoticeAction
* @Description: TODO(这里用一句话描述这个类的作用)
* @author chenxy
* @date 2016年8月26日 上午11:47:34
*/
public class IndisNoticeAction extends BaseAction {
private static final long serialVersionUID = 1L;
@Getter
@Setter
private IndisNotice indisNotice;
@Getter
@Setter
private Long noticeId;
@Resource
private IndisNoticeService indisNoticeService;
@Resource
private IndisSchemaService indisSchemaService;
public String list() {
QueryFilter filter = new QueryFilter(getRequest());
List<IndisNotice> list = indisNoticeService.queryTranslateAllFull(filter);
StringBuffer buff = new StringBuffer("{success:true,'totalCounts':").append(filter.getPagingBean().getTotalItems()).append(",result:");
buff.append(GsonUtil.toJson(list));
buff.append("}");
this.jsonString = buff.toString();
return SUCCESS;
}
public String load() {
IndisNotice c = indisNoticeService.getTranslateFull(noticeId);
StringBuffer sb = new StringBuffer("{success:true,data:[");
sb.append(GsonUtil.toJson(c, false));
sb.append("]}");
setJsonString(sb.toString());
return SUCCESS;
}
@ActionLog(description = "保存或更新安拆告知")
public String save() {
IndisSchema indisSchema = indisSchemaService.get(indisNotice.getSchemaId());
if (indisNotice.getNoticeId() == null) {
indisNotice.setIndisSchema(indisSchema);
super.isCreateFileAttach = true;
} else {
IndisNotice p = indisNoticeService.get(indisNotice.getNoticeId());
indisNotice.setIndisSchema(p.getIndisSchema());
indisNotice.setRelateModule(p.getRelateModule());
}
indisNoticeService.saveOrMergeForEdit(indisNotice);
createFileAttach(indisNotice.getNoticeId());
return SUCCESS;
}
@ActionLog(description = "删除安拆告知")
public String multiDel() {
String[] ids = getRequest().getParameterValues("ids");
for (String id : ids) {
indisNoticeService.remove(new Long(id));
}
return SUCCESS;
}
@ActionLog(description = "删除安拆告知人员")
public String multiDelPracti() {
String[] ids = getRequest().getParameterValues("ids");
for (String id : ids) {
indisNoticeService.deletePracti(new Long(id));
}
return SUCCESS;
}
}
| true |
8a3aac7fbaa35f7eac9f26c47fda68fd290d7316 | Java | 2550462328/daily-java-test | /src/main/java/cn/zhanghui/demo/daily/jdk8_newProp/forkjoin/ForkJoin_v3.java | UTF-8 | 734 | 3.28125 | 3 | [] | no_license | package cn.zhanghui.demo.daily.jdk8_newProp.forkjoin;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* @ClassName: ForkJoin_v2.java
* @Description: 这是jdk1.8 使用Stream的并行流的排序方式(实质也是fork/join)
* @author: ZhangHui
* @date: 2019年11月6日 下午5:16:17
*/
public class ForkJoin_v3 {
public static Integer[] parallelSort(Integer[] array) {
List<Integer> tmp = new ArrayList<Integer>();
Collections.addAll(tmp, array);
List<Integer> tmp1 = tmp.stream().parallel().mapToInt(Integer::intValue).sorted().boxed().collect(Collectors.toList());
return tmp1.toArray(new Integer[0]);
}
}
| true |
a5c4551849edd63d079d4e7c28a7276b5794f36e | Java | rainkun/explainable | /src/test/java/com/github/explainable/benchmark/ConjunctionGeneratorTest.java | UTF-8 | 9,233 | 2.140625 | 2 | [] | no_license | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Gabriel Bender
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.explainable.benchmark;
import com.github.explainable.corelang.Atom;
import com.github.explainable.corelang.Conjunction;
import com.github.explainable.corelang.Relation;
import com.github.explainable.corelang.RelationImpl;
import com.github.explainable.corelang.Term;
import com.github.explainable.corelang.View;
import com.google.common.collect.ImmutableList;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Random;
import static com.github.explainable.corelang.Terms.constant;
import static com.github.explainable.corelang.Terms.dist;
import static com.github.explainable.corelang.Terms.set;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit testNextWithDefaultDist_s for {@link ConjunctionGenerator}.
*/
public class ConjunctionGeneratorTest {
private Random random = null;
@Before
public void setUp() {
random = new Random(-1702765630L);
}
@After
public void tearDown() {
random = null;
}
@Test
public void testNextWithDefaultDist_simple() {
Relation relR = RelationImpl.create("R", ImmutableList.of("x", "y"));
Relation relS = RelationImpl.create("S", ImmutableList.of("z", "w"));
Term dist1 = dist();
Term dist2 = dist();
View view1 = View.asView(
Atom.asMultisetAtom(relR, dist1, dist2),
Atom.asSetAtom(relS, dist1, dist2));
ConjunctionGenerator viewGen = ConjunctionGenerator.create(ImmutableList.of(view1), random);
Conjunction actual = viewGen.nextWithDefaultDist();
Conjunction expected = Conjunction.create(ImmutableList.of(
Atom.asMultisetAtom(relR, dist1, dist2),
Atom.asSetAtom(relS, dist1, dist2)));
assertTrue(expected.isHomomorphicTo(actual));
}
@Test
public void testNextWithDefaultDist_recursive() {
Relation relR = RelationImpl.create("R", ImmutableList.of("x"));
View view = View.asView(
Atom.asMultisetAtom(relR, dist()),
Atom.asSetAtom(relR, set()));
Conjunction expected = Conjunction.create(ImmutableList.of(
Atom.asMultisetAtom(relR, dist()),
Atom.asSetAtom(relR, set())));
ConjunctionGenerator viewGen = ConjunctionGenerator.create(ImmutableList.of(view), random);
Conjunction actual = viewGen.nextWithDefaultDist();
assertTrue(expected.isHomomorphicTo(actual));
}
@Test
public void testNextWithDefaultDist_chainSubstitution1() {
Relation relR = RelationImpl.create("R", ImmutableList.of("x", "y"));
Relation relS = RelationImpl.create("S", ImmutableList.of("z", "w"));
Relation relT = RelationImpl.create("T", ImmutableList.of("a", "b"));
Term dist1 = dist();
Term dist2 = dist();
View view1 = View.asView(
Atom.asMultisetAtom(relR, dist1, dist2),
Atom.asSetAtom(relS, dist1, dist2));
View view2 = View.asView(
Atom.asMultisetAtom(relS, constant(1L), constant(2L)),
Atom.asSetAtom(relT, set(), set()));
Conjunction expectedOption1 = Conjunction.create(ImmutableList.of(
Atom.asMultisetAtom(relS, constant(1L), constant(2L)),
Atom.asSetAtom(relT, set(), set())));
Conjunction expectedOption2 = Conjunction.create(ImmutableList.of(
Atom.asMultisetAtom(relR, constant(1L), constant(2L)),
Atom.asSetAtom(relS, constant(1L), constant(2L)),
Atom.asSetAtom(relT, set(), set())));
ConjunctionGenerator viewGen = ConjunctionGenerator.create(
ImmutableList.of(view1, view2),
random);
boolean[] witnessed = new boolean[2];
for (int i = 0; i < 10; i++) {
Conjunction actual = viewGen.nextWithDefaultDist();
if (expectedOption1.isHomomorphicTo(actual)) {
witnessed[0] = true;
} else if (expectedOption2.isHomomorphicTo(actual)) {
witnessed[1] = true;
} else {
fail();
}
}
// There are two possible outputs. Make sure that each of them is observed at least once
// among our ten runs.
assertTrue(witnessed[0]);
assertTrue(witnessed[1]);
}
@Test
public void testNextWithDefaultDist_chainSubstitution2() {
Relation relR = RelationImpl.create("R", ImmutableList.of("x", "y"));
Relation relS = RelationImpl.create("S", ImmutableList.of("z", "w"));
Relation relT = RelationImpl.create("T", ImmutableList.of("a", "b"));
View view1 = View.asView(
Atom.asMultisetAtom(relR, set(), set()),
Atom.asSetAtom(relS, constant(1L), constant(2L)));
Term dist1 = dist();
Term dist2 = dist();
View view2 = View.asView(
Atom.asMultisetAtom(relS, dist1, dist2),
Atom.asSetAtom(relT, dist1, dist2));
Conjunction expectedOption1 = Conjunction.create(ImmutableList.of(
Atom.asMultisetAtom(relS, dist1, dist2),
Atom.asSetAtom(relT, dist1, dist2)));
Conjunction expectedOption2 = Conjunction.create(ImmutableList.of(
Atom.asMultisetAtom(relR, set(), set()),
Atom.asSetAtom(relS, constant(1L), constant(2L)),
Atom.asSetAtom(relT, constant(1L), constant(2L))));
ConjunctionGenerator viewGen = ConjunctionGenerator.create(
ImmutableList.of(view1, view2),
random);
boolean[] witnessed = new boolean[2];
for (int i = 0; i < 10; i++) {
Conjunction actual = viewGen.nextWithDefaultDist();
if (expectedOption1.isHomomorphicTo(actual)) {
witnessed[0] = true;
} else if (expectedOption2.isHomomorphicTo(actual)) {
witnessed[1] = true;
} else {
fail();
}
}
// There are two possible outputs. Make sure that each of them is observed at least once
// among our ten runs.
assertTrue(witnessed[0]);
assertTrue(witnessed[1]);
}
@Test
public void testNextWithNoDist_simple() {
Relation relR = RelationImpl.create("R", ImmutableList.of("x", "y"));
Relation relS = RelationImpl.create("S", ImmutableList.of("z", "w"));
Term dist1 = dist();
Term dist2 = dist();
View view1 = View.asView(
Atom.asMultisetAtom(relR, dist1, dist2),
Atom.asSetAtom(relS, dist1, dist2));
ConjunctionGenerator viewGen = ConjunctionGenerator.create(ImmutableList.of(view1), random);
Conjunction actual = viewGen.nextWithNoDist();
Term set1 = set();
Term set2 = set();
Conjunction expected = Conjunction.create(ImmutableList.of(
Atom.asMultisetAtom(relR, set1, set2),
Atom.asSetAtom(relS, set1, set2)));
assertTrue(expected.isHomomorphicTo(actual));
}
@Test
public void testNextWithRandomDist_simple() {
Relation relR = RelationImpl.create("R", ImmutableList.of("x", "y"));
Relation relS = RelationImpl.create("S", ImmutableList.of("z", "w"));
Term viewDist1 = dist();
Term viewDist2 = dist();
View view1 = View.asView(
Atom.asMultisetAtom(relR, viewDist1, viewDist2),
Atom.asSetAtom(relS, viewDist1, viewDist2));
ConjunctionGenerator viewGen = ConjunctionGenerator.create(ImmutableList.of(view1), random);
Term set1 = set();
Term set2 = set();
Term dist1 = dist();
Term dist2 = dist();
Conjunction[] expectedOptions = new Conjunction[] {
Conjunction.create(ImmutableList.of(
Atom.asMultisetAtom(relR, set1, set2),
Atom.asSetAtom(relS, set1, set2))),
Conjunction.create(ImmutableList.of(
Atom.asMultisetAtom(relR, set1, dist2),
Atom.asSetAtom(relS, set1, dist2))),
Conjunction.create(ImmutableList.of(
Atom.asMultisetAtom(relR, dist1, set2),
Atom.asSetAtom(relS, dist1, set2))),
Conjunction.create(ImmutableList.of(
Atom.asMultisetAtom(relR, dist1, dist2),
Atom.asSetAtom(relS, dist1, dist2)))
};
boolean[] observed = new boolean[4];
// There are two possible outputs. Make sure that each of them is observed at least once
// among our 100 trials.
for (int trial = 0; trial < 100; trial++) {
Conjunction actual = viewGen.nextWithRandomDist(1.0);
if (expectedOptions[0].isHomomorphicTo(actual)) {
observed[0] = true;
} else if (expectedOptions[1].isHomomorphicTo(actual)) {
observed[1] = true;
} else if (expectedOptions[2].isHomomorphicTo(actual)) {
observed[2] = true;
} else if (expectedOptions[3].isHomomorphicTo(actual)) {
observed[3] = true;
} else {
fail("Illegal output: " + actual);
}
}
assertTrue(observed[0]);
assertTrue(observed[1]);
assertTrue(observed[2]);
assertTrue(observed[3]);
}
} | true |
fcafc1fb11e8b721a48651b02402132a9607b703 | Java | pcingola/SnpEff | /src/main/java/org/snpeff/util/Download.java | UTF-8 | 14,793 | 2.625 | 3 | [
"MIT"
] | permissive | package org.snpeff.util;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
* Command line program: Build database
*
* @author pcingola
*/
public class Download {
public static final int DEFAULT_PROXY_PORT = 80;
private static final int BUFFER_SIZE = 102400;
boolean debug = false;
boolean verbose = false;
boolean update; // Are we updating SnpEff itself?
boolean maskDownloadException = false;
public Download() {
}
/**
* File name from URL (i.e. anything after the last '/')
*/
public static String urlBaseName(String url) {
String[] f = url.split("/");
String base = f[f.length - 1];
int qidx = base.indexOf('?');
if (qidx > 0) base = base.substring(0, qidx);
return base;
}
/**
* Add files to 'backup' ZIP file
*/
void backupFile(ZipOutputStream zos, String fileName) {
try {
FileInputStream fis = new FileInputStream(fileName);
zos.putNextEntry(new ZipEntry(fileName));
int len;
byte[] buf = new byte[BUFFER_SIZE];
while ((len = fis.read(buf)) > 0)
zos.write(buf, 0, len);
zos.closeEntry();
fis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public boolean download(String urlString, String localFile) {
try {
URL url = new URL(urlString);
return download(url, localFile);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
/**
* Download a file
*/
public boolean download(URL url, String localFile) {
boolean res = false;
try {
sslSetup(); // Set up SSL for websites having issues with certificates (e.g. Sourceforge)
if (verbose) Log.info("Connecting to " + url);
URLConnection connection = openConnection(url);
// Follow redirect? (only for http connections)
if (connection instanceof HttpURLConnection) {
for (boolean followRedirect = true; followRedirect; ) {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
if (verbose) Log.info("Connecting to " + url + ", using proxy: " + httpConnection.usingProxy());
int code = httpConnection.getResponseCode();
if (code == 200) {
followRedirect = false; // We are done
} else if (code == 302) {
String newUrl = connection.getHeaderField("Location");
if (verbose) Log.info("Following redirect: " + newUrl);
url = new URL(newUrl);
connection = openConnection(url);
} else if (code == 404) {
throw new RuntimeException("File not found on the server. Make sure the database name is correct.");
} else throw new RuntimeException("Error code from server: " + code);
}
}
// Copy resource to local file, use remote file if no local file name specified
InputStream is = connection.getInputStream();
// Print info about resource
Date date = new Date(connection.getLastModified());
if (debug) Log.debug("Copying file (type: " + connection.getContentType() + ", modified on: " + date + ")");
// Open local file
if (verbose) Log.info("Local file name: '" + localFile + "'");
// Create local directory if it doesn't exists
File file = new File(localFile);
if (file != null && file.getParent() != null) {
File path = new File(file.getParent());
if (!path.exists()) {
if (verbose) Log.info("Local path '" + path + "' doesn't exist, creating.");
path.mkdirs();
}
}
FileOutputStream os = null;
os = new FileOutputStream(localFile);
// Copy to file
int count = 0, total = 0, lastShown = 0;
byte[] data = new byte[BUFFER_SIZE];
while ((count = is.read(data, 0, BUFFER_SIZE)) != -1) {
os.write(data, 0, count);
total += count;
// Show every MB
if ((total - lastShown) > (1024 * 1024)) {
if (verbose) System.err.print(".");
lastShown = total;
}
}
if (verbose) Log.info("");
// Close streams
is.close();
os.close();
if (verbose) Log.info("Download finished. Total " + total + " bytes.");
res = true;
} catch (Exception e) {
res = false;
if (verbose) Log.info("ERROR while connecting to " + url);
if (!maskDownloadException) throw new RuntimeException(e);
}
return res;
}
/**
* Open a connection
*/
URLConnection openConnection(URL url) throws IOException {
Proxy proxy = proxy();
return (proxy == null ? url.openConnection() : url.openConnection(proxy));
}
/**
* Parse an entry path from a ZIP file
*/
String parseEntryPath(String entryName, String mainDir, String dataDir) {
if (update) {
// Software update: Entry name should be something like 'snpEff_vXX/dir/file';
int idx = entryName.indexOf('/');
if (idx > 0) entryName = mainDir + entryName.substring(idx);
else throw new RuntimeException("Expecting at least one directory in path '" + entryName + "'");
} else {
// Database download
String[] entryPath = entryName.split("/"); // Entry name should be something like 'data/genomeVer/file';
String dataName = entryPath[entryPath.length - 2] + "/" + entryPath[entryPath.length - 1]; // remove the 'data/' part
entryName = dataDir + "/" + dataName; // Ad local 'data' dir
if (debug) Log.debug("Local file name: '" + entryName + "'");
}
return entryName;
}
/**
* Parse proxy value from environment
*
* @param envVarName: Environment variable name
* @return A Tuple with host and port, null if not found or could not be parsed
*/
Tuple<String, Integer> parseProxyEnv(String envVarName) {
String envProxy = System.getenv(envVarName);
if (envProxy == null || envProxy.isBlank()) return null;
// Parse URL from environment variable
if (verbose) Log.info("Using proxy from environment variable '" + envVarName + "', value '" + envProxy + "'");
String proxyHost = null;
int port = DEFAULT_PROXY_PORT;
try {
URL url;
url = new URL(envProxy);
proxyHost = url.getHost();
port = url.getPort();
} catch (MalformedURLException e) {
// Could not parse URL
if (envProxy.indexOf(':') > 0) {
// Try "host:port" format
String[] hp = envProxy.split(":");
proxyHost = hp[0];
port = Gpr.parseIntSafe(hp[1]);
} else {
// Use just host (leave port as default)
proxyHost = envVarName;
}
}
if (verbose)
Log.info("Parsing proxy value '" + envProxy + "', host: '" + proxyHost + "', port: '" + port + "'");
return new Tuple<>(proxyHost, port);
}
/**
* Parse proxy from Java propperties
*
* @return A Tuple with host and port, null if not found or could not be parsed
*/
Tuple<String, Integer> parseProxyJavaPropperty() {
// Try java properties, i.e. '-D' command line argument
String proxyHost = System.getProperty("http.proxyHost");
String proxyPort = System.getProperty("http.proxyPort");
// Java property not found
if (proxyHost == null || proxyHost.isBlank()) return null;
if (verbose)
Log.info("Using proxy from Java properties: http.proxyHost: '" + proxyHost + "', http.proxyPort: '" + proxyPort + "'");
int port = (proxyPort != null && !proxyPort.isBlank() ? Gpr.parseIntSafe(proxyPort) : DEFAULT_PROXY_PORT);
if (verbose)
Log.info("Parsing proxy value from Java propperties, host: '" + proxyHost + "', port: '" + port + "'");
return new Tuple<>(proxyHost, port);
}
/**
* Create a proxy if the system properties are set
* I.e.: If java is run using something like
* java -Dhttp.proxyHost=$PROXY -Dhttp.proxyPort=$PROXY_PORT -jar ...
*
* @return A proxy object if system properties were defined, null otherwise
*/
Proxy proxy() {
// Try environment variable
Tuple<String, Integer> proxyHostPort = parseProxyEnv("http_proxy");
// Try another environment variable
if (proxyHostPort == null) proxyHostPort = parseProxyEnv("HTTP_PROXY");
// Not found in environment? Try java properties
if (proxyHostPort == null) proxyHostPort = parseProxyJavaPropperty();
if (proxyHostPort == null) return null;
return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostPort.getFirst(), proxyHostPort.getSecond()));
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public void setMaskDownloadException(boolean maskDownloadException) {
this.maskDownloadException = maskDownloadException;
}
public void setUpdate(boolean update) {
this.update = update;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
/**
* Sourceforge certificates throw exceptions if we don't add this SSL setup
* Reference: http://stackoverflow.com/questions/1828775/how-to-handle-invalid-ssl-certificates-with-apache-httpclient
*/
void sslSetup() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
}
/**
* UnZIP all files
*/
public boolean unzip(String zipFile, String mainDir, String dataDir) {
try {
FileInputStream fis = new FileInputStream(zipFile);
ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(fis));
ZipOutputStream zipBackup = null;
String backupFile = "";
// Create a ZIP backup file (only if we are updating)
if (update) {
backupFile = String.format("%s/backup_%2$tY-%2$tm-%2$td_%2$tH:%2$tM:%2$tS.zip", mainDir, new GregorianCalendar());
if (verbose) Log.info("Creating backup file '" + backupFile + "'");
zipBackup = new ZipOutputStream(new FileOutputStream(backupFile));
}
//---
// Extract ZIP file
//---
ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
if (!entry.isDirectory()) {
String localEntryName = parseEntryPath(entry.getName(), mainDir, dataDir);
if (debug) Log.debug("Extracting file '" + entry.getName() + "' to '" + localEntryName + "'");
else if (verbose) Log.info("Extracting file '" + entry.getName() + "'");
// Backup entry
if (zipBackup != null) backupFile(zipBackup, localEntryName);
//---
// Does directory exists?
//---
String dirName = Gpr.dirName(localEntryName);
File dir = new File(dirName);
if (!dir.exists()) {
// Create local dir
if (verbose) Log.info("Creating local directory: '" + dir + "'");
if (!dir.mkdirs())
throw new RuntimeException("Cannot create directory '" + dir.getCanonicalPath() + "'");
}
//---
// Extract entry
//---
FileOutputStream fos = new FileOutputStream(localEntryName);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);
int count = 0;
byte[] data = new byte[BUFFER_SIZE];
while ((count = zipIn.read(data, 0, BUFFER_SIZE)) != -1)
dest.write(data, 0, count);
dest.flush();
dest.close();
} else if (entry.isDirectory()) {
String dir = parseEntryPath(entry.getName(), mainDir, dataDir);
// Create local dir
if (verbose) Log.info("Creating local directory: '" + dir + "'");
if (!(new File(dir)).mkdirs()) throw new RuntimeException("Cannot create directory '" + dir + "'");
}
}
// Close zip files
zipIn.close();
if (zipBackup != null) {
zipBackup.close();
Log.info("Backup file created: '" + backupFile + "'");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return true;
}
/**
* Used to get rid of some SSL Certificateproblems
* Ref: http://stackoverflow.com/questions/1828775/how-to-handle-invalid-ssl-certificates-with-apache-httpclient
*/
private static class DefaultTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}
| true |
10d62a556f3a36755942349786975f6ca09a6193 | Java | darshanadsw/todo-jms | /src/main/java/com/myapp/todojms/jms/ToDoProducer.java | UTF-8 | 527 | 2.3125 | 2 | [] | no_license | package com.myapp.todojms.jms;
import com.myapp.todojms.domain.ToDo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@RequiredArgsConstructor
public class ToDoProducer {
private final JmsTemplate jmsTemplate;
public void sendTo(String destination, ToDo todo){
this.jmsTemplate.convertAndSend(destination,todo);
log.info("Producer >> Message Sent");
}
}
| true |
1f835452986746e7e45d971b9b1c73abf39b75d8 | Java | fmribeiro/book-review-api | /src/main/java/com/resenha/microserviceresenha/services/LikedReviewService.java | UTF-8 | 4,396 | 2.296875 | 2 | [] | no_license | package com.resenha.microserviceresenha.services;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.resenha.microserviceresenha.data.model.LikedReview;
import com.resenha.microserviceresenha.data.model.Review;
import com.resenha.microserviceresenha.data.repositories.LikedReviewRepository;
import com.resenha.microserviceresenha.data.repositories.ReviewRepository;
import com.resenha.microserviceresenha.dto.LikedReviewDTO;
import com.resenha.microserviceresenha.dto.model.LikedReviewModelDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.sort;
@AllArgsConstructor
@Service
@Slf4j
public class LikedReviewService {
private ReviewRepository reviewRepository;
private LikedReviewRepository likedReviewRepository;
private MongoTemplate mongoTemplate;
private ObjectMapper objectMapper;
public Optional<LikedReview> saveUpdateLikedReview(LikedReviewModelDTO likedReviewModelDTO) {
Optional optionalBook = Optional.empty();
try{
LikedReview likedReview = objectMapper.convertValue(likedReviewModelDTO, LikedReview.class);
boolean removed = removeOrIncrementLikedReview(likedReview);
if(removed){
return optionalBook;
}
return Optional.of(likedReviewRepository.save(likedReview));
}
catch (Exception e){
log.error("Erro ao inserir um novo likedReview", e);
}
return optionalBook;
}
public boolean removeOrIncrementLikedReview(LikedReview likedReview) {
boolean wasRemoved = false;
LikedReview byReviewIdAndUserId = likedReviewRepository.findByReviewIdAndUserId(likedReview.getReviewId(), likedReview.getUserId());
Review review = reviewRepository.findById(likedReview.getReviewId().toHexString()).get();
Integer likeTotal = review.getLikes();
if (Objects.nonNull(byReviewIdAndUserId)) {
likeTotal -= 1;
review.setLikes(likeTotal);
reviewRepository.save(review);
likedReviewRepository.delete(byReviewIdAndUserId);
wasRemoved = true;
} else {
likeTotal += 1;
review.setLikes(likeTotal);
reviewRepository.save(review);
}
return wasRemoved;
}
public void deleteLikedReviewById(String reviewId) {
likedReviewRepository.deleteById(reviewId);
}
public List<LikedReview> getAllLikedReviews() {
return likedReviewRepository.findAll();
}
public LikedReview findById(String id) {
Optional<LikedReview> byId = likedReviewRepository.findById(id);
if (byId.isPresent()) {
return byId.get();
}
return null;
}
public List<LikedReviewDTO> findFavoritesReviews(String userId) {
LookupOperation lookup = LookupOperation.newLookup()
.from("reviews")
.localField("reviewId")
.foreignField("_id")
.as("review");
LookupOperation lookup2 = LookupOperation.newLookup()
.from("users")
.localField("review.userId")
.foreignField("_id")
.as("user");
ObjectId objectId = new ObjectId(userId);
SortOperation sort = sort(Sort.by(Sort.Direction.DESC, "_id"));
LimitOperation limitOperation = new LimitOperation(10);
AggregationOperation match1 = Aggregation.match(Criteria.where("userId").is(objectId));
AggregationOperation unwind = Aggregation.unwind("review");
AggregationOperation unwind2 = Aggregation.unwind("user");
Aggregation aggregation = Aggregation.newAggregation(lookup, match1, unwind, lookup2, unwind2, limitOperation, sort);
List<LikedReviewDTO> results = mongoTemplate.aggregate(aggregation, "likedReviews", LikedReviewDTO.class).getMappedResults();
return results;
}
}
| true |
6fed1ce608cc9e0ff93dce744ba9ab3fddc05735 | Java | medonja/IceSoap | /IceSoap/src/com/alexgilleran/icesoap/xml/XMLNode.java | UTF-8 | 2,794 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | /**
*
*/
package com.alexgilleran.icesoap.xml;
import java.util.Collection;
import com.alexgilleran.icesoap.xml.impl.XMLAttributeImpl;
/**
* Interface that represents a single XML node within an XML document.
*
* @author Alex Gilleran
*
*/
public interface XMLNode extends XMLElement {
/** Prefix for the XMLSchema namespace. */
final static String NS_PREFIX_XSD = "xsd";
/** URL of the XMLSchema namespace. */
final static String NS_URI_XSD = "http://www.w3.org/2001/XMLSchema";
/** Prefix for the XmlSchema-instance namespace. */
final static String NS_PREFIX_XSI = "xsi";
/** URL of the XmlSchema-instance namespace. */
final static String NS_URI_XSI = "http://www.w3.org/2001/XMLSchema-instance";
/** The name of the xsi:nil element. */
final static String XSI_NIL_NAME = "nil";
/** The value of the xsi:nil element if true. */
final static String XSI_NIL_TRUE = "true";
/**
* Get all the attributes of this element.
*
* @return The attributes as a collection of {@link XMLAttributeImpl}
* objects.
*/
Collection<XMLAttribute> getAttributes();
/**
* Adds an attribute to the element.
*
* @param namespace
* The namespace of the element as a URI - can be null if no
* namespace is to be set.
* @param name
* The name of the attribute.
* @param value
* The value of the attribute.
* @return
*/
XMLAttribute addAttribute(String namespace, String name, String value);
/**
* Sets the <code>xsi:type</code> attribute for the element.
*
* Note that this basically adds a new attribute called "type" in the
* "http://www.w3.org/2001/XMLSchema-instance" namespace - it doesn't
* automatically declare this namespace with the "xsi" prefix. If the xsi
* prefix is declared with {@link XMLNode#declarePrefix(String, String)}
* method on this element or any higher elements, it this will come out as
* xsi:type.
*
* @param type
* The type, as a string.
*/
void setType(String type);
/**
* Declare a prefix for a namespace URI.
*
* @param prefix
* The prefix name (e.g. "xsi").
* @param namespace
* The namespace URI, as a String.
*/
void declarePrefix(String prefix, String namespace);
/**
* Get the name of the element.
*
* @return The name as a string.
*/
String getName();
/**
* Sets the name of the element.
*
* @param name
* The new name as a string.
*/
void setName(String name);
/**
* Get the namespace URI for this element.
*
* @return The namespace URI, as a String.
*/
String getNamespace();
/**
* Sets the namespace of this element.
*
* @param namespace
* The namespace URI as a String.
*/
void setNamespace(String namespace);
} | true |
54f40d86453f7c14c63033039bbd7ce762f4fb97 | Java | ieiko/livre_de_cuisine | /src/dao/DAORecetteJDBC.java | UTF-8 | 3,441 | 2.6875 | 3 | [] | no_license | package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import metier.*;
public class DAORecetteJDBC implements DAORecette {
private Connection connect() throws SQLException {
Properties pt = new Properties();
pt.setProperty("user", "root");
pt.setProperty("password", "ajcformation");
pt.setProperty("useSSL", "false");
pt.setProperty("autoReconnect", "true");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/recettes?serverTimezone=UTC", pt);
}
public Recette selectById(Integer id) throws SQLException, ClassNotFoundException {
Connection conn = this.connect();
Recette recette = null;
PreparedStatement ps=conn.prepareStatement("select * from recettes where id_recette=?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
recette = new Recette(rs.getInt("id_recette"), rs.getString("name"), rs.getString("resume"), Type.valueOf(rs.getString("type")));
}
conn.close();
return recette;
}
public ArrayList<Recette> selectAll() throws SQLException, ClassNotFoundException {
Connection conn = this.connect();
ArrayList<Recette> recettes = new ArrayList<Recette>();
PreparedStatement ps= conn.prepareStatement("select * from recettes");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
recettes.add(new Recette(rs.getInt("id_recette"), rs.getString("name"), rs.getString("resume"), Type.valueOf(rs.getString("type"))));
}
conn.close();
return recettes;
}
public void insert(Recette obj) throws ClassNotFoundException, SQLException {
Connection conn = this.connect();
PreparedStatement ps = conn.prepareStatement("insert into recettes (name, resume, type) values (?, ?, ?)");
ps.setString(1, obj.getName());
ps.setString(2, obj.getResume());
ps.setString(3, obj.getType().getLibelle());
ps.executeUpdate();
conn.close();
}
public void update(Recette obj) throws ClassNotFoundException, SQLException {
Connection conn = this.connect();
PreparedStatement ps = conn.prepareStatement("update recettes set name = ?, resume = ?, type = ? where id_recette = ?");
ps.setString(1, obj.getName());
ps.setString(2, obj.getResume());
ps.setString(3, obj.getType().getLibelle());
ps.setInt(4, obj.getId());
ps.executeUpdate();
conn.close();
}
public void delete(Recette obj) throws ClassNotFoundException, SQLException {
Connection conn = this.connect();
PreparedStatement ps = conn.prepareStatement("delete from recettes where id_recette = ?");
ps.setInt(1, obj.getId());
ps.executeUpdate();
conn.close();
}
@Override
public ArrayList<Recette> getRecetteByType(Type type) throws SQLException {
Connection conn = this.connect();
ArrayList<Recette> recettes = new ArrayList<Recette>();
PreparedStatement ps=conn.prepareStatement("select * from recettes where type=?");
ps.setString(1, type.getLibelle());
ResultSet rs = ps.executeQuery();
while (rs.next()) {
recettes.add(new Recette(rs.getInt("id_recette"), rs.getString("name"), rs.getString("resume"), Type.valueOf(rs.getString("type"))));
}
conn.close();
return recettes;
}
}
| true |
e91c5e5c128a5703731b07297952a0107344e977 | Java | dlvip/jiushiguang | /piclib/src/main/java/com/pic/lib/activitys/PhotoPreviewActivity.java | UTF-8 | 5,641 | 1.851563 | 2 | [
"Apache-2.0"
] | permissive | package com.pic.lib.activitys;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.pic.lib.PicCode;
import com.pic.lib.utils.ActivityUtils;
import com.pic.lib.utils.ScreenTools;
import com.pic.lib.R;
import com.pic.lib.adapters.ImagePagerAdapter;
import com.pic.lib.adapters.PhotoGalleyAdapter;
import com.pic.lib.utils.AlbumController;
import com.pic.lib.utils.PhotoSelectorHelper;
import java.util.ArrayList;
import java.util.List;
public class PhotoPreviewActivity extends BaseLibActivity implements PhotoSelectorHelper.OnLoadPhotoListener, ViewPager.OnPageChangeListener {
private ViewPager mViewPager;
private ImageView mCheckBox;
private TextView mCountText;
private TextView mPreviewNum;
private int index, maxPickCount;
private String albumName;
private List<String> mList;
private ImagePagerAdapter mPhotoAdapter;
/**
* 图片浏览
*
* @param index
* @param maxPickCount
* @param albumName
*/
public static void startPhotoPreviewActivity(Context mContext, int index, int maxPickCount, String albumName, int requestCode) {
Intent intent = new Intent(mContext, PhotoPreviewActivity.class);
intent.putExtra(PicCode.EXTRA_IMAGE_INDEX, index);
intent.putExtra(PicCode.MAX_PICK_COUNT, maxPickCount);
intent.putExtra(PicCode.ALBUM_NAME, albumName);
ActivityUtils.startActivityForResult((Activity) mContext, intent, requestCode);
}
@Override
protected void initEvent() {
mCheckBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selCount = PhotoGalleyAdapter.mSelectedImage.size();
if (selCount >= maxPickCount) {
ScreenTools.ToastMessage(PhotoPreviewActivity.this, "已经选满" + selCount + "张");
return;
}
int index = mViewPager.getCurrentItem();
boolean selFlag = PhotoGalleyAdapter.mSelectedImage.contains(mList.get(index));
mCheckBox.setSelected(!selFlag);
if (selFlag) {
PhotoGalleyAdapter.mSelectedImage.remove(mList.get(index));
} else {
PhotoGalleyAdapter.mSelectedImage.add(mList.get(index));
}
updateCountView();
}
});
mCountText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityUtils.finishActivity(PhotoPreviewActivity.this);
}
});
}
@Override
protected void initView() {
Intent intent = getIntent();
this.maxPickCount = intent.getIntExtra(PicCode.MAX_PICK_COUNT, 1);
this.albumName = intent.getStringExtra(PicCode.ALBUM_NAME);
this.index = intent.getIntExtra(PicCode.EXTRA_IMAGE_INDEX, 0);
ActionBar mActionBar = getActionBar();
if (mActionBar != null) {
mActionBar.setTitle(albumName);
mActionBar.setDisplayHomeAsUpEnabled(true);
}
mViewPager = this.findViewById(R.id.viewpager_preview_photo);
mCheckBox = this.findViewById(R.id.checkbox_sel_flag);
mPreviewNum = this.findViewById(R.id.tv_preview_num);
mCountText = this.findViewById(R.id.tv_to_confirm);
mViewPager.addOnPageChangeListener(this);
mList = new ArrayList<>();
mPhotoAdapter = new ImagePagerAdapter(getSupportFragmentManager(), mList, false);
mViewPager.setAdapter(mPhotoAdapter);
if (albumName != null && !albumName.equals(AlbumController.RECENT_PHOTO)) {
new PhotoSelectorHelper(this).getAlbumPhotoList(albumName, this);
} else {
new PhotoSelectorHelper(this).getReccentPhotoList(this);
}
updateCountView();
}
@Override
protected int getLayoutID() {
return R.layout.piclib_activity_photo_preview;
}
@Override
public void onPhotoLoaded(List<String> photos) {
mList.clear();
mList.addAll(photos);
mPhotoAdapter.notifyDataSetChanged();
mViewPager.setCurrentItem(index, false);
mPreviewNum.setText(index + 1 + "/" + mList.size());
mCheckBox.setSelected(PhotoGalleyAdapter.mSelectedImage.contains(mList.get(index)));
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mCheckBox.setSelected(PhotoGalleyAdapter.mSelectedImage.contains(mList.get(position)));
mPreviewNum.setText(position + 1 + "/" + mList.size());
}
@Override
public void onPageScrollStateChanged(int state) {
}
private void updateCountView() {
if (PhotoGalleyAdapter.mSelectedImage.size() == 0) {
mCountText.setEnabled(false);
} else {
mCountText.setEnabled(true);
}
mCountText.setText("确定(" + PhotoGalleyAdapter.mSelectedImage.size() + "/" + maxPickCount + ")");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true |
d09d655d2ac7ea21908bf7a43ccd492d233b9ad9 | Java | paullewallencom/android-978-1-7864-6895-6 | /_src/Zomato/app/src/main/java/com/androcid/zomato/model/CollectionItem.java | UTF-8 | 2,255 | 2.21875 | 2 | [
"MIT",
"Apache-2.0"
] | permissive | package com.androcid.zomato.model;
import com.androcid.zomato.util.Constant;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
/**
*
*/
public class CollectionItem implements Serializable {
private static final long serialVersionUID = 1L;
@SerializedName(Constant.ID)
int id;
@SerializedName(Constant.USER_ID)
int user_id;
@SerializedName(Constant.NAME)
String name;
@SerializedName(Constant.IMAGE)
String image;
@SerializedName(Constant.DESCRIPTION)
String description;
@SerializedName(Constant.TAGS)
String tags;
@SerializedName(Constant.DATA)
List<String> restaurants;
//NEW
@SerializedName(Constant.SAVED)
boolean saved;
@SerializedName(Constant.COUNT)
int count;
public boolean isSaved() {
return saved;
}
public int getCount() {
return count;
}
public CollectionItem(int id, int user_id, String name, String description, String tags, List<String> restaurants) {
this.id = id;
this.user_id = user_id;
this.name = name;
this.description = description;
this.tags = tags;
this.restaurants = restaurants;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<String> getRestaurants() {
return restaurants;
}
public void setRestaurants(List<String> restaurants) {
this.restaurants = restaurants;
}
}
| true |
2099c90072a8f8b5fa8b5c1251271520d73895d0 | Java | phanssen/CS361_IDE_Project | /proj10DouglasHanssenMacDonaldZhang/CodeAreaTabPane.java | UTF-8 | 1,499 | 2.875 | 3 | [] | no_license | /*
File: CodeAreaTabPane.java
CS361 Project 9
Names: Liwei Jiang, Chris Marcello, Tracy Quan, Wyett MacDonald, Paige Hanssen, Tia Zhang, Kyle Douglas
Date: 11/20/2018
*/
package proj10DouglasHanssenMacDonaldZhang;
import org.fxmisc.richtext.CodeArea;
import javafx.scene.control.*;
import org.fxmisc.flowless.VirtualizedScrollPane;
import javafx.fxml.FXML;
import javafx.scene.control.TabPane;
/**
* A class that holds a static method to access the active code area.
* Used by the edit menu controller and the file menu controller.
* @author Evan Savillo
* @author Paige Hanssen
* @author Tia Zhang
*/
public class CodeAreaTabPane extends TabPane {
public CodeAreaTabPane(){
super();
}
/**
* Returns the currently active code area given a TabPane object
* @return the CodeArea object in the currently selected Tab of the input TabPane
*/
public CodeArea getCurCodeArea( ) {
if (this.getTabs().size()>0) {
Tab selectedTab = getCurTab();
VirtualizedScrollPane vsp = (VirtualizedScrollPane) selectedTab.getContent();
return (CodeArea) vsp.getContent();
}
else return null;
}
/**
* Returns the currently active tabPane given a TabPane object
* @return the tapPane object in the currently selected Tab of the input TabPane
*/
public Tab getCurTab() {
if (this.getTabs().size()>0) {
return this.getSelectionModel().getSelectedItem();
}
else {
return null;
}
}
} | true |
359d03ca6c187c3adf9f43a211c298840a07207e | Java | jerome-jouvie/LibLoader | /src-java/org/jouvieje/libloader/LibLoaderJNI.java | UTF-8 | 1,835 | 2.125 | 2 | [] | no_license | /**
* LibLoader
* Copyright © 2007-2017 Jérôme Jouvie
*
* Created on 25 mar. 2007
* @version file v1.0.0
*
* To contact me:
* jerome.jouvie@gmail.com
* http://jerome.jouvie.free.fr/
*
* INTRODUCTION
* This project enhance the Java's System.loadLibrary and allows:
* - library loading without loading dependencies
* - search libraries from "java.library.path", "sun.jnlp.applet.launcher", "org.lwjgl.librarypath"
* - library loading from applet
*
*
* GNU LESSER GENERAL PUBLIC LICENSE
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of the License,
* or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the
* Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package org.jouvieje.libloader;
final class LibLoaderJNI {
static {
if(!LibLoader.isLibLoaderLibsLoaded()) {
throw new UnsatisfiedLinkError("LibLoader libraries not loaded !");
}
}
/* void *dlopen(const char *filename, int flag); */
protected final static native long dlopen(byte[] filename, int flag);
/* char *dlerror(void); */
protected final static native String dlerror();
/* void *dlsym(void *handle, const char *symbol); */
protected final static native long dlsym(long handle, byte[] symbol);
/* int dlopen(void *handle); */
protected final static native int dlclose(long handle);
}
| true |
0f1c6530de07c0dc4170052b8289001c0eda8ca7 | Java | vishal901/Retrofit2SampleApp | /app/src/main/java/zeroturnaround/org/jrebel4androidgettingstarted/imageloader/impl/FrescoImageLoader.java | UTF-8 | 2,725 | 2.0625 | 2 | [
"MIT"
] | permissive | package zeroturnaround.org.jrebel4androidgettingstarted.imageloader.impl;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.widget.ImageView;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.nativecode.Bitmaps;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.imagepipeline.request.Postprocessor;
import jp.wasabeef.fresco.processors.BlurPostprocessor;
import zeroturnaround.org.jrebel4androidgettingstarted.imageloader.ImageLoader;
/**
* Created by Sten on 17/02/16.
*/
public class FrescoImageLoader implements ImageLoader {
@Override
public void loadImage(String url, ImageView imageView) {
if (!(imageView instanceof SimpleDraweeView)) {
return;
}
Postprocessor blurPostprocessor = new BlurPostprocessor(imageView.getContext(), 10, 1) {
@Override
public void process(Bitmap dest, Bitmap source) {
Canvas canvas = new Canvas(dest);
Rect sourceRect = new Rect(0, 0, source.getWidth(), source.getHeight());
RectF scaledDestRect = new RectF(0, 0, source.getWidth() - source.getWidth() / 4,
source.getHeight() - source.getHeight()/4);
canvas.drawBitmap(source, sourceRect, scaledDestRect, null);
Matrix matrix = new Matrix();
matrix.postRotate(180);
matrix.preScale(-1, 1);
matrix.postTranslate(0, scaledDestRect.height());
canvas.setMatrix(matrix);
scaledDestRect.offset(0, - scaledDestRect.height());
canvas.drawBitmap(source, sourceRect, scaledDestRect, null);
super.process(dest, dest);
scaledDestRect.offset(0, 0);
canvas.drawBitmap(source, sourceRect, scaledDestRect, null);
}
};
ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(url)).
setPostprocessor(blurPostprocessor).build();
PipelineDraweeController pipelineDraweeController = (PipelineDraweeController) Fresco.newDraweeControllerBuilder().
setImageRequest(imageRequest).setOldController(((SimpleDraweeView) imageView).getController()).build();
((SimpleDraweeView) imageView).setController(pipelineDraweeController);
}
}
| true |
8f79beb7debb7b39d524d2a125b980fdd7c7f5d9 | Java | tandaica0612/MARDJAVA | /src-mard-backend/src/main/java/com/nsw/backend/mard/p07/repositories/TbdYcrut07Repository.java | UTF-8 | 434 | 1.757813 | 2 | [] | no_license | package com.nsw.backend.mard.p07.repositories;
import com.nsw.backend.mard.p07.model.TbdYcrut07;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Repository : TbdYcrut07.
*/
@Repository
public interface TbdYcrut07Repository extends JpaRepository<TbdYcrut07, Long> {
List<TbdYcrut07> findAllByFiNSWFileCode(String fiNSWFileCode);
}
| true |
da7507c52524fd85c42793c70c25551046b8cf8e | Java | DzhonPetrus/JAVA-Reservation-System | /RESERVATION SYSTEM-MySQL/SIMPLE-INVENTORY-RESERVATION-SYSTEM/src/simple/inventory/reservation/system/DB/DAO_ACCOUNTS.java | UTF-8 | 6,132 | 2.671875 | 3 | [
"MIT"
] | permissive | /*
* 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 simple.inventory.reservation.system.DB;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author dzhon
*/
public class DAO_ACCOUNTS {
MYSQL_DB sql = new MYSQL_DB();
public List<CLASS_ACCOUNTS> getAllAccounts() {
List<CLASS_ACCOUNTS> list = new ArrayList<>();
try {
sql.createConnection();
sql.rs = sql.st.executeQuery("Select * from accounts");
// GET THE RESULT OF QUERY THEN ADD IT TO LIST
while (sql.rs.next()){
CLASS_ACCOUNTS tempAccount = convertRowToEmployee(sql.rs);
list.add(tempAccount);
}
// CLOSE CONECTION
sql.rs.close();
sql.st.close();
sql.con.close();
} catch (SQLException ex) {
Logger.getLogger(DAO_ACCOUNTS.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
private CLASS_ACCOUNTS convertRowToEmployee(ResultSet myRs) throws SQLException {
int id = myRs.getInt("ID");
String username = myRs.getString("USERNAME");
String password = myRs.getString("PASSWORD");
String perid = myRs.getString("PERSON_ID");
String fname = myRs.getString("fname");
String lname = myRs.getString("lname");
int role = myRs.getInt("ROLE");
CLASS_ACCOUNTS tempAccount = new CLASS_ACCOUNTS(id, username, password, perid, fname, lname, role);
return tempAccount;
}
public List<CLASS_ACCOUNTS> searchAccount(int ID) {
List<CLASS_ACCOUNTS> list = new ArrayList<>();
try {
sql.createConnection();
sql.rs = sql.st.executeQuery("Select * from accounts where ID ="+ ID +"");
// GET THE RESULT OF QUERY THEN ADD IT TO LIST
while (sql.rs.next()){
CLASS_ACCOUNTS tempAccount = convertRowToEmployee(sql.rs);
list.add(tempAccount);
}
// CLOSE CONECTION
sql.rs.close();
sql.st.close();
sql.con.close();
} catch (SQLException ex) {
Logger.getLogger(DAO_ACCOUNTS.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
public List<CLASS_ACCOUNTS> searchAccountByPersonID(String personID) {
List<CLASS_ACCOUNTS> list = new ArrayList<>();
try {
sql.createConnection();
sql.rs = sql.st.executeQuery("Select * from accounts where PERSON_ID ='"+ personID +"'");
// GET THE RESULT OF QUERY THEN ADD IT TO LIST
while (sql.rs.next()){
CLASS_ACCOUNTS tempAccount = convertRowToEmployee(sql.rs);
list.add(tempAccount);
}
// CLOSE CONECTION
sql.rs.close();
sql.st.close();
sql.con.close();
} catch (SQLException ex) {
Logger.getLogger(DAO_ACCOUNTS.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
public List<CLASS_ACCOUNTS> verifyAccount(String username, String password) {
List<CLASS_ACCOUNTS> list = new ArrayList<>();
try {
sql.createConnection();
sql.rs = sql.st.executeQuery("Select * from accounts where username = '"+ username +"' and password = '"+ password +"'");
// GET THE RESULT OF QUERY THEN ADD IT TO LIST
while (sql.rs.next()){
CLASS_ACCOUNTS tempAccount = convertRowToEmployee(sql.rs);
list.add(tempAccount);
}
// CLOSE CONECTION
sql.rs.close();
sql.st.close();
sql.con.close();
} catch (SQLException ex) {
Logger.getLogger(DAO_ACCOUNTS.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
public void addAccount(CLASS_ACCOUNTS theAccount) throws SQLException {
sql.createConnection();
sql.pst = sql.con.prepareStatement("Insert into accounts(username, password, person_id, fname, lname, role) values(?, ?, ?, ?, ?, ?)");
sql.pst.setString(1, theAccount.getUsername());
sql.pst.setString(2, theAccount.getPassword());
sql.pst.setString(3, theAccount.getPerson_id());
sql.pst.setString(4, theAccount.getFname());
sql.pst.setString(5, theAccount.getLname());
sql.pst.setInt(6, theAccount.getRole());
sql.pst.executeUpdate();
sql.rs.close();
sql.st.close();
}
public void updateAccount(CLASS_ACCOUNTS theAccount) throws SQLException {
sql.createConnection();
sql.pst = sql.con.prepareStatement("Update accounts set username=?, password=?, person_id=?, fname=?, lname=?, role=? where id=?");
sql.pst.setString(1, theAccount.getUsername());
sql.pst.setString(2, theAccount.getPassword());
sql.pst.setString(3, theAccount.getPerson_id());
sql.pst.setString(4, theAccount.getFname());
sql.pst.setString(5, theAccount.getLname());
sql.pst.setInt(6, theAccount.getRole());
sql.pst.setInt(7, theAccount.getId());
sql.pst.executeUpdate();
sql.rs.close();
sql.st.close();
}
public void deleteAccount(CLASS_ACCOUNTS theAccount) throws SQLException {
sql.createConnection();
sql.pst = sql.con.prepareStatement("Delete from accounts where id=?");
sql.pst.setInt(1, theAccount.getId());
sql.pst.executeUpdate();
sql.rs.close();
sql.st.close();
}
}
| true |
61596d18fe12378375977a3d920d83bcc4c5521e | Java | enha-rs/WebWechat | /SecondAccessOfyanfazhongxin/webWeChat/src/com/crs/dao/FriendsDao.java | UTF-8 | 564 | 1.882813 | 2 | [] | no_license | package com.crs.dao;
import com.crs.entity.Friends;
import java.util.List;
/**
* @author shkstart
* @create 2021-05-09 22:06
*/
public interface FriendsDao {
/**
* 添加好友
* @param friend
* @return
*/
public int saveFriend(Friends friend);
/**
* 根据本人id查找本人的好友
* @param userId
* @return
*/
public List queryAllFriendsIdByUserId(int userId);
/**
* 删除好友
* @param nickname
* @return
*/
public int deleteFriendByNickname(String nickname);
}
| true |
ad211e0a12ff1968f79a96155ca43469bf634f54 | Java | lars-reimann/playground | /Java/VierGewinnt/src/net/bplaced/programmierung/vierGewinnt/Computer.java | UTF-8 | 3,140 | 2.921875 | 3 | [] | no_license | package net.bplaced.programmierung.vierGewinnt;
import java.util.List;
import java.util.Random;
public final class Computer {
private final Engine engine;
private long[][] transpositionIndex = new long[42][10];
private int[][] transpositionValue = new int[42][10];
private int insertionIndex = 0;
private static final long[][][] hashValues = new long[42][3][2];
static {
final Random random = new Random();
for (int i = 0; i < 42; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 2; k++) {
hashValues[i][j][k] = random.nextLong();
}
}
}
}
public Computer(final Engine engine) {
this.engine = engine;
}
private int searchRoot(final int player) {
final List<Integer> moves = engine.genMoves();
int bestMove = 0;
int best = -1;
for (int move : moves) {
engine.doMove(move, player);
final int value = -alphaBeta(1, -1, -best, -player);
engine.undoMove(move, player);
if (value > best) {
best = value;
bestMove = move;
}
}
return bestMove;
}
private int alphaBeta(final int depth, final int alpha, final int beta, final int player) {
if (depth == 10) {
return 0;
}
long hashValue = 0;
for (int i = 0; i < 42; i++) {
final int piece;
if ((engine.mapPlayerNeg & Data.MAPS_FIELD[i]) != 0) {
piece = 0;
} else if ((engine.mapPlayerPos & Data.MAPS_FIELD[i]) != 0) {
piece = 1;
} else {
piece = 2;
}
final int playerIndex = player == -1 ? 0 : 1;
hashValue ^= hashValues[i][piece][playerIndex];
}
int index = -1;
for (int i = 0; i < 10; i++) {
if (transpositionIndex[depth][i] == hashValue) {
index = i;
break;
}
}
if (index >= 0) {
return transpositionValue[depth][index];
}
if (engine.isWonForPlayer(player)) {
return 1;
} else if (engine.isWonForPlayer(-player)) {
return -1;
} else if (engine.isDraw()) {
return 0;
}
final List<Integer> moves = engine.genMoves();
int best = alpha;
for (int move : moves) {
engine.doMove(move, player);
final int value = -alphaBeta(depth + 1, -beta, -best, -player);
engine.undoMove(move, player);
if (value >= beta) {
return beta;
}
if (value > best)
best = value;
}
transpositionIndex[depth][insertionIndex] = hashValue;
transpositionValue[depth][insertionIndex] = best;
insertionIndex = (insertionIndex + 1) % 10;
return best;
}
public void doComputerMove(final int player) {
engine.doMove(searchRoot(player), player);
}
}
| true |
b0a0b86da3c823a0746c7e147c2df1e0099ead5b | Java | deternan/Light-tools | /src/Json/XML_to_JSON.java | UTF-8 | 1,351 | 2.75 | 3 | [] | no_license | package Json;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import org.json.JSONObject;
import org.json.XML;
public class XML_to_JSON
{
private String read_file_path = "";
private String read_file_name = "*.xml";
private String write_file_path = "";
private String write_file_name = "*.json";
private JSONObject jsonObj;
public XML_to_JSON() throws Exception
{
File file = new File (read_file_path + read_file_name);
InputStream inputStream = new FileInputStream(file);
StringBuilder builder = new StringBuilder();
int ptr = 0;
while ((ptr = inputStream.read()) != -1 )
{
builder.append((char) ptr);
}
String xml = builder.toString();
jsonObj = XML.toJSONObject(xml);
//System.out.println(jsonObj);
Write_Line_file();
System.out.println("Convert OK");
}
private void Write_Line_file() throws Exception
{
FileWriter fw = new FileWriter(write_file_path + write_file_name);
//Replace_brackets();
fw.write(jsonObj.toString());
fw.flush();
fw.close();
}
public static void main(String[] args)
{
try {
XML_to_JSON xtj= new XML_to_JSON();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true |
6f2ab7905cc62988f6befb7b215a3b4a0631ba13 | Java | jaenyeong/Study_Spring-Web-mvc | /src/main/java/com/jaenyeong/springwebmvc/springWebHttpMethod/BaseController.java | UTF-8 | 2,696 | 2.484375 | 2 | [] | no_license | package com.jaenyeong.springwebmvc.springWebHttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import java.util.List;
// 전역 컨트롤러
// 여기에 선언하면 모든 컨트롤러에 적용됨
// assignableTypes 속성으로 특정 컨트롤러에만 적용
@ControllerAdvice(assignableTypes = {HandlerMethodController_1.class, HandlerMethodController_2.class, EventApi.class})
public class BaseController {
@ModelAttribute
public void categories(Model model) {
model.addAttribute("categories", List.of("study", "seminar", "hobby", "social"));
}
@ModelAttribute("categoriesReturnList")
public List<String> categoriesReturnList(Model model) {
return List.of("study", "seminar", "hobby", "social");
}
// @Autowired
// EventValidator eventValidator;
// 아래처럼 메서드에서 원하는 시점에 명시적으로 처리할 수 있음
// eventValidator.validate(event, bindingResult);
// 데이터 바인딩을 커스터마이징
@InitBinder
// @InitBinder("event") // 이와 같이 문자열을 지정하면 모델 어트리뷰트 이름에 맞는 객체가 바인딩 될때만 적용됨
public void initEventBinder(WebDataBinder webDataBinder) {
// ID 값을 받지 않을 경우
webDataBinder.setDisallowedFields("id");
// Validator 인터페이스를 구현한 커스터마이징 클래스를 추가
webDataBinder.addValidators(new EventValidator());
}
// 가장 구체적인 익셉션이 매핑됨
// "/error" 로 요청시 해당 메서드를 통해 익셉션 페이지 리턴
// @ExceptionHandler
// public String eventErrorHandler(EventException exception, Model model) {
// 여러 익셉션 처리
@ExceptionHandler({EventException.class, RuntimeException.class})
// 여러 익셉션 처리 경우 모두 받을 수 있는 상위타입으로 매개변수 설정
public String eventErrorHandler(RuntimeException exception, Model model) {
model.addAttribute("message", "event error");
return "error";
}
@ExceptionHandler
public String runtimeErrorHandler(RuntimeException exception, Model model) {
model.addAttribute("message", "runtime error");
return "error";
}
// Rest API 경우 ResponseEntity를 이용해 에러 메세지 반환
@ExceptionHandler
public ResponseEntity<String> restErrorHandler() {
return ResponseEntity.badRequest().body("REST API error message");
}
}
| true |
6c1e94dc9e31de310dd3a2ef9809f4211c2b6060 | Java | rentongfu/MyTestApp | /app/src/main/java/com/tongfu/mytestapp/lifecycle/fragment/FragmentLifecycleActivity.java | UTF-8 | 5,445 | 1.960938 | 2 | [] | no_license | package com.tongfu.mytestapp.lifecycle.fragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.tongfu.mytestapp.R;
import com.tongfu.mytestapp.TraceRecorder;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class FragmentLifecycleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
TraceRecorder.record(this , "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_lifecycle);
ButterKnife.bind(this);
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.anim_fragment_show_from_left, R.anim.anim_fragment_exit_to_right).add(R.id.fl_container , new LifecycleTestFragment() , "test").commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
TraceRecorder.record(this , "onCreateOptionMenu");
getMenuInflater().inflate(R.menu.menu_lifecycle_test , menu );
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
TraceRecorder.record(this , "onOptionsItemSelected");
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
TraceRecorder.record(this , "onCreateContextMenu");
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
TraceRecorder.record(this , "onPrepareOptionMenu");
return super.onPrepareOptionsMenu(menu);
}
@Override
protected void onDestroy() {
TraceRecorder.record(this , "onDestroy");
super.onDestroy();
}
@Override
protected void onStart() {
TraceRecorder.record(this , "onStart");
super.onStart();
}
@Override
protected void onRestart() {
TraceRecorder.record(this , "onRestart");
super.onRestart();
}
@Override
protected void onResume() {
TraceRecorder.record(this , "onResume");
super.onResume();
}
@Override
protected void onNewIntent(Intent intent) {
TraceRecorder.record(this , "onNewIntent");
super.onNewIntent(intent);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
TraceRecorder.record(this , "onRestoreInstanceState");
super.onRestoreInstanceState(savedInstanceState);
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
TraceRecorder.record(this , "onSaveInstanceState");
super.onSaveInstanceState(outState, outPersistentState);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
TraceRecorder.record(this , "onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
TraceRecorder.record(this , "onConfigurationChanged");
super.onConfigurationChanged(newConfig);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
TraceRecorder.record(this , "onRequestPermissionResult");
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onPause() {
TraceRecorder.record(this , "onPause");
super.onPause();
}
@Override
protected void onStop() {
TraceRecorder.record(this , "onStop");
super.onStop();
}
@OnClick({R.id.btn_add_fragment,R.id.btn_remove_fragment,R.id.btn_show_fragment,R.id.btn_hide_fragment})
public void onClick(View view){
switch (view.getId()){
case R.id.btn_add_fragment:{
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.anim_fragment_show_from_left, R.anim.anim_fragment_exit_to_right).add(R.id.fl_container , new LifecycleTestFragment() , "test").commit();
break;
}
case R.id.btn_remove_fragment:{
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.anim_fragment_show_from_left, R.anim.anim_fragment_exit_to_right).remove(getSupportFragmentManager().findFragmentByTag("test")).commit();
break;
}
case R.id.btn_hide_fragment:{
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.anim_fragment_show_from_left, R.anim.anim_fragment_exit_to_right).hide(getSupportFragmentManager().findFragmentByTag("test")).commit();
break;
}
case R.id.btn_show_fragment:{
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.anim_fragment_show_from_left, R.anim.anim_fragment_exit_to_right).show(getSupportFragmentManager().findFragmentByTag("test")).commit();
break;
}
}
}
}
| true |
0e26179a1a92ffd7c2421e2c438aa121700b2492 | Java | ChristinaDev/android-master | /baker/src/test/java/com/daniel/alexa/baker/services/youtube/YoutubeSuggestionBakerTest.java | UTF-8 | 908 | 2.234375 | 2 | [] | no_license | package com.daniel.alexa.baker.services.youtube;
import org.junit.BeforeClass;
import org.junit.Test;
import com.daniel.alexa.Downloader;
import com.daniel.alexa.baker.Alexa;
import com.daniel.alexa.baker.SuggestionBaker;
import com.daniel.alexa.baker.exceptions.ExtractionException;
import java.io.IOException;
import static org.junit.Assert.assertFalse;
import static com.daniel.alexa.baker.ServiceList.YouTube;
/**
* Test for {@link SuggestionBaker}
*/
public class YoutubeSuggestionBakerTest {
private static SuggestionBaker suggestionBaker;
@BeforeClass
public static void setUp() throws Exception {
Alexa.init(Downloader.getInstance());
suggestionBaker = YouTube.getSuggestionBaker();
}
@Test
public void testIfSuggestions() throws IOException, ExtractionException {
assertFalse(suggestionBaker.suggestionList("hello", "de").isEmpty());
}
}
| true |
b80aeb04540c775b6f30d19d88a252979b8e3f8c | Java | JGerdes/Schauburgr | /app/src/main/java/com/jonasgerdes/schauburgr/usecase/home/guide/GuideContract.java | UTF-8 | 956 | 1.882813 | 2 | [
"MIT"
] | permissive | package com.jonasgerdes.schauburgr.usecase.home.guide;
import com.jonasgerdes.schauburgr.model.schauburg.entity.Screening;
import com.jonasgerdes.schauburgr.model.schauburg.entity.ScreeningDay;
import com.jonasgerdes.schauburgr.mvp.BasePresenter;
import com.jonasgerdes.schauburgr.mvp.BaseView;
import io.realm.RealmResults;
public interface GuideContract {
interface View extends BaseView<GuideContract.Presenter> {
void showScreeningDays(RealmResults<ScreeningDay> screeningDays, boolean animate);
void showIsLoading(boolean show);
void showError(String message);
void showError(int messageResource);
void hideError();
void openWebpage(String url);
}
interface Presenter extends BasePresenter<GuideContract.View> {
void loadGuide(boolean forceRefresh);
void onRefreshTriggered();
void onScreeningSelected(Screening screening);
void onCinemaChanged();
}
} | true |
5c36461abc9181830998890319670d432c24c2df | Java | jazl/tw | /src/com/fortify/fod/remediation/ui/OpenEditorAction.java | UTF-8 | 2,791 | 2.265625 | 2 | [] | no_license | package com.fortify.fod.remediation.ui;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorProvider;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.testFramework.LightVirtualFile;
public class OpenEditorAction extends AnAction {
private String fileName = "filename.java";
private Project project;
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
project = anActionEvent.getProject();
showInMemoryDocument();
}
private String getFileContent() {
StringBuilder sb = new StringBuilder(100);
for(int i=0; i<100; i++) {
sb.append("Line "+i+": opened in project "+project.getName()+"\n");
}
String fileContent = sb.toString();
return fileContent;
}
private void showInMemoryDocument() {
FileEditorManager fem = FileEditorManager.getInstance(project);
LightVirtualFile vf = new LightVirtualFile(fileName, getFileContent());
FileType fileType = vf.getFileType();
System.out.println("fileType = "+fileType);
FileTypeManager fileTypeManager = FileTypeManager.getInstance();
FileType knownFileTypeOrAssociate = fileTypeManager.getKnownFileTypeOrAssociate(vf, project);
System.out.println("knownFileTypeOrAssociate = "+knownFileTypeOrAssociate);
if(knownFileTypeOrAssociate == null) {
FileTypeManager.getInstance().registerFileType(StdFileTypes.PLAIN_TEXT, vf.getExtension());
}
if(fileType==StdFileTypes.UNKNOWN){
//FileTypeManager.getInstance().registerFileType(StdFileTypes.PLAIN_TEXT, fileExtensions);
//vf.setFileType(StdFileTypes.PLAIN_TEXT);
// FileType knownFileTypeOrAssociate = FileTypeManager.getInstance().getKnownFileTypeOrAssociate(vf, project);
// System.out.println("knownFileTypeOrAssociate = "+knownFileTypeOrAssociate);
}
OpenFileDescriptor fd = new OpenFileDescriptor(project, vf);
java.util.List<FileEditor> fileEditors = fem.openEditor(fd, true);
System.out.println("fileEditors.size() = "+fileEditors.size());
//FileEditor[] fileEditors1 = fem.openFile(vf, true);
//Editor editor = fem.openTextEditor(fd, true);
//System.out.println("Editor = "+editor);
}
}
| true |
9018cc90905b3558f6a45055378604fb248f2501 | Java | Taranovski/EpamSpringProject | /src/test/java/com/epam/training/movie/theater/service/user/UserServiceImplTest.java | UTF-8 | 1,164 | 1.804688 | 2 | [] | no_license | /*
* 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 com.epam.training.movie.theater.service.user;
import com.epam.training.movie.theater.BaseTest;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.GenericXmlContextLoader;
/**
*
* @author Alyx
*/
//@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(
// locations = {"/test-MovieTheatre-servlet.xml"},
// loader = GenericXmlContextLoader.class
//)
public class UserServiceImplTest extends BaseTest {
@Autowired
UserServiceImpl userService;
public UserServiceImplTest() {
}
@Test
public void shouldResolveDependencies() {
assertNotNull(userService.getTicketDao());
assertNotNull(userService.getUserDao());
}
}
| true |