text
stringlengths 10
2.72M
|
|---|
package test.nz.org.take.compiler.scenario0;
import static org.junit.Assert.*;
import java.util.Iterator;
import org.junit.Test;
import test.nz.org.take.compiler.scenario0.generatedclasses.KB;
import test.nz.org.take.compiler.scenario0.generatedclasses.son;
public class Tests {
@Test
public void test1() throws Exception {
Iterator<son> results = new KB().son_01("jens");
assertTrue(results.hasNext());
}
}
|
package frameworksamples;
import graphana.MainControl;
import graphana.script.GraphanaDefaultScriptSystem;
import graphana.script.bindings.GraphanaScriptSystemInterface;
import view.userinterfaces.ConsoleInteraction;
public class ScriptMain {
public static void main(String[] args) {
ConsoleInteraction consoleInteraction = new ConsoleInteraction();
GraphanaScriptSystemInterface scriptSystem = new GraphanaDefaultScriptSystem();
new MainControl(consoleInteraction, scriptSystem);
consoleInteraction.userOutput("Graphana started\n");
global.Debug.debugOn = true;
consoleInteraction.mainLoop();
}
}
|
package com.tencent.mm.pluginsdk.g.a.a;
import com.tencent.mm.kernel.g;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.storage.aa.a;
final class p {
static void atx() {
g.Eh().dpP.a(new m(), 0);
if (g.Eg().Dx()) {
g.Ei().DT().a(a.sRH, Long.valueOf(bi.VE() + 86400));
}
}
}
|
package lexer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import errors.EndOfFileException;
import interpretator.Interpretator;
public class SourcesManager {
private Reader reader;
private Integer numberLine;
private Integer numberCharInLine;
public void setFile(String path) throws FileNotFoundException, IOException
{
numberLine = 1;
numberCharInLine = 0;
Charset encoding = Charset.defaultCharset();
InputStream in = new FileInputStream(new File(path));
reader = new InputStreamReader(in, encoding);
}
public char getNextChar() throws EndOfFileException
{
try {
char ch;
int r;
do
{
r = reader.read();
if(r == -1)
throw new EndOfFileException();
ch = (char) r;
}while(ch == '\r');
if(ch == '\n')
{
numberLine++;
numberCharInLine = 0;
}
else
numberCharInLine++;
return (char) r;
} catch (IOException e) {
Interpretator.printLine("Blad IO", false);
//e.printStackTrace();
}
return 0;
}
public Integer getNumberLine() {
return numberLine;
}
public Integer getNumberCharInLine() {
return numberCharInLine;
}
}
|
package com.tencent.mm.plugin.wallet.balance.a.a;
import com.tencent.mm.ab.a$a;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.protocal.c.bdm;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.vending.c.a;
import com.tencent.mm.vending.g.b;
class m$2 implements a<Void, a$a<bdm>> {
final /* synthetic */ b dEk;
final /* synthetic */ m oZb;
m$2(m mVar, b bVar) {
this.oZb = mVar;
this.dEk = bVar;
}
public final /* synthetic */ Object call(Object obj) {
a$a a_a = (a$a) obj;
x.i("MicroMsg.LqtSaveFetchInteractor", "on qry purchase result finish, cgiBack: %s, errType: %s, errCode: %s", new Object[]{a_a, Integer.valueOf(a_a.errType), Integer.valueOf(a_a.errCode)});
if (a_a.errType == 0 && a_a.errCode == 0) {
bdm bdm = (bdm) a_a.dIv;
x.i("MicroMsg.LqtSaveFetchInteractor", "on qry purchase result finsih, retcode: %s, retmsg: %s, purchase_state: %s", new Object[]{Integer.valueOf(bdm.hwV), bdm.hwW, Integer.valueOf(bdm.sfv)});
if (bdm.hwV == 0) {
this.dEk.v(new Object[]{bdm});
h.mEJ.a(663, 6, 1, false);
} else {
this.dEk.ct(bdm.hwW);
h.mEJ.a(663, 7, 1, false);
}
} else {
this.dEk.ct(Boolean.valueOf(false));
h.mEJ.a(663, 8, 1, false);
}
return uQG;
}
}
|
package pers.jim.app.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import pers.jim.app.business.UserService;
import pers.jim.app.exception.HttpException;
import pers.jim.app.model.LoginResult;
@RestController
@Api(tags = {"登录"})
@RequestMapping(value = "/apis/login",produces = "application/json")
public class Login {
@Autowired
UserService userService;
@PostMapping(value = "/user")
@ApiOperation(value = "检验密码是否正确",response = LoginResult.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "用户名", dataType = "string", paramType = "query", example = "Jim", required = true),
@ApiImplicitParam(name = "password", value = "密码", dataType = "string", paramType = "query", example = "1", required = true)
})
public Object getUser(@RequestParam String name,
@RequestParam String password) throws HttpException {
String token = userService.checkPassword(name, password) ;
if(token != null) {
return new LoginResult(token);
}else {
throw new HttpException(412,"密码/账号不正确");
}
}
}
|
package com.smxknife.softmarket.util;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
public class WeChatUtil {
public static String signature(String token, String timestamp, String notice) {
String[] arrays = new String[] {token, timestamp, notice};
Arrays.sort(arrays);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < arrays.length; i++) {
builder.append(arrays[i]);
}
MessageDigest md = null;
String tmpStr = null;
try {
md = MessageDigest.getInstance("SHA-1");
// 将三个参数字符串拼接成一个字符串进行 sha1 加密
byte[] digest = md.digest(builder.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
builder = null;
return tmpStr;
}
public static boolean checkSignature(String signature, String timestamp, String notice, String token) {
String tmpStr = signature(token, timestamp, notice);
// 将 sha1 加密后的字符串可与 signature 对比,标识该请求来源于微信
return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
}
/**
* 将字节数组转换为十六进制字符串
* @param byteArray
* @return
*/
private static String byteToStr(byte[] byteArray) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < byteArray.length; i++) {
builder.append(byteToHexStr(byteArray[i]));
}
return builder.toString();
}
/**
* 将字节转换为十六进制字符串
* @param mByte
* @return
*/
private static String byteToHexStr(byte mByte) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
String s = new String(tempArr);
return s;
}
public static Map<String, String> parseXml(HttpServletRequest request) throws IOException, DocumentException {
// 将解析结果存储在HashMap中
Map<String,String> map = new HashMap<>();
// 从request中获取输入流
try (InputStream inputStream = request.getInputStream()) {
// 读取输入流
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
// 得到根元素
Element root = document.getRootElement();
// 得到根元素的所有子节点
List<Element> elements = root.elements();
// 遍历所有子节点
for (Element element : elements) {
map.put(element.getName(), element.getText());
}
}
return map;
}
// public static String sendTextMsg(Map<String, String> requestMap, String content) {
// Map<String, Object> responseMap = new HashMap<>();
// responseMap.put(WeChatConstant.FROM_USER_NAME, requestMap.get(WeChatConstant.TO_USER_NAME));
// responseMap.put(WeChatConstant.TO_USER_NAME, requestMap.get(WeChatConstant.FROM_USER_NAME));
// responseMap.put(WeChatConstant.MSG_TYPE, MsgType.text.name());
// responseMap.put(WeChatConstant.CREATE_TIME, new Date().getTime());
// responseMap.put(WeChatConstant.CONTENT, content);
//
// return mapToXml(responseMap);
// }
public static String mapToXml(Map<String, Object> map) {
StringBuilder builder = new StringBuilder();
builder.append("<xml>");
mapToXml2(map, builder);
builder.append("</xml>");
return builder.toString();
}
private static void mapToXml2(Map<String, Object> map, StringBuilder builder) {
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
Object value = map.get(key);
if (value == null) value = "";
if (ArrayList.class.isAssignableFrom(value.getClass())) {
ArrayList list = (ArrayList) value;
builder.append("<" + key + ">");
for (int i = 0; i < list.size(); i++) {
HashMap hashMap = (HashMap) list.get(i);
mapToXml2(hashMap, builder);
}
builder.append("</" + key + ">");
} else if (Map.class.isAssignableFrom(value.getClass())){
builder.append("<" + key + ">");
mapToXml2((Map) value, builder);
builder.append("</" + key + ">");
} else {
builder.append("<" + key + "><![CDATA[" + value + "]]></" + key + ">");
}
}
}
}
|
package com.igitras.codegen.common.next.processors;
import com.igitras.codegen.common.next.CgElement;
import com.igitras.codegen.common.next.ResolveState;
import com.igitras.codegen.common.next.annotations.NotNull;
/**
* Created by mason on 1/5/15.
*/
public interface CgScopeProcessor {
interface Event {
Event SET_DECLARATION_HOLDER = new Event() {};
}
/**
* @param element candidate element.
* @param state current state of resolver.
* @return false to stop processing.
*/
boolean execute(@NotNull CgElement element, @NotNull ResolveState state);
// @Nullable
// <T> T getHint(@NotNull Key<T> hintKey);
//
// void handleEvent(@NotNull Event event, @Nullable Object associated);
}
|
package com.rickyluu.locker;
public class App extends TimerRunner{
boolean running = false;
public App() throws InterruptedException {
System.out.println("Proccess ID " +Kernel32.getProccessID(Kernel32.GetCurrentProcessHandle()));
System.out.println("SET CPU ussage to 1" +Kernel32.setProccessAffinity(Kernel32.GetCurrentProcessHandle(), 1));
running = true;
while(running) {
Thread.sleep(1000);
userIsInactive();
}
}
public static void main(String[] args) {
try {
new App();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void stopChecking() {
running = false;
}
public void startChecking() {
running = false;
}
public void userIsInactive() {
int secondsInactive = this.getInactiveActvitySeconds();
System.out.println("seconds "+secondsInactive);
if(secondsInactive >=45 ) {
System.out.println("lock this machine");
secondsInactive = 0;
User32.lockUser();
}
if(secondsInactive <60 ) {
System.out.println("user still active.");
}
}
}
|
/**
* Coppyright (C) 2020 Luvina
* MstJapanLogics.java, Nov 17, 2020, BuiTienDung
*/
package Manageruser.logics;
import java.util.List;
import Manageruser.entities.MstJapanEntities;
/**
* @author LA-PM
*
*/
public interface MstJapanLogics {
public List<MstJapanEntities> getAllMstJapan();
}
|
package com.penzias.controller;
import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import com.alibaba.fastjson.JSONObject;
import com.penzias.core.commons.AjaxConroller;
import com.penzias.entity.SmUser;
import com.penzias.entity.UserPersonalInfo;
import com.penzias.entity.UserPersonalInfoExample;
import com.penzias.service.SmUserService;
import com.penzias.service.UserPersonalInfoService;
import com.penzias.util.CookieUtil;
/**
* <b>描述:</b>用户操作控制器 <br/>
* <b>作者:</b>zrb <br/>
* <b>修改日期:</b>2016年1月15日 - 下午5:01:25<br/>
*
*/
@Controller
@RequestMapping("user")
public class UserInfoController extends AjaxConroller{
@Resource
private SmUserService smUserService;
@Resource
private UserPersonalInfoService userPersonalInfoService;
/**
* <b>作者:</b> zrb<br/>
* <b>修改时间:</b>2016年1月15日 - 下午5:11:11<br/>
* <b>功能说明:</b>跳转添加个人信息页面<br/>
* @param model
* @return
*/
@RequestMapping("add")
public String addUserInfoPage(Model model, HttpServletRequest request){
String username = CookieUtil.getCookieValueByName(request, cookieUserNameKey);
UserPersonalInfoExample example = new UserPersonalInfoExample();
example.createCriteria().andUsernameEqualTo(username);
List<UserPersonalInfo> list = this.userPersonalInfoService.list(example);
if(list.size()>0){
model.addAttribute("bean",list.get(0));
}else{
model.addAttribute("bean",new UserPersonalInfo());
}
return "user/user_info";
}
/**
* <b>作者:</b> zrb<br/>
* <b>修改时间:</b>2016年1月15日 - 下午5:11:28<br/>
* <b>功能说明:</b>保存用户个人信息<br/>
* @param bean
* @param model
* @param request
* @return
*/
@RequestMapping("saveinfo")
public String saveUserInfo(UserPersonalInfo bean, Model model, HttpServletRequest request){
String username = bean.getUsername();
if(!StringUtils.isEmpty(username)){
this.userPersonalInfoService.updateById(bean);
}else{
this.userPersonalInfoService.add(bean);
}
return "redirect:/user/add.htm";
}
/**
* <b>作者:</b> zrb<br/>
* <b>修改时间:</b>2016年1月15日 - 下午5:24:31<br/>
* <b>功能说明:</b>跳转修改密码页面<br/>
* @param model
* @return
*/
@RequestMapping("torepwd")
public String modifyPasswordPage(Integer err, Model model, HttpServletRequest request){
if(null!=err){
if(1==err){
model.addAttribute("error",getMessage(request, "user.resetpassword.err"));
}
}
return "user/reset_password";
}
/**
* 方法名称: validatePassword<br/>
* 描述:校验原密码<br/>
* 作者: ruibo<br/>
* 修改日期:2016年1月17日-上午10:34:12<br/>
* @throws IOException
*/
@RequestMapping("vp")
public void validatePassword(String pwd, HttpServletRequest request, HttpServletResponse response) throws IOException{
String username = CookieUtil.getCookieValueByName(request, cookieUserNameKey);
SmUser user = this.smUserService.getById(username);
String encryptedPassword = DigestUtils.md5Hex(pwd);
JSONObject obj = new JSONObject();
if(!encryptedPassword.equals(user.getPassword())){
obj.put("msg","原密码错误!");
obj.put("state",400);
writeJson(response, obj.toJSONString());
}else{
obj.put("state",200);
writeJson(response, obj.toJSONString());
}
}
/**
* <b>作者:</b> zrb<br/>
* <b>修改时间:</b>2016年1月15日 - 下午5:24:51<br/>
* <b>功能说明:</b>修改密码页面<br/>
* @param oldPassword
* @param pwd
* @param model
* @param request
* @return
*/
@RequestMapping("repwd")
public String modifyPassword(String oldPassword, String pwd, Model model, HttpServletRequest request){
String username = CookieUtil.getCookieValueByName(request, cookieUserNameKey);
SmUser user = this.smUserService.getById(username);
String encryptedPassword = DigestUtils.md5Hex(oldPassword);
if(encryptedPassword.equals(user.getPassword())){
String encryptedPwd = DigestUtils.md5Hex(pwd);
user.setPassword(encryptedPwd);
this.smUserService.updateById(user);
//提示需要重新登录,然后重新登录
return "redirect:/logout.htm?err=2";
}else{
//原密码错误
return "redirect:/user/torepwd.htm?err=1";
}
}
}
|
package com.sixmac.service;
import com.sixmac.entity.Team;
import com.sixmac.service.common.ICommonService;
import org.springframework.data.domain.Page;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2016/5/18 0018 上午 9:55.
*/
public interface TeamService extends ICommonService<Team> {
public Page<Team> page(String name, Long cityId, Integer pageNum, Integer pageSize);
public Team findListByLeaderId(Long leaderId);
// 球队详情
public Map<String, Object> info(HttpServletResponse response, Long teamId);
// 邀请朋友加入球队
public void addFriend(HttpServletResponse response, Long userId, Long toUserId);
// 申请加入球队
public void apply(HttpServletResponse response, Long userId, Long teamId);
// 约球队详情
public void orderInfo(HttpServletResponse response,
Long team1Id,
Long team2Id,
Long time,
Long cityId);
}
|
package net.sf.ardengine.sound;
import net.sf.ardengine.renderer.Renderers;
import paulscode.sound.SoundSystem;
import paulscode.sound.SoundSystemConfig;
import paulscode.sound.SoundSystemException;
import paulscode.sound.codecs.CodecIBXM;
import paulscode.sound.codecs.CodecJOgg;
import paulscode.sound.libraries.LibraryJavaSound;
import paulscode.sound.codecs.CodecWav;
import paulscode.sound.libraries.LibraryLWJGLOpenAL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Simple class responsible for initializing Paulscode soundsystem.
*/
public class SoundManager {
private final static Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
/** http://www.paulscode.com/tutorials/SoundSystem/SoundSystem.pdf */
private static SoundSystem system;
/**
* Initializes SoundSystem, called automatically.
* @param preferredLib Renderers.JAVAFX(JavaSound) / other(OpenAL)
*/
public static void init(Renderers preferredLib){
try
{
//Plugins
SoundSystemConfig.setCodec( "wav", CodecWav.class );
SoundSystemConfig.setCodec( "ogg", CodecJOgg.class );
SoundSystemConfig.setCodec( "s3m", CodecIBXM.class );
SoundSystemConfig.setCodec( "mod", CodecIBXM.class );
SoundSystemConfig.setCodec( "xm", CodecIBXM.class );
system = new SoundSystem((preferredLib== Renderers.JAVAFX)?LibraryJavaSound.class:LibraryLWJGLOpenAL.class);
//SoundSystemConfig.setSoundFilesPackage("net/sf/ardengine/res/");
//system.backgroundMusic( "boss", "boss.ogg", true);
//system.play("boss");
}
catch( SoundSystemException e )
{
LOGGER.log(Level.SEVERE, "Failed to load sound system!", e);
}
}
/**
* @return Paulscode awesome sound system
*/
public static SoundSystem getSystem() {
return system;
}
/**
* Frees SoundSystem resources, called automatically.
*/
public static void cleanUp(){
system.cleanup();
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.common.populator.impl;
import static java.util.Locale.ENGLISH;
import static java.util.Locale.FRENCH;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.cmsfacades.data.ComposedTypeData;
import de.hybris.platform.cmsfacades.languages.LanguageFacade;
import de.hybris.platform.commercefacades.storesession.data.LanguageData;
import de.hybris.platform.core.model.type.ComposedTypeModel;
import de.hybris.platform.servicelayer.i18n.CommonI18NService;
import java.util.Locale;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.common.collect.Lists;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class ComposedTypeModelPopulatorTest
{
private static final String CODE = "code";
private static final String NAME_EN = "name-EN";
private static final String NAME_FR = "name-FR";
private static final String DESCRIPTION_EN = "description-EN";
private static final String DESCRIPTION_FR = "description-FR";
private static final String EN = Locale.ENGLISH.getLanguage();
private static final String FR = Locale.FRENCH.getLanguage();
@Mock
private ComposedTypeModel composedTypeModel;
@Mock
private LanguageFacade languageFacade;
@Mock
private CommonI18NService commonI18NService;
@InjectMocks
private DefaultLocalizedPopulator localizedPopulator;
@InjectMocks
private ComposedTypeModelPopulator populator;
private ComposedTypeData composedTypeData;
@Before
public void setUp()
{
composedTypeData = new ComposedTypeData();
when(composedTypeModel.getName(Locale.ENGLISH)).thenReturn(NAME_EN);
when(composedTypeModel.getName(Locale.FRENCH)).thenReturn(NAME_FR);
when(composedTypeModel.getDescription(Locale.ENGLISH)).thenReturn(DESCRIPTION_EN);
when(composedTypeModel.getDescription(Locale.FRENCH)).thenReturn(DESCRIPTION_FR);
when(composedTypeModel.getCode()).thenReturn(CODE);
final LanguageData languageEN = new LanguageData();
languageEN.setIsocode(EN);
final LanguageData languageFR = new LanguageData();
languageFR.setIsocode(FR);
when(languageFacade.getLanguages()).thenReturn(Lists.newArrayList(languageEN, languageFR));
when(commonI18NService.getLocaleForIsoCode(EN)).thenReturn(ENGLISH);
when(commonI18NService.getLocaleForIsoCode(FR)).thenReturn(FRENCH);
populator.setLocalizedPopulator(localizedPopulator);
}
@Test
public void shouldPopulateNonLocalizedAttributes()
{
populator.populate(composedTypeModel, composedTypeData);
assertThat(composedTypeData.getCode(), equalTo(CODE));
}
@Test
public void shouldPopulateLocalizedAttributes_NullMaps()
{
composedTypeData.setName(null);
composedTypeData.setDescription(null);
populator.populate(composedTypeModel, composedTypeData);
assertThat(composedTypeData.getName().get(EN), equalTo(NAME_EN));
assertThat(composedTypeData.getName().get(FR), equalTo(NAME_FR));
assertThat(composedTypeData.getDescription().get(EN), equalTo(DESCRIPTION_EN));
assertThat(composedTypeData.getDescription().get(FR), equalTo(DESCRIPTION_FR));
}
@Test
public void shouldPopulateLocalizedAttributes_AllLanguages()
{
populator.populate(composedTypeModel, composedTypeData);
assertThat(composedTypeData.getName().get(EN), equalTo(NAME_EN));
assertThat(composedTypeData.getName().get(FR), equalTo(NAME_FR));
assertThat(composedTypeData.getDescription().get(EN), equalTo(DESCRIPTION_EN));
assertThat(composedTypeData.getDescription().get(FR), equalTo(DESCRIPTION_FR));
}
}
|
import java.time.LocalDateTime;
public class PetDog {
private int HP;//生命值 上限1000
private int hungerValue;//飢餓值 上限100
private int thirstValue;//口渴值 上限100
private LocalDateTime lastUpdateTime;
private boolean isHunger;
private boolean isThirst;
private boolean doReviseHP;
private boolean wearMask;//true為有戴
private Decoration decoration;
public PetDog(int HP,int hungerValue,int thirstValue,String lastTime,boolean doReviseHP,boolean isHunger,boolean isThirst,boolean wearMask,Decoration decoration)
{
this.HP=HP;
this.hungerValue=hungerValue;
this.thirstValue=thirstValue;
this.isHunger=isHunger;
this.isThirst=isThirst;
this.doReviseHP=doReviseHP;
this.lastUpdateTime=LocalDateTime.parse(lastTime);
this.wearMask=wearMask;
this.decoration=decoration;
updatePetStatus();
}
public void setHP(int HP){
this.HP=HP;
}
public void setHungerValue(int hungerValue){
this.hungerValue=hungerValue;
}
public void setThirstValue(int thirstValue){
this.thirstValue=thirstValue;
}
public void setLastUpdateTime(LocalDateTime lt){
this.lastUpdateTime=lt;
}
public void setDoReviseHP(boolean doReviseHP){
this.doReviseHP = doReviseHP;
}
public void setIsHunger(boolean isHunger){
this.isHunger=isHunger;
}
public void setIsThirst(boolean isThirst){
this.isThirst=isThirst;
}
public void setDecoration(Decoration decoration){
this.decoration=decoration;
}
public void setWearMask(boolean wearMask)
{
this.wearMask = wearMask;
}
public boolean getWearMask()
{
return this.wearMask;
}
public int getHP(){
return this.HP;
}
public int getHungerValue(){
return this.hungerValue;
}
public int getThirstValue(){
return this.thirstValue;
}
public LocalDateTime getLastUpdateTime(){
return this.lastUpdateTime;
}
public boolean getIsHunger(){
return this.isHunger;
}
public boolean getDoReviseHP(){
return this.doReviseHP;
}
public boolean getIsThirst(){
return this.isThirst;
}
public Decoration getDecoration(){
return this.decoration;
}
public void eatFood(int number){
this.hungerValue+=number*5;
if(hungerValue>=100){
this.hungerValue=100;
}
this.checkHungerAndThirstStatus();
}
public void drinkWater(int number){
this.thirstValue+=number*5;
if(thirstValue>=100){
this.thirstValue=100;
}
this.checkHungerAndThirstStatus();
}
public void useMedicine(int input){
this.hungerValue=100;
this.thirstValue=100;
this.HP=1000;
this.checkHungerAndThirstStatus();
}
public void decreaseHungerAndThirstValue()//每隔15分鐘呼叫一次扣減飢渴值
{
this.hungerValue-=1;
this.thirstValue-=1;
if(this.hungerValue<0){
this.hungerValue=0;
}
if(this.thirstValue<0){
this.thirstValue=0;
}
if(doReviseHP){
this.reviseHP();
this.doReviseHP=false;
}else{
this.doReviseHP=true;
}
this.checkHungerAndThirstStatus();
}
public void reviseHP()//根據飢渴度調整HP
{
if((this.hungerValue>80 || this.thirstValue>80))
{
if (Math.min((this.hungerValue), this.thirstValue)>=80)
{
this.HP+=Math.max(200-this.hungerValue-thirstValue,25);
}
else if(this.hungerValue<60)
this.HP-=(80-this.hungerValue)/4;
else if(this.thirstValue<60)
this.HP-=(80-this.thirstValue)/4;
}else{
this.HP-=((160-this.hungerValue-this.thirstValue)/8+Math.min(20, Math.abs(this.hungerValue-this.thirstValue)));
}
if(this.HP<0)
this.HP=0;
else if(this.HP>1000)
this.HP=1000;
}
public void checkHungerAndThirstStatus()//確認寵物的饑渴狀態
{
if((this.hungerValue>80 || this.thirstValue>80))
{
if(this.hungerValue<60)
{
this.isHunger=true;
this.isThirst=false;
}
else if(this.thirstValue<60)
{
this.isHunger=false;
this.isThirst=true;
}
else
{
this.isHunger=false;
this.isThirst=false;
}
}
else
{
this.isHunger=true;
this.isThirst=true;
}
if(HP<=200)
{
this.decoration=Decoration.nothing;
this.wearMask=false;
}
}
public void updatePetStatus()//在開啟程式時補上次關掉程式後的進度
{
while(lastUpdateTime.plusMinutes(15).isBefore(LocalDateTime.now()))
{
lastUpdateTime=lastUpdateTime.plusMinutes(15);
this.decreaseHungerAndThirstValue();
}
}
public String formatCsvString(){
return String.format(this.HP+","+this.hungerValue+","+this.thirstValue+","+this.lastUpdateTime.toString()+","+this.doReviseHP+","+this.isHunger+","+this.isThirst+","+this.wearMask+","+this.decoration);
}
}
|
package fr.cg95.cvq.business;
/**
* Marker interface for objects interested in automatic historization.
*
* Currently only applies in the context of an home folder modification request but
* can be extended to other usages.
*
* @author bor@zenexity.fr
*
*/
public interface Historizable {
public Long getId();
}
|
package fl.sabal.source.interfacePC.Codes.Event;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
/**
*
* @author FL-AndruAnnohomy
*/
@SuppressWarnings("serial")
public class styleTable extends DefaultTableCellRenderer implements TableCellRenderer {
/* (non-Javadoc)
* @see javax.swing.table.DefaultTableCellRenderer#getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
*/
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
setBackground(null);
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
boolean oddRow = row % 2 == 0;
if (oddRow) {
setBackground(new Color(132, 189, 0));
}
return this;
}
}
|
package coreClasses.threadLocal;
import java.util.concurrent.CountDownLatch;
import static coreClasses.threadLocal.BrokenSampleDatabaseConnection.getConnection;
public class DBAppBroken {
public static void main(String[] args) throws InterruptedException {
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final Thread thread1 = new Thread(() -> {
getConnection().addOrOverwriteTable("this one didn't write");
latch1.countDown();
try {
latch2.await();
} catch (InterruptedException consume) { }
getConnection().addRowIfTableExists("table1", "row2 is not written");
});
final Thread thread2 = new Thread(() -> {
getConnection().addOrOverwriteTable("this one didn't write");
try {
latch1.await();
} catch (InterruptedException consume) {}
getConnection().addOrOverwriteTable("table1");
getConnection().addRowIfTableExists("table1", "row1 is written");
getConnection().close();
latch2.countDown();
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(getConnection().getDb());
}
}
|
package com.bat.message.exchange.event;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
/**
* 使用监听器获取连接到webSocket的session
*
* @author ZhengYu
* @version 1.0 2019/11/27 17:24
**/
@Slf4j
@Component
public class WebSocketConnectEventListener {
/**
* websocket 连接建立事件 监听
*
* @param event 连接建立事件
* @author ZhengYu
*/
@EventListener
public void handleWebSocketConnectedListener(SessionConnectEvent event) {
log.info("=== [{}]", JSONObject.toJSONString(event));
}
/**
* websocket 连接断开事件 监听
*
* @param event 连接断开事件
* @author ZhengYu
*/
@EventListener
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
log.info("### [{}]", JSONObject.toJSONString(event));
}
}
|
/*
* 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 rs_project;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import MainClasses.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
/**
*
* @author Samosad
*/
public class frmEventInfo extends Application {
ArrayList<SubjectEvent> events;
int currentEventNumber;
Button btnNext;
Button btnPrevious;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Задания");
SubjectEvent currentEvent = events.get(currentEventNumber);
Label lblInfo = CreateLabels(currentEvent);
btnNext = new Button();
btnNext.setText("Next Event");
btnPrevious = new Button();
btnPrevious.setText("Previous Event");
GridPane grid = CreateGrid(lblInfo);
ScrollPane sp = new ScrollPane(grid);
Scene scene = new Scene(grid, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
//ScrollPane sp= new ScrollPane();
btnNext.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
grid.getChildren().clear();
if (currentEventNumber < events.size() - 1) {
currentEventNumber++;
} else {
currentEventNumber = 0;
}
try {
start(primaryStage);
} catch (Exception ex) {
Logger.getLogger(frmEventInfo.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
btnPrevious.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
grid.getChildren().clear();
if (currentEventNumber != 0) {
currentEventNumber--;
} else {
currentEventNumber = events.size() - 1;
}
try {
start(primaryStage);
} catch (Exception ex) {
Logger.getLogger(frmEventInfo.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public void SetEvents(ArrayList<SubjectEvent> ev) {
events = ev;
}
private Label CreateLabels(SubjectEvent events) {
Label tempLbl = new Label(DataProcessor.GetLabelText(events));
tempLbl.setFont(Font.font("Tahoma", FontWeight.NORMAL, 15));
return tempLbl;
}
private GridPane CreateGrid(Label lblList) {
GridPane grid = new GridPane();
grid.add(lblList, 1, 1);
grid.add(btnNext, 2, 2);
grid.add(btnPrevious, 1, 2);
return grid;
}
}
|
package com.example.dto;
public class ProductDto {
private String name;
private String description;
private float price;
private String category_name;
public ProductDto(){}
public ProductDto(String name, String description, float price, String category_name){
this.name=name;
this.description= description;
this.price=price;
this.category_name=category_name;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public float getPrice() {
return this.price;
}
public void setPrice(float price) {
this.price = price;
}
public String getCategory_name() {
return this.category_name;
}
public void setCategory_name(String category_name) {
this.category_name = category_name;
}
}
|
package edu.lab.server.coodinator.communication.requests;
import edu.lab.server.coodinator.communication.Request;
import edu.lab.server.coodinator.communication.RequestCode;
public class UpdateTableRequest extends Request {
public UpdateTableRequest(RequestCode code) {
super(code);
}
@Override
protected void buildInfoBytes() {
//доп инфы нет
}
}
|
package com.tencent.mm.g.a;
import com.tencent.mm.protocal.c.aqv;
import java.util.LinkedList;
public final class ka extends com.tencent.mm.sdk.b.b {
public a bUo;
public b bUp;
public static final class a {
public String bSr;
public boolean bTN = false;
}
public static final class b {
public int bSU = 0;
public LinkedList<aqv> bUb;
}
public ka() {
this((byte) 0);
}
private ka(byte b) {
this.bUo = new a();
this.bUp = new b();
this.sFm = false;
this.bJX = null;
}
}
|
/*******************************************************************************
* Copyright 2021 Danny Kunz
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package org.omnaest.genomics.ensembl.domain.raw;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class ExternalXRef
{
@JsonProperty("db_display_name")
private String displayName;
@JsonProperty("display_id")
private String displayId;
@JsonProperty("primary_id")
private String primaryId;
@JsonProperty
private String version;
@JsonProperty
private String description;
@JsonProperty("dbname")
private String name;
@JsonProperty
private List<String> synonyms;
@JsonProperty("info_text")
private String infoText;
@JsonProperty("info_type")
private String infoType;
@JsonProperty("ensembl_identity")
private long ensemblIdentity;
@JsonProperty("ensembl_start")
private long ensemblStart;
@JsonProperty("ensembl_end")
private long ensemblEnd;
public long getEnsemblIdentity()
{
return this.ensemblIdentity;
}
public void setEnsemblIdentity(long ensemblIdentity)
{
this.ensemblIdentity = ensemblIdentity;
}
public long getEnsemblStart()
{
return this.ensemblStart;
}
public void setEnsemblStart(long ensemblStart)
{
this.ensemblStart = ensemblStart;
}
public long getEnsemblEnd()
{
return this.ensemblEnd;
}
public void setEnsemblEnd(long ensemblEnd)
{
this.ensemblEnd = ensemblEnd;
}
public String getDisplayName()
{
return this.displayName;
}
public void setDisplayName(String displayName)
{
this.displayName = displayName;
}
public String getDisplayId()
{
return this.displayId;
}
public void setDisplayId(String displayId)
{
this.displayId = displayId;
}
public String getPrimaryId()
{
return this.primaryId;
}
public void setPrimaryId(String primaryId)
{
this.primaryId = primaryId;
}
public String getVersion()
{
return this.version;
}
public void setVersion(String version)
{
this.version = version;
}
public String getDescription()
{
return this.description;
}
public void setDescription(String description)
{
this.description = description;
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
public List<String> getSynonyms()
{
return this.synonyms;
}
public void setSynonyms(List<String> synonyms)
{
this.synonyms = synonyms;
}
public String getInfoText()
{
return this.infoText;
}
public void setInfoText(String infoText)
{
this.infoText = infoText;
}
public String getInfoType()
{
return this.infoType;
}
public void setInfoType(String infoType)
{
this.infoType = infoType;
}
@Override
public String toString()
{
return "ExternalXRef [displayName=" + this.displayName + ", displayId=" + this.displayId + ", primaryId=" + this.primaryId + ", version=" + this.version
+ ", description=" + this.description + ", name=" + this.name + ", synonyms=" + this.synonyms + ", infoText=" + this.infoText + ", infoType="
+ this.infoType + "]";
}
}
|
package com.tibco.as.io;
import java.util.ArrayList;
import java.util.Collection;
import com.tibco.as.io.transfer.Transfer;
import com.tibco.as.space.FieldDef;
import com.tibco.as.space.SpaceDef;
import com.tibco.as.space.Tuple;
import com.tibco.as.util.convert.ConverterFactory;
public abstract class AbstractDestination<T> implements IDestination {
private IChannel channel;
private SpaceDef spaceDef = SpaceDef.create();
private BrowseConfig browseConfig = new BrowseConfig();
private OperationConfig operationConfig = new OperationConfig();
protected AbstractDestination(IChannel channel) {
this.channel = channel;
}
public FieldDef[] getFieldDefs() {
String[] fieldNames = getFieldNames();
Collection<FieldDef> fieldDefs = new ArrayList<FieldDef>();
for (int index = 0; index < fieldNames.length; index++) {
FieldDef fieldDef = spaceDef.getFieldDef(fieldNames[index]);
if (fieldDef == null) {
continue;
}
fieldDefs.add(fieldDef);
}
return fieldDefs.toArray(new FieldDef[fieldDefs.size()]);
}
public String[] getFieldNames() {
Collection<String> fieldNames = new ArrayList<String>();
for (FieldDef fieldDef : spaceDef.getFieldDefs()) {
fieldNames.add(fieldDef.getName());
}
return fieldNames.toArray(new String[fieldNames.size()]);
}
@Override
public BrowseConfig getBrowseConfig() {
return browseConfig;
}
@Override
public OperationConfig getOperationConfig() {
return operationConfig;
}
public IChannel getChannel() {
return channel;
}
@Override
public SpaceDef getSpaceDef() {
return spaceDef;
}
public void setSpaceDef(SpaceDef spaceDef) {
this.spaceDef = spaceDef;
}
protected abstract IInputStream<T> getInputStream();
protected abstract IStreamAdapter<T, Tuple> getInputStreamAdapter();
protected abstract IStreamAdapter<Tuple, T> getOutputStreamAdapter();
protected abstract IOutputStream<T> getOutputStream();
@Override
public Transfer<Tuple, T> getExport() {
return getExport(new SpaceInputStream(this));
}
private Transfer<Tuple, T> getExport(IInputStream<Tuple> in) {
IStreamAdapter<Tuple, T> adapter = getOutputStreamAdapter();
IOutputStream<T> out = getOutputStream();
return new Transfer<Tuple, T>(in, adapter, out);
}
@Override
public Transfer<T, Tuple> getImport() {
IInputStream<T> in = getInputStream();
IStreamAdapter<T, Tuple> adapter = getInputStreamAdapter();
SpaceOutputStream out = new SpaceOutputStream(this);
return new Transfer<T, Tuple>(in, adapter, out);
}
@Override
public ITransfer getSNExport() {
return getExport(new SNFileInputStream(this));
}
public ConverterFactory getConverterFactory() {
ConverterFactory factory = new ConverterFactory();
factory.setConfig(channel.getConversionConfig());
return factory;
}
public abstract Class<?> getType(FieldDef fieldDef, int index);
}
|
package com.ssgl.mapper;
/*
* 功能:
* User: jiajunkang
* email:jiajunkang@outlook.com
* Date: 2018/1/1 0001
* Time: 1:20
*/
import com.ssgl.bean.City;
import com.ssgl.bean.County;
import java.util.List;
public interface CustomerAddressMapper {
List<City> selectCitiesByProvinceId(String provinceid);
List<County> selectCountiesByCityId(String cityid);
}
|
package JavaException;
public class example_uncheckedexception {
public static void main(String[] args) {
try {
System.out.println("1");//1
int a = 5/5; //1st step
System.out.println("2");//2
System.out.println(a);//1
System.out.println("3");//3
System.exit(0);
int b = 5/0;
System.out.println("4");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("5");
e.printStackTrace();
System.out.println("6");
System.exit(0);
System.out.println("7");
}finally{ // it is used for code closer, clean up
System.out.println("8");
System.out.println("code executes");
}
}
//finally : if there is exception or no exception finally code will execute
// database: if you have open a database, you need to close it. you will close code inside database
//text file, excel file
//if I write system.exit before finally will it execute
}
|
package fr.infologic.vei.audit.migration;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collections;
import oracle.jdbc.pool.OracleDataSource;
import org.junit.Ignore;
import org.junit.Test;
import fr.infologic.vei.audit.api.AuditIngestTrace;
@Ignore
public class MainTest extends AuditGatewayStub
{
private static final String URL = "jdbc:oracle:thin:@10.99.81.6:1521:orcl";
private static final String USER = "RAN_VT_VALENTIN";
private static final String PASSWORD = "RAN_VT_VALENTIN";
@Test
public void ingestAll() throws SQLException, InterruptedException, IOException
{
Main.main("8", URL, USER, PASSWORD);
}
@Test
public void ingestNightlyBuild() throws SQLException
{
OracleDataSource db = new OracleDataSource();
db.setURL("jdbc:oracle:thin:@10.99.81.19:1521:orclweiso");
db.setUser("MI_VALENTIN_HEAD");
db.setPassword("MI_VALENTIN_HEAD");
AuditKey key = new AuditKey();
key.setMetadataId("fr.infologic.stocks.cumuls.modele.Prevision");
key.setSourceDosResIK(1L);
key.setSourceEK("02J");
new AuditMongoDataSink("MI_VALENTIN_HEAD").ingest(key, new AuditOracleDataSource(db, Collections.emptySet()).fetch(key));
}
@Ignore @Test
public void unzip() throws SQLException
{
OracleDataSource db = new OracleDataSource();
db.setURL(URL);
db.setUser(USER);
db.setPassword(PASSWORD);
AuditKey key = new AuditKey();
key.setMetadataId("fr.infologic.gpao.modele.Planning");
key.setSourceDosResIK(2L);
key.setSourceEK("SEM");
new AuditMongoDataSink(this).ingest(key, new AuditOracleDataSource(db, Collections.emptySet()).fetch(key));
}
@Override
public void ingest(AuditIngestTrace patch)
{
}
@Test
public void testParse()
{
double x = new Double("36.000000");
System.out.println(x);
}
}
|
package com.example.mvpdemo0602.fragments;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
import com.example.mvpdemo0602.R;
import com.example.mvpdemo0602.base.BaseFragment;
import java.util.Timer;
import java.util.TimerTask;
import butterknife.Bind;
import butterknife.OnClick;
/**
* Created by Administrator on 2018/6/5.
*/
public class MineFragment extends BaseFragment {
@Bind(R.id.chr_mine_timer_1)
TextView mTimerTv;
@Bind(R.id.bn_mine_timer_1)
Button mBtn;
@Bind(R.id.tv_mine_title)
TextView tvTitle;
private int nums;
private Timer timer;
@Override
protected int getLayoutId() {
return R.layout.fragment_minie_1;
}
// @Nullable
// @Override
// public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.fragment_minie_1, null);
//
//
// return view;
// }
@Override
protected void initView(View view) {
tvTitle.setText("计时器:"+formatMiss(nums));
timer = new Timer();
for (int i = 0; i < 5; i++) {
mTimerTv.append("abcdeft=="+i+";");
mTimerTv.append("\r\n");
}
}
TimerTask task=new TimerTask() {
@Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
tvTitle.setText("计时器:"+formatMiss(nums));
}
});
nums++;
}
};
public String formatMiss(int time){
String hh=time/3600>9?time/3600+"":"0"+time/3600;
String mm=(time% 3600)/60>9?(time% 3600)/60+"":"0"+(time% 3600)/60;
String ss=(time% 3600) % 60>9?(time% 3600) % 60+"":"0"+(time% 3600) % 60;
return hh+":"+mm+":"+ss;
}
private boolean isStart;
@OnClick({R.id.bn_mine_timer_1})
public void onClick(View view){
switch (view.getId()){
case R.id.bn_mine_timer_1:
if (!isStart){
nums=0;
if (timer==null) timer=new Timer();
timer.schedule(task,1000,1000);
}else {
}
isStart =!isStart;
break;
}
}
@Override
protected void initData() {
}
@Override
public void onDestroyView() {
super.onDestroyView();
timer.cancel();
timer=null;
}
}
|
package com.test.class1;
import java.io.*;
public class HelloClassLoader extends ClassLoader{
public static void main(String[] args) throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException {
String path = "E:\\极客学习资料\\class1\\Hello.xlass";
ClassLoader helloClassLoader = new HelloClassLoader();
Class<?> clazz = helloClassLoader.loadClass(path);
}
private String classPath;
protected Class<?> findClass(String name){
byte [] classData = new byte[0];
try {
classData = getData(name);
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < classData.length; i++) {
classData[i] = (byte)(255-classData[i]);
}
return defineClass(name,classData,0,classData.length);
}
private byte[] getData(String name) throws IOException {
String path = name;
InputStream fileInputStream = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
fileInputStream = new FileInputStream(path);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(bytes)) != -1){
byteArrayOutputStream.write(bytes,0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(fileInputStream != null){
fileInputStream.close();
}
}
return byteArrayOutputStream.toByteArray();
}
}
|
package com.travelportal.domain.rooms;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Query;
import javax.persistence.Table;
import com.travelportal.domain.City;
import com.travelportal.domain.Country;
import com.travelportal.domain.allotment.AllotmentMarket;
import play.db.jpa.JPA;
import play.db.jpa.Transactional;
@Entity
@Table(name="specialsmarket")
public class SpecialsMarket {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String stayDays;
private String payDays;
private String typeOfStay;
public String earlyBird;
public String earlyBirdDisount;
public String earlyBirdRateCalculat;
public Double flatRate;
private boolean multiple;
private boolean combined;
public boolean breakfast;
public String adultRate;
public String childRate;
private String applyToMarket;
@OneToOne
private Specials special;
/*@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
public List<City> cities;*/
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
public List<Country> country;
public List<Country> getCountry() {
return country;
}
public void setCountry(List<Country> country) {
this.country = country;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStayDays() {
return stayDays;
}
public void setStayDays(String stayDays) {
this.stayDays = stayDays;
}
public String getPayDays() {
return payDays;
}
public void setPayDays(String payDays) {
this.payDays = payDays;
}
public String getTypeOfStay() {
return typeOfStay;
}
public void setTypeOfStay(String typeOfStay) {
this.typeOfStay = typeOfStay;
}
public boolean isMultiple() {
return multiple;
}
public void setMultiple(boolean multiple) {
this.multiple = multiple;
}
public boolean isCombined() {
return combined;
}
public void setCombined(boolean combined) {
this.combined = combined;
}
public Specials getSpecial() {
return special;
}
public void setSpecial(Specials special) {
this.special = special;
}
public String getApplyToMarket() {
return applyToMarket;
}
public void setApplyToMarket(String applyToMarket) {
this.applyToMarket = applyToMarket;
}
public boolean isBreakfast() {
return breakfast;
}
public void setBreakfast(boolean breakfast) {
this.breakfast = breakfast;
}
public String getAdultRate() {
return adultRate;
}
public void setAdultRate(String adultRate) {
this.adultRate = adultRate;
}
public String getChildRate() {
return childRate;
}
public void setChildRate(String childRate) {
this.childRate = childRate;
}
public String getEarlyBird() {
return earlyBird;
}
public void setEarlyBird(String earlyBird) {
this.earlyBird = earlyBird;
}
public String getEarlyBirdDisount() {
return earlyBirdDisount;
}
public void setEarlyBirdDisount(String earlyBirdDisount) {
this.earlyBirdDisount = earlyBirdDisount;
}
public String getEarlyBirdRateCalculat() {
return earlyBirdRateCalculat;
}
public void setEarlyBirdRateCalculat(String earlyBirdRateCalculat) {
this.earlyBirdRateCalculat = earlyBirdRateCalculat;
}
public Double getFlatRate() {
return flatRate;
}
public void setFlatRate(Double flatRate) {
this.flatRate = flatRate;
}
public static SpecialsMarket findByIdCity(long Code) {
try
{
Query query = JPA.em().createQuery("Select s from SpecialsMarket s where s.id = ?1");
query.setParameter(1, Code);
return (SpecialsMarket) query.getSingleResult();
}
catch(Exception ex){
return null;
}
}
public static SpecialsMarket findByTopid() {
try
{
return (SpecialsMarket) JPA.em().createQuery("select c from SpecialsMarket c where c.id = (select max(a.id) from SpecialsMarket a)").getSingleResult();
}
catch(Exception ex){
return null;
}
}
public static int deleteMarketSp(Long id) {
Query query = JPA.em().createQuery("delete from SpecialsMarket p where p.id = ?1");
query.setParameter(1, id);
return query.executeUpdate();
}
public static int deleteSp(Long id) {
Query query = JPA.em().createQuery("delete from SpecialsMarket p where p.special.id = ?1");
query.setParameter(1, id);
return query.executeUpdate();
}
public static List<SpecialsMarket> findBySpecialsId(Long id) {
Query query = JPA.em().createQuery("Select s from SpecialsMarket s where s.special.id = ?1");
query.setParameter(1, id);
return (List<SpecialsMarket>) query.getResultList();
}
public static List<SpecialsMarket> findBySpecialsIdnationality(Long specialId,int nation) {
List<Object[]> list;
list =JPA.em().createNativeQuery("select * from specialsmarket spm,specialsmarket_country spmc where spm.id = spmc.SpecialsMarket_id and spm.special_id ='"+specialId+"' and spmc.country_country_code = '"+nation+"'").getResultList();
List<SpecialsMarket> list1 = new ArrayList<>();
for(Object[] o :list) {
SpecialsMarket spm = new SpecialsMarket();
spm.setId(Long.parseLong(o[0].toString()));
spm.setCombined(Boolean.parseBoolean(o[1].toString()));
spm.setMultiple(Boolean.parseBoolean(o[2].toString()));
if(o[3] != null){
spm.setPayDays(o[3].toString());
}
if(o[4] != null){
spm.setStayDays(o[4].toString());
}
if(o[5] != null){
spm.setTypeOfStay(o[5].toString());
}
spm.setApplyToMarket(o[7].toString());
if(o[8] != null){
spm.setAdultRate(o[8].toString());
}
spm.setBreakfast(Boolean.parseBoolean(o[9].toString()));
if(o[10] != null){
spm.setChildRate(o[10].toString());
}
if(o[11] != null){
spm.setEarlyBird(o[11].toString());
}
if(o[12] != null){
spm.setEarlyBirdDisount(o[12].toString());
}
if(o[13] != null){
spm.setEarlyBirdRateCalculat(o[13].toString());
}
if(o[14] != null){
spm.setFlatRate(Double.valueOf(o[14].toString()));
}
list1.add(spm);
}
return list1;
}
public static SpecialsMarket findById(Long id) {
Query query = JPA.em().createQuery("Select s from SpecialsMarket s where s.id = ?1");
query.setParameter(1, id);
return (SpecialsMarket) query.getSingleResult();
}
public static int deletespecialCountry(long code) {
Query q = JPA.em().createNativeQuery("delete from specialsmarket_country where SpecialsMarket_id = '"+code+"'");
return q.executeUpdate();
}
@Transactional
public void save() {
JPA.em().persist(this);
JPA.em().flush();
}
@Transactional
public void delete() {
JPA.em().remove(this);
}
@Transactional
public void merge() {
JPA.em().merge(this);
}
@Transactional
public void refresh() {
JPA.em().refresh(this);
}
}
|
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Choice;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.List;
import java.awt.TextArea;
/**
* Frame을 확장하여 사용자 정의 Frame 만들기
* @author 이대용
*
*/
public class GridLayoutFrame extends Frame {
public GridLayoutFrame() {
this("No-Title");
}
public GridLayoutFrame(String title) {
super(title);
}
public void setContents() {
setLayout(new GridLayout(8,8));
for (int i = 0; i < 64; i++) {
Button button = new Button(i + "버튼");
add(button);
}
}
public static void main(String[] args) {
GridLayoutFrame frame = new GridLayoutFrame("확장개념을 이용한 화면 구성");
frame.setContents();
// frame.setSize(800,500);
frame.setSize(new Dimension(800, 800));
frame.setVisible(true);
}
}
|
import java.util.Arrays;
public class TwoSumLessThanK_1099 {
public static int twoSumLessThanK(int[] A, int K) {
int i = 0, j = A.length - 1, S = -1;
Arrays.sort(A);
while (i < j) {
int sum = A[i] + A[j];
if (sum < K) {
S = Math.max(S, sum);
i++;
} else{
j--;
}
}
return S;
}
public static void main(String[] args){
System.out.println(twoSumLessThanK(new int[]{1, 2, 34, 4, 5, 6, 23, 12}, 50));
}
}
|
package com.google.android.gms.common.api;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.google.android.gms.common.api.o.b;
final class o$a extends Handler {
final /* synthetic */ o aLG;
o$a(o oVar, Looper looper) {
this.aLG = oVar;
super(looper);
}
public final void handleMessage(Message message) {
switch (message.what) {
case 1:
o oVar = this.aLG;
oVar.aKI.lock();
try {
if (oVar.oS()) {
oVar.connect();
}
oVar.aKI.unlock();
return;
} catch (Throwable th) {
oVar.aKI.unlock();
}
case 2:
o.a(this.aLG);
return;
case 3:
((b) message.obj).b(this.aLG);
return;
case 4:
throw ((RuntimeException) message.obj);
default:
new StringBuilder("Unknown message id: ").append(message.what);
return;
}
}
}
|
package com.rile.methotels.services.dao;
import com.rile.methotels.entities.Korisnik;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
/**
*
* @author Stefan
*/
public class KorisnikDaoImpl extends GenericDaoImpl<Korisnik> implements KorisnikDao {
@Override
public Korisnik checkKorisnik(String korisnickoIme, String lozinka) {
try {
Korisnik korisnik = (Korisnik) session.createCriteria(classType)
.add(Restrictions.eq("korisnickoIme", korisnickoIme))
.add(Restrictions.eq("lozinka", lozinka)).uniqueResult();
return korisnik != null ? korisnik : null;
} catch (NullPointerException e) {
return null;
}
}
@Override
public boolean checkIfEmailExists(String email) {
Long rows = (Long) session.createCriteria(classType).add(
Restrictions.eq("email", email)).setProjection(Projections.rowCount()).uniqueResult();
return (rows != 0);
}
@Override
public Korisnik checkIfFaceBookExists(String id) {
return (Korisnik) session.createCriteria(classType)
.add(Restrictions.eq("facebookId", id)).uniqueResult();
}
}
|
package org.kernelab.basis;
/**
* The interface that define the Object which can be accessed as a vector.<br>
* Similar as object in some script languages, objects can be accessed as
* {@code o.id} and also can be accessed {@code o["id"]}.<br>
* Here, object can be accessed as a vector which is indexed by integer.
*
* @author Dilly King
*
*/
public interface VectorAccessible
{
/**
* Return the length of the vector.
*
* @return The length of the vector.
*/
public int vectorAccess();
/**
* Get the value in vector at position of index.
*
* @param index
* The position to get the value.
* @return The value in vector at index.
*/
public Object vectorAccess(int index);
/**
* Set the value in vector at position of index.
*
* @param index
* The position to set the value.
* @param element
* The value to set.
*/
public void vectorAccess(int index, Object element);
}
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int [][] map;
static boolean[][] visit;
static int n;
static int[] dx = {-1, 0, 1, 0};
static int[] dy = {0, 1, 0, -1};
static int result = Integer.MAX_VALUE;
public static void main (String [] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
map = new int [n][n];
visit = new boolean[n][n];
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for (int j = 0; j < n; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
dfs (0, 0);
System.out.println(result);
}
static void dfs (int count, int sum) {
if (count == 3) {
result = Math.min(result, sum);
}
else {
for (int i = 1; i < n - 1; i++) {
for (int j = 1; j < n - 1; j++) {
if (!visit[i][j] && check(i, j)) {
visit[i][j] = true;
int hap = sum(i, j);
dfs (count + 1, sum + hap);
visitClear(i, j);
visit[i][j] = false;
}
}
}
}
}
static boolean check (int x, int y) {
for (int i = 0; i < dx.length; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (visit[nx][ny]) {
return false;
}
}
return true;
}
static void visitClear (int x, int y) {
for (int i = 0; i < dx.length; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
visit[nx][ny] = false;
}
}
static int sum (int x, int y) {
int hap = map[x][y];
for (int i = 0; i < dx.length; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
visit[nx][ny] = true;
hap += map[nx][ny];
}
return hap;
}
}
|
package com.qgbase.biz.huodong.repository;
import com.qgbase.biz.huodong.domain.HdHuodong2user;
import org.springframework.data.repository.CrudRepository;
public interface HdHuodong2userRespository extends CrudRepository<HdHuodong2user,String> {
HdHuodong2user getFirstByHuodongIdAndShopIdAndUserId(String huodongId,String shopId,String userId);
HdHuodong2user getFirstByPayOrder(String orderId);
}
|
package com.walkerwang.algorithm.bigcompany;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class HuaWei02 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String op = in.nextLine();
if (op.length() > 50) {
return;
}
// RA 436512
Map<Character, Integer> map = new HashMap<>();
map.put('L', 1);
map.put('R', 2);
map.put('F', 3);
map.put('B', 4);
map.put('O', 5);
map.put('D', 6);
char[] opChs = op.toCharArray();
int tmp = 0;
for (int i = 0; i < opChs.length; i++) {
char ch = opChs[i];
switch (ch) {
// 向左翻转
case 'L':
tmp = map.get('O');
map.put('O', map.get('R'));
map.put('R', map.get('D'));
map.put('D', map.get('L'));
map.put('L', tmp);
break;
// 向右翻转
case 'R':
tmp = map.get('O');
map.put('O', map.get('L'));
map.put('L', map.get('D'));
map.put('D', map.get('R'));
map.put('R', tmp);
break;
// 向前翻转
case 'F':
tmp = map.get('O');
map.put('O', map.get('B'));
map.put('B', map.get('D'));
map.put('D', map.get('F'));
map.put('F', tmp);
break;
// 向后翻转
case 'B':
tmp = map.get('O');
map.put('O', map.get('F'));
map.put('F', map.get('D'));
map.put('D', map.get('B'));
map.put('B', tmp);
break;
// 逆时针
case 'A':
tmp = map.get('L');
map.put('L', map.get('B'));
map.put('B', map.get('R'));
map.put('R', map.get('F'));
map.put('F', tmp);
break;
// 顺时针
case 'C':
tmp = map.get('L');
map.put('L', map.get('F'));
map.put('F', map.get('R'));
map.put('R', map.get('B'));
map.put('B', tmp);
break;
default:
break;
}
}
printMap(map);
}
}
public static void printMap(Map<Character, Integer> map) {
System.out.print(map.get('L') + "" + map.get('R') + map.get('F') + map.get('B') + map.get('O') + map.get('D'));
}
}
|
/*
* 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 Forms;
import Clases.Cl_Conectar;
import Clases.Cl_Varios;
import java.awt.Desktop;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
/**
*
* @author pc
*/
public class frm_rpt_fechas extends javax.swing.JInternalFrame {
Cl_Conectar con = new Cl_Conectar();
Cl_Varios ven = new Cl_Varios();
public static String rpt = "";
public static String idmat = "";
String fec_ini;
String fec_fin;
/**
* Creates new form frm_rpt_fechas
*/
public frm_rpt_fechas() {
initComponents();
txt_fec_ini.setText(ven.fechaformateada(ven.getFechaActual()));
txt_fec_fin.setText(ven.fechaformateada(ven.getFechaActual()));
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
txt_fec_ini = new javax.swing.JFormattedTextField();
txt_fec_fin = new javax.swing.JFormattedTextField();
setTitle("Imprimir Reportes");
jLabel1.setText("Ingrese Fechas:");
jLabel2.setText("Fecha Inicio:");
jLabel3.setText("Fecha Fin:");
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/cancel.png"))); // NOI18N
jButton1.setText("Cerrar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
try {
txt_fec_ini.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
txt_fec_ini.setHorizontalAlignment(javax.swing.JTextField.CENTER);
txt_fec_ini.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_fec_iniKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
txt_fec_iniKeyTyped(evt);
}
});
txt_fec_fin.setEditable(false);
try {
txt_fec_fin.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
txt_fec_fin.setHorizontalAlignment(javax.swing.JTextField.CENTER);
txt_fec_fin.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_fec_finKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
txt_fec_finKeyTyped(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(txt_fec_ini, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_fec_fin, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE)
.addGap(33, 33, 33))
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_fec_ini, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_fec_fin, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(15, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
this.dispose();
}//GEN-LAST:event_jButton1ActionPerformed
private void txt_fec_iniKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_fec_iniKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
if (txt_fec_ini.getText().length() == 10) {
txt_fec_fin.setEditable(true);
txt_fec_fin.requestFocus();
}
}
}//GEN-LAST:event_txt_fec_iniKeyPressed
private void txt_fec_iniKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_fec_iniKeyTyped
char car = evt.getKeyChar();
if ((car < '0' || car > '9') && car != '-') {
evt.consume();
}
}//GEN-LAST:event_txt_fec_iniKeyTyped
private void txt_fec_finKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_fec_finKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
if (txt_fec_fin.getText().length() == 10) {
fec_ini = ven.fechabase(txt_fec_ini.getText());
fec_fin = ven.fechabase(txt_fec_fin.getText());
if (rpt.equals("kardex")) {
Map<String, Object> parametros = new HashMap<>();
parametros.put("idmat", idmat);
parametros.put("fec_ini", fec_ini);
parametros.put("fec_fin", fec_fin);
ven.ver_reporte("rpt_kardex", parametros);
}
JOptionPane.showMessageDialog(null, "Reporte Generado");
this.dispose();
}
}
}//GEN-LAST:event_txt_fec_finKeyPressed
private void txt_fec_finKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_fec_finKeyTyped
char car = evt.getKeyChar();
if ((car < '0' || car > '9') && car != '-') {
evt.consume();
}
}//GEN-LAST:event_txt_fec_finKeyTyped
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JFormattedTextField txt_fec_fin;
private javax.swing.JFormattedTextField txt_fec_ini;
// End of variables declaration//GEN-END:variables
}
|
package ds.stack;
public class App {
public static void main(String[] args) {
Stack newStack = new Stack(8);
newStack.push(12);
newStack.push(13);
newStack.push(14);
newStack.push(19);
newStack.pop();
for (int i = 0; i < newStack.newArray.length; i++) {
System.out.println(newStack.newArray[i]);
}
System.out.println(newStack.peak());
}
}
|
package com.magit.logic.system.tasks;
import com.magit.logic.exceptions.*;
import com.magit.logic.system.MagitEngine;
import com.magit.logic.system.managers.BranchManager;
import com.magit.logic.system.managers.RepositoryManager;
import com.magit.logic.system.managers.RepositoryXmlParser;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.beans.property.StringProperty;
import javafx.concurrent.Task;
import javafx.scene.layout.AnchorPane;
import javafx.util.Duration;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.function.Supplier;
public class ImportRepositoryTask extends Task<Boolean> {
private int objectsCount = 0;
private int currentObjectCount = 0;
private String filePath = null;
private InputStream xml;
private BranchManager branchManager;
private RepositoryManager repositoryManager;
private boolean forceCreation = false;
private RepositoryXmlParser xmlParser;
private MagitEngine engine;
private AnchorPane pane;
private StringProperty repositoryNameProperty;
private StringProperty repositoryPathProperty;
private Runnable forceCreationRunnable;
private Runnable doAfter;
public ImportRepositoryTask(String filePath, MagitEngine engine, AnchorPane pane, StringProperty repositoryNameProperty,StringProperty repositoryPathProperty,Runnable forceCreationRunnable,Runnable doAfter, boolean forceCreation) {
this.filePath = filePath;
this.branchManager = engine.getmBranchManager();
this.forceCreation = forceCreation;
this.repositoryManager = engine.getmRepositoryManager();
this.engine = engine;
this.pane = pane;
this.repositoryNameProperty = repositoryNameProperty;
this.repositoryPathProperty = repositoryPathProperty;
this.forceCreationRunnable = forceCreationRunnable;
this.doAfter = doAfter;
}
public ImportRepositoryTask(InputStream xml, MagitEngine engine, StringProperty repositoryNameProperty,StringProperty repositoryPathProperty,Runnable forceCreationRunnable,Runnable doAfter, boolean forceCreation) {
this.xml = xml;
this.branchManager = engine.getmBranchManager();
this.forceCreation = forceCreation;
this.repositoryManager = engine.getmRepositoryManager();
this.engine = engine;
this.repositoryNameProperty = repositoryNameProperty;
this.repositoryPathProperty = repositoryPathProperty;
this.forceCreationRunnable = forceCreationRunnable;
this.doAfter = doAfter;
}
private boolean importRepositoryXML() throws RepositoryAlreadyExistsException {
if (!initializeXmlParser())
return false;
if (!commenceXmlValidityChecks())
return false;
if (!handleFoldersChecks())
return false;
if (importObject("Importing blobs...", this::importBlobs))
return false;
if (importObject("Importing folders...", this::importFolders))
return false;
xmlParser.buildTree();
if (importObject("Importing commits...", this::importCommits))
return false;
try {
updateMessage("Initializing repository...");
xmlParser.initializeRepository();
xmlParser.setRemoteReference();
importObject("Importing branches...", this::importBranches);
updateMessage("Creating repository...");
repositoryManager.setActiveRepository(xmlParser.createRepository());
} catch(IOException | IllegalPathException ex) {
updateMessage(ex.getMessage());
return false;
}
try {
updateMessage("Unzipping files...");
engine.loadHeadBranchCommitFiles();
updateProgress(currentObjectCount + 2, objectsCount);
} catch (JAXBException | RepositoryAlreadyExistsException | IllegalPathException | XmlFileException | PreviousCommitsLimitExceededException | ParseException | IOException e) {
e.printStackTrace();
}
updateMessage("Repository created successfully!");
Platform.runLater(() -> {
repositoryNameProperty.setValue("");
repositoryNameProperty.setValue(engine.getRepositoryName());
repositoryPathProperty.setValue(engine.guiGetRepositoryPath());
});
return true;
}
@Override
protected Boolean call() {
boolean success = false;
try {
success = importRepositoryXML();
} catch (RepositoryAlreadyExistsException e) {
Platform.runLater(() -> {
forceCreationRunnable.run();
});
}
deleteProgressBar();
return success;
}
private void deleteProgressBar(){
Platform.runLater(() -> {
KeyFrame keyFrame = new KeyFrame(Duration.seconds(5), event -> {
if(pane !=null)
pane.setVisible(false);
doAfter.run();
});
Timeline timer = new Timeline(keyFrame);
timer.playFromStart();
});
}
private boolean initializeXmlParser(){
updateMessage("Fetching file...");
updateProgress(0, 1);
try {
xmlParser = new RepositoryXmlParser(filePath);
} catch (Exception ex) {
updateMessage(ex.getMessage());
return false;
}
updateProgress(1, 1);
return true;
}
private boolean commenceXmlValidityChecks() {
updateMessage("Commencing validity checks...");
int validityCheckCount = 7;
updateProgress(0, validityCheckCount);
try {
xmlParser.checkXmlValidity();
} catch (XmlFileException ex) {
updateMessage(ex.getMessage());
return false;
}
updateProgress(validityCheckCount, validityCheckCount);
return true;
}
private boolean handleFoldersChecks() throws RepositoryAlreadyExistsException {
updateMessage("Checking folder validity...");
updateProgress(0, 1);
try {
xmlParser.handleExistingRepositories(forceCreation);
} catch (IOException ex) {
updateMessage(ex.getMessage());
return false;
}
updateProgress(1, 1);
objectsCount = xmlParser.getObjectsCount();
return true;
}
private boolean importBlobs() {
try {
currentObjectCount += xmlParser.importBlobs();
} catch (ParseException e) {
updateMessage(e.getMessage());
return false;
}
return true;
}
private boolean importFolders() {
try {
currentObjectCount += xmlParser.importFolders();
} catch (ParseException e) {
updateMessage(e.getMessage());
return false;
}
return true;
}
private boolean importCommits() {
try {
currentObjectCount += xmlParser.createCommits();
} catch (ParseException | PreviousCommitsLimitExceededException | IOException e) {
updateMessage(e.getMessage());
return false;
}
return true;
}
private boolean importBranches() {
currentObjectCount += xmlParser.createBranches(branchManager);
return true;
}
private boolean importObject(String message, Supplier<Boolean> xmlFunc) {
updateMessage(message);
boolean output = xmlFunc.get();
updateProgress(currentObjectCount, objectsCount);
return !output;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.tftp;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.net.tftp.TFTPServer.ServerMode;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Basic tests to ensure that the TFTP Server is honoring its read/write mode, and preventing files from being read or written from outside of the assigned
* roots.
*/
public class TFTPServerPathTest {
private static final int SERVER_PORT = 6901;
String filePrefix = "tftp-";
File serverDirectory = FileUtils.getTempDirectory();
private File file;
private File out;
@AfterEach
public void afterEach() {
deleteFixture(file);
deleteFixture(out);
}
@BeforeEach
public void beforeEach() throws IOException {
// Fixture 1
file = new File(serverDirectory, filePrefix + "source.txt");
deleteFixture(file);
file.createNewFile();
// Fixture 2
out = new File(serverDirectory, filePrefix + "out");
deleteFixture(out);
}
private void deleteFixture(final File file) {
if (file != null && !file.delete()) {
file.deleteOnExit();
}
}
@Test
public void testReadOnly() throws IOException {
// Start a read-only server
try (TFTPServer tftpS = new TFTPServer(serverDirectory, serverDirectory, SERVER_PORT, ServerMode.GET_ONLY, null, null)) {
// Create our TFTP instance to handle the file transfer.
try (TFTPClient tftp = new TFTPClient()) {
tftp.open();
tftp.setSoTimeout(2000);
try {
// check old failed runs
assertFalse(out.exists(), () -> "Couldn't clear output location, deleted=");
try (final FileOutputStream output = new FileOutputStream(out)) {
tftp.receiveFile(file.getName(), TFTP.BINARY_MODE, output, "localhost", SERVER_PORT);
}
assertTrue(out.exists(), "file not created");
out.delete();
assertThrows(IOException.class, () -> {
try (final FileInputStream fis = new FileInputStream(file)) {
tftp.sendFile(out.getName(), TFTP.BINARY_MODE, fis, "localhost", SERVER_PORT);
fail("Server allowed write");
}
});
} finally {
deleteFixture(file);
deleteFixture(out);
}
}
}
}
@Test
public void testWriteOnly() throws IOException {
// Start a write-only server
try (TFTPServer tftpS = new TFTPServer(serverDirectory, serverDirectory, SERVER_PORT, ServerMode.PUT_ONLY, null, null)) {
// Create our TFTP instance to handle the file transfer.
try (TFTPClient tftp = new TFTPClient()) {
tftp.open();
tftp.setSoTimeout(2000);
try {
// check old failed runs
assertFalse(out.exists(), () -> "Couldn't clear output location, deleted=");
assertThrows(IOException.class, () -> {
try (final FileOutputStream output = new FileOutputStream(out)) {
tftp.receiveFile(file.getName(), TFTP.BINARY_MODE, output, "localhost", SERVER_PORT);
fail("Server allowed read");
}
});
out.delete();
try (final FileInputStream fis = new FileInputStream(file)) {
tftp.sendFile(out.getName(), TFTP.BINARY_MODE, fis, "localhost", SERVER_PORT);
}
assertTrue(out.exists(), "file not created");
} finally {
// cleanup
deleteFixture(file);
deleteFixture(out);
}
}
}
}
@Test
public void testWriteOutsideHome() throws IOException {
// Start a server
try (TFTPServer tftpS = new TFTPServer(serverDirectory, serverDirectory, SERVER_PORT, ServerMode.GET_AND_PUT, null, null)) {
// Create our TFTP instance to handle the file transfer.
try (TFTPClient tftp = new TFTPClient()) {
tftp.open();
try {
assertFalse(new File(serverDirectory, "../foo").exists(), "test construction error");
assertThrows(IOException.class, () -> {
try (final FileInputStream fis = new FileInputStream(file)) {
tftp.sendFile("../foo", TFTP.BINARY_MODE, fis, "localhost", SERVER_PORT);
fail("Server allowed write!");
}
});
assertFalse(new File(serverDirectory, "../foo").exists(), "file created when it should not have been");
} finally {
// cleanup
deleteFixture(file);
}
}
}
}
}
|
package com.smxknife.mybatis.springboot.dao;
import com.smxknife.mybatis.springboot.model.TBString;
import com.smxknife.mybatis.springboot.model.TBStringExample;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface TBStringMapper {
long countByExample(TBStringExample example);
int deleteByExample(TBStringExample example);
int deleteByPrimaryKey(Long id);
int insert(TBString record);
int insertSelective(TBString record);
List<TBString> selectByExample(TBStringExample example);
TBString selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") TBString record, @Param("example") TBStringExample example);
int updateByExample(@Param("record") TBString record, @Param("example") TBStringExample example);
int updateByPrimaryKeySelective(TBString record);
int updateByPrimaryKey(TBString record);
}
|
package exercise2;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AnagramTest {
@Test
public void test1() {
assertEquals(false, StringUtility.areAnagrams("aaa", "a"));
}
@Test
public void test2() {
assertEquals(false, StringUtility.areAnagrams("aaa", "aa"));
}
@Test
public void test3() {
assertEquals(true, StringUtility.areAnagrams("aaa", "aaa"));
}
@Test
public void test4() {
assertEquals(false, StringUtility.areAnagrams("aaaa", "aaa"));
}
@Test
public void test5() {
assertEquals(false, StringUtility.areAnagrams(" Aa b ", "ab"));
}
@Test
public void test6() {
assertEquals(false, StringUtility.areAnagrams(" Aa b ", "ab"));
}
@Test
public void test7() {
assertEquals(false, StringUtility.areAnagrams(" Aa b ", "Ab A"));
}
@Test
public void test8() {
assertEquals(false, StringUtility.areAnagrams(" I am a blackstar", "ras blackt i am a"));
}
@Test
public void test9() {
assertEquals(true, StringUtility.areAnagrams(" I am a blackstar", "ras blackt I maa"));
}
@Test
public void test10() {
assertEquals(true, StringUtility.areAnagrams(" I am a blackstar", "b l s ara kcItama"));
}
}
|
package com.tyss.capgemini.loanproject.exceptions;
@SuppressWarnings("serial")
public class LoanExcessException extends RuntimeException {
public LoanExcessException(String msg) {
super(msg);
}
}
|
package com.research.configurer;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 配置静态资源访问路径
*
* @author shc
* @date 2018-06-18
**/
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
/**
* 允许通过网络访问静态资源
* 如:http://localhost:8090/images/IMG41.jpg
* <p>
* /images/** 指匹配的url
* classpath:/images/ 定位的资源路径位置
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("classpath:/images/");
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(10000L);
}
}
|
package com.qm.spring.boot.blog.personblog.repository;
import com.qm.spring.boot.blog.personblog.domain.Catalog;
import com.qm.spring.boot.blog.personblog.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* 分类管理
*/
public interface CatalogRepository extends JpaRepository<Catalog, Long> {
/**
* 根据用户查询
* @param user
* @return
*/
List<Catalog> findByUser(User user);
/**
* 根据用户及分类名称查询
* @param user
* @param name
* @return
*/
List<Catalog> findByUserAndName(User user, String name);
}
|
package org.ubiquity;
import java.util.List;
/**
* This interface defines a Copier, used to copy an object into another,
* or map an object into another one of another class.
*
* @author François LAROCHE
*
* @param <T> the source object class
* @param <U> the destination object class
*/
public interface Copier<T, U> {
/**
* Copies the values of the object given in a new object of the destination class.
*
* @param element the object to copy into a new destination object
* @return a new object of the destination, in which have been copied the properties
*/
U map(T element);
/**
* Copy a list of elements of the source class into a list of new elements of the destination class
*
* @param elements the source objects
* @return objects of the destination class, containing the objects
*/
List<U> map(List<T> elements);
/**
* Copy an object properties into another.
*
* @param source the source object, from which to read the properties
* @param destination the destination object, in which to write the properties
*/
void copy(T source, U destination);
/**
* Map an array of T elements to an array of U elements.
* If the specified array of Us doesn't have the same size as the array of T
* or is null, then a new array of U will be created.
* Else, the original array will be returned.
*
* @param src the array containing the Ts to copy
* @param target the array containing the destination Us
* @return an array, that can be the target argument containing all the merged elements
*/
U[] map (T[] src, U[] target);
}
|
package com.proofconcept.uploadfile.service;
import android.app.IntentService;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;
import android.util.Log;
import com.proofconcept.uploadfile.db.UploadFileOpenHelper;
/**
* @author everardo.salazar on 4/18/17.
*/
public class FileStatusService extends IntentService {
public static final String FILE_URL_EXTRA = "com.proofconcept.uploadfile.service.fileUrlExtra";
public FileStatusService() {
super("FileStatusService");
setIntentRedelivery(true);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.i(FileStatusService.class.getName(), "onHandleIntent");
UploadFileOpenHelper dbHelper = new UploadFileOpenHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(UploadFileOpenHelper.FileUploadsContract.UploadFileEntry.COLUMN_URL, intent.getStringExtra(FILE_URL_EXTRA));
values.put(UploadFileOpenHelper.FileUploadsContract.UploadFileEntry.COLUMN_STATUS, "notStarted");
long newRowId = db.insert(UploadFileOpenHelper.FileUploadsContract.UploadFileEntry.TABLE_NAME, null, values);
dbHelper.close();
Log.i(FileStatusService.class.getName(), "new row inserted " + newRowId);
}
}
|
package cn.chinaunicom.monitor.alarm;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.jauker.widget.BadgeView;
import com.zaaach.toprightmenu.MenuItem;
import com.zaaach.toprightmenu.TopRightMenu;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.chinaunicom.monitor.ChinaUnicomApplication;
import cn.chinaunicom.monitor.MainActivity;
import cn.chinaunicom.monitor.R;
import cn.chinaunicom.monitor.beans.AlarmCategoryEntity;
import cn.chinaunicom.monitor.beans.CenterEntity;
import cn.chinaunicom.monitor.beans.Connection;
import cn.chinaunicom.monitor.callback.TopRightPointCallBack;
import cn.chinaunicom.monitor.sqlite.AlarmDatabaseHelper;
import cn.chinaunicom.monitor.utils.Config;
import cn.chinaunicom.monitor.utils.Utils;
import cn.chinaunicom.monitor.viewholders.AlarmCategoryViewHolder;
import me.leolin.shortcutbadger.ShortcutBadger;
public class AlarmFragment extends Fragment implements TopRightPointCallBack {
private AlarmCategoryEntity curCategoryEntity = null;
private AlarmDatabaseHelper dbHelper;
private SQLiteDatabase db;
private TopRightMenu menu;
private List<MenuItem> menuItems = new ArrayList<>();
//key:centerName, value:centerId
private Map<String, String> uncheckCenterMap = new HashMap<>();
private BadgeView imgRightBtnBadgeView;
public static AlarmFragment instance = null;
@Bind(R.id.txtViewTitle)
public TextView title;
@Bind(R.id.imgBtnRight)
ImageButton imgBtnRight;
@Bind(R.id.alarmCategoryList)
ListView alarmCategoryList;
@OnClick(R.id.imgBtnRight)
void popMenu() {
Cursor uncheckCenterCursor = db.query("CENTER", Config.CENTER_COLUMN,
null, null, null, null, null);
while (uncheckCenterCursor.moveToNext()) {
if (uncheckCenterCursor.getInt(3) == 1) //有未读消息
uncheckCenterMap.put(uncheckCenterCursor.getString(1), uncheckCenterCursor.getString(2));
}
initTopRigtMenu();
initMenuItem(ChinaUnicomApplication.alarmCenterList, uncheckCenterMap);
menu.showAsDropDown(imgBtnRight, 0, 0);
uncheckCenterCursor.close();
}
public AlarmFragment() {
// Required empty public constructor
}
public static AlarmFragment getInstance() {
instance = new AlarmFragment();
return instance;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_alarm, container, false);
ButterKnife.bind(this, view);
//这里初始化的顺序不能变更!
initDB();
initTopRigtMenu();
initView();
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
//ChinaUnicomApplication.alarmCategoryEntities.clear();
instance = null;
}
@Override
public void onDestroy() {
super.onDestroy();
//关闭数据库资源
//db.close();
}
private void initDB() {
dbHelper = new AlarmDatabaseHelper(getContext(), Config.DB_NAME, null, Config.DB_VERSION);
db = dbHelper.getWritableDatabase();
}
private void initView() {
ShortcutBadger.applyCount(getContext(), 0); //for 1.1.4+
imgRightBtnBadgeView = new BadgeView(getActivity());
imgRightBtnBadgeView.setTargetView(imgBtnRight);
imgRightBtnBadgeView.getBackground().setAlpha(0);
imgRightBtnBadgeView.setTextColor(Color.rgb(205, 175, 149));
imgRightBtnBadgeView.setBadgeGravity(Gravity.TOP | Gravity.RIGHT );
Cursor uncheckCenterCursor = db.query("CENTER", Config.CENTER_COLUMN,
null, null, null, null, null);
while (uncheckCenterCursor.moveToNext()) {
if (uncheckCenterCursor.getInt(3) == 1) {
uncheckCenterMap.put(uncheckCenterCursor.getString(1), uncheckCenterCursor.getString(2));
imgRightBtnBadgeView.setText("●");
}
}
uncheckCenterCursor.close();
//首次显示将当前选择的中心设为List中的第一个
if (null == ChinaUnicomApplication.alarmCurCenter &&
!Utils.isListEmpty(ChinaUnicomApplication.alarmCenterList)) {
String itemId = ChinaUnicomApplication.alarmCenterList.get(0).itemId;
String title = ChinaUnicomApplication.alarmCenterList.get(0).title;
ChinaUnicomApplication.alarmCurCenter = new CenterEntity(itemId, title);
}
//如果用户第一次登录,在选择告警页面时,此时如果中心的列表还没下载完,告警分类的列表就应该不能显示
if (null != ChinaUnicomApplication.alarmCurCenter &&
!Utils.isStringEmpty(ChinaUnicomApplication.alarmCurCenter.itemId)) {
initAlarmCategoryList(ChinaUnicomApplication.alarmCurCenter.itemId);
getAlarmCategoryEntities(ChinaUnicomApplication.alarmCurCenter.itemId);
}
initTitleBar();
initListView();
}
private void initTopRigtMenu() {
updateAlarmCenterList();
menu = new TopRightMenu(getActivity());
menu.setHeight(Config.POP_UP_DIALOG_HEIGHT)
.setWidth(Config.POP_UP_DIALOG_WIDTH)
.showIcon(true)
.dimBackground(true)
.needAnimationStyle(true)
.setHeight(Config.TOP_RIGHT_MENU_HEIGHT)
.setOnMenuItemClickListener(
new TopRightMenu.OnMenuItemClickListener() {
@Override
public void onMenuItemClick(int position) {
actionWhenClickMenuItem(position);
}
});
}
//点击菜单后重置Title,重置currentCenter变量
private void actionWhenClickMenuItem(int position) {
//这里的逻辑都在OnClick监听里面,如果TopRight为空,也就不可能点击,所以不用判空
if (null != ChinaUnicomApplication.alarmCurCenter) {
ChinaUnicomApplication.alarmCurCenter.title = ChinaUnicomApplication.alarmCenterList.get(position).title;
ChinaUnicomApplication.alarmCurCenter.itemId = ChinaUnicomApplication.alarmCenterList.get(position).itemId;
} else {
ChinaUnicomApplication.alarmCurCenter =
new CenterEntity(ChinaUnicomApplication.alarmCenterList.get(position).itemId,
ChinaUnicomApplication.alarmCenterList.get(position).title);
}
initAlarmCategoryList(ChinaUnicomApplication.alarmCurCenter.itemId);
getAlarmCategoryEntities(ChinaUnicomApplication.alarmCurCenter.itemId);
Utils.showSuccessToast(getContext(), "已切换到 " + ChinaUnicomApplication.alarmCurCenter.title);
updateTitle();
}
//删除弹出菜单对话框里面中心前的红点与否
private void removeCenterRedPoint() {
Cursor centerCursor = db.query("ALARM_CATEGORY", Config.ALARM_CATEGORY_COLUMN,
"center_id=?", new String[]{ChinaUnicomApplication.alarmCurCenter.itemId}, null, null, null);
if (!centerCursor.moveToNext()) {
db.delete("CENTER", "center_name=? and center_id=?",
new String[]{ChinaUnicomApplication.alarmCurCenter.title,
ChinaUnicomApplication.alarmCurCenter.itemId});
uncheckCenterMap.remove(ChinaUnicomApplication.alarmCurCenter.title);
updateAlarmCenterList();
if (!Utils.isListEmpty(ChinaUnicomApplication.alarmCenterList)) {
actionWhenClickMenuItem(0);
} else {
ChinaUnicomApplication.alarmCurCenter = null;
ChinaUnicomApplication.alarmCategoryEntities.clear();
ChinaUnicomApplication.alarmCategoryAdapter.notifyDataSetChanged();
updateTitle();
}
updateTopRightPoint();
} else {
//把游标移动到第一条记录之前
centerCursor.moveToPrevious();
while (centerCursor.moveToNext()) {
//如果该中心还有未读消息,就保留红点
if (centerCursor.getInt(2) != 0)
break;
if (centerCursor.isLast()) {
ContentValues values = new ContentValues();
values.put("is_uncheck", 0);
db.update("CENTER", values, "center_name=? and center_id=?",
new String[]{ChinaUnicomApplication.alarmCurCenter.title,
ChinaUnicomApplication.alarmCurCenter.itemId});
uncheckCenterMap.remove(ChinaUnicomApplication.alarmCurCenter.title);
updateTopRightPoint();
}
}
}
centerCursor.close();
}
private void updateTopRightPoint() {
if (!uncheckCenterMap.isEmpty()) {
imgRightBtnBadgeView.setText("●");
} else {
imgRightBtnBadgeView.setBadgeCount(0);
}
}
//初始化menu的item
private void initMenuItem(List<CenterEntity> data, Map<String, String> uncheckCenterMap) {
menuItems.clear();
//如果未查看的中心Map中有该中心,则显示红点,否则不显示
for (int i = 0; i < data.size(); i++) {
if (uncheckCenterMap.containsKey(data.get(i).title)) {
menuItems.add(new MenuItem(R.mipmap.ic_red_point, data.get(i).title));
} else {
menuItems.add(new MenuItem(R.mipmap.ic_blank, data.get(i).title));
}
}
menu.addMenuList(menuItems);
}
//这里进行全局告警类别列表更新的目的在于,如果首次打开App且没有更新的告警来,要读取以前是否有未读的消息进行显示
private void getAlarmCategoryEntities(String currentCenterId) {
Cursor cursor = db.query("ALARM_CATEGORY", Config.ALARM_CATEGORY_COLUMN, "center_id=?",
new String[]{currentCenterId}, null, null,null);
//每次加载新的UI要将全局保存的告警类别信息进行清空,否则会重复显示
ChinaUnicomApplication.alarmCategoryEntities.clear();
while (cursor.moveToNext()) {
AlarmCategoryEntity e = new AlarmCategoryEntity();
//括号里的序号对应SqliteDataBaseHelper中表的列
e.title = cursor.getString(1);
e.value = cursor.getInt(2);
e.mesContent = cursor.getString(3);
e.sendTime = cursor.getLong(4);
e.column = cursor.getString(5);
ChinaUnicomApplication.alarmCategoryEntities.add(e);
}
cursor.close();
ChinaUnicomApplication.alarmCategoryAdapter.notifyDataSetChanged();
}
private void updateAlarmCenterList() {
Cursor centerCursor = db.query("CENTER", Config.CENTER_COLUMN, null, null, null, null, null);
ChinaUnicomApplication.alarmCenterList.clear();
while (centerCursor.moveToNext()) {
CenterEntity e = new CenterEntity();
e.title = centerCursor.getString(1);
e.itemId = centerCursor.getString(2);
e.isUncheck = centerCursor.getInt(3);
ChinaUnicomApplication.alarmCenterList.add(e);
}
}
private void initListView() {
alarmCategoryList.setAdapter(ChinaUnicomApplication.alarmCategoryAdapter);
alarmCategoryList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
curCategoryEntity = ChinaUnicomApplication.alarmCategoryEntities.get(position);
new AlertDialog
.Builder(getActivity())
.setTitle("提示")
.setMessage("是否要删除关于" + curCategoryEntity.title + "的告警记录?")
.setNegativeButton("取消", null)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ChinaUnicomApplication.alarmCategoryEntities.remove(position);
db.delete("ALARM_CATEGORY", "category=? and center_id=?",
new String[]{curCategoryEntity.title, ChinaUnicomApplication.alarmCurCenter.itemId});
db.delete("ALARM", "category=? and center_id=?",
new String[]{curCategoryEntity.title, ChinaUnicomApplication.alarmCurCenter.itemId});
//更新Tab告警的红点
MainActivity.instance.updateAlarmBadge();
//移除中心列表里相应中心的红点提示
removeCenterRedPoint();
ChinaUnicomApplication.alarmCategoryAdapter.notifyDataSetChanged();
}
})
.show();
return true;
}
});
alarmCategoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
curCategoryEntity = ChinaUnicomApplication.alarmCategoryEntities.get(position);
Intent intent = new Intent(getContext(), AlarmDetailActivity.class);
intent.putExtra("ALARM_CATEGORY", curCategoryEntity.column);
intent.putExtra("ALARM_CATEGORY_TITLE", curCategoryEntity.title);
intent.putExtra("CENTER_NAME", ChinaUnicomApplication.alarmCurCenter.title);
intent.putExtra("CENTER_ID", ChinaUnicomApplication.alarmCurCenter.itemId);
((AlarmCategoryViewHolder)view.getTag()).badgeView.setBadgeCount(0);
//这里是处理Badge的逻辑,如果带红点的item已读,则将UnCheck中的该项清除
ContentValues values = new ContentValues();
values.put("uncheck_num", 0);
curCategoryEntity.value = 0;
ChinaUnicomApplication.badgeMap.put(curCategoryEntity.title, 0);
ShortcutBadger.applyCount(ChinaUnicomApplication.getApplication(), 0);
db.update("ALARM_CATEGORY", values,"category=? and center_id=?",
new String[]{curCategoryEntity.title, ChinaUnicomApplication.alarmCurCenter.itemId});
//更新Tab告警的红点
MainActivity.instance.updateAlarmBadge();
//移除中心列表里相应中心的红点提示
removeCenterRedPoint();
startActivity(intent);
}
});
}
private void initAlarmCategoryList(String currentCenterId) {
//1.将未读的categroy存入map,为badge做准备
Cursor cursor = db.query("ALARM_CATEGORY",new String[]{"category", "uncheck_num"},
"center_id=?", new String[]{currentCenterId}, null, null, null);
ChinaUnicomApplication.badgeMap.clear();
while (cursor.moveToNext()) {
ChinaUnicomApplication.badgeMap.put(cursor.getString(0), cursor.getInt(1));
}
cursor.close();
}
private void initTitleBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
imgBtnRight.setImageDrawable(getResources().getDrawable(R.mipmap.ic_menu, null));
} else {
imgBtnRight.setImageDrawable(getResources().getDrawable(R.mipmap.ic_menu));
}
updateTitle();
}
private void updateTitle() {
if (!Utils.isListEmpty(ChinaUnicomApplication.alarmCenterList))
title.setText(ChinaUnicomApplication.alarmCurCenter.title + "-告警");
else
title.setText("暂无任何告警");
}
@Override
public void showPoint() {
Cursor uncheckCenterCursor = db.query("CENTER", Config.CENTER_COLUMN,
null, null, null, null, null);
while (uncheckCenterCursor.moveToNext()) {
if (uncheckCenterCursor.getInt(3) == 1) {
uncheckCenterMap.put(uncheckCenterCursor.getString(1),
uncheckCenterCursor.getString(2));
}
}
uncheckCenterCursor.close();
imgRightBtnBadgeView.setText("●");
}
//告警分类列表的ViewHolder
class ViewHolder {
@Bind(R.id.alarmLogo)
ImageView alarmLogo;
@Bind(R.id.alarmCategoryTitle)
TextView alarmCategoryTitle;
@Bind(R.id.latestAlarm)
TextView latestAlarm;
@Bind(R.id.alarmSendTime)
TextView alarmSendTime;
BadgeView badgeView;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
badgeView = new BadgeView(getActivity());
badgeView.setTargetView(alarmLogo);
badgeView.setBadgeCount(0);
}
}
}
|
/*
* (c) 2014 Samuel Kilada.
* All rights reserved.
*/
package imagestamper;
import java.io.File;
/**
*
* @author Samuel Kilada
*/
public class ImageFilter extends javax.swing.filechooser.FileFilter {
@Override
public boolean accept(File file) {
// Allow only images
return file.isDirectory()
|| file.getAbsolutePath().toLowerCase().endsWith(".bmp")
|| file.getAbsolutePath().toLowerCase().endsWith(".jpg")
|| file.getAbsolutePath().toLowerCase().endsWith(".png");
}
@Override
public String getDescription() {
return "Image Files(*.BMP;*.JPG;*.PNG)";
}
}
|
package com.spbsu.flamestream.example.benchmark;
import com.spbsu.flamestream.core.Graph;
import com.spbsu.flamestream.runtime.FlameRuntime;
/**
* User: Artem
* Date: 28.12.2017
*/
public class FlameGraphDeployer implements GraphDeployer {
private final FlameRuntime runtime;
private final Graph graph;
private final FlameRuntime.FrontType<?, ?> frontType;
private final FlameRuntime.RearType<?, ?> rearType;
public FlameGraphDeployer(FlameRuntime runtime,
Graph graph,
FlameRuntime.FrontType<?, ?> frontType,
FlameRuntime.RearType<?, ?> rearType) {
this.runtime = runtime;
this.graph = graph;
this.frontType = frontType;
this.rearType = rearType;
}
@Override
public void deploy() {
final FlameRuntime.Flame flame = runtime.run(graph);
flame.attachRear("FlameSocketGraphDeployerRear", rearType);
flame.attachFront("FlameSocketGraphDeployerFront", frontType);
}
@Override
public void close() {
try {
runtime.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
package com.lavajato.models;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class VeiculoModelTest {
@Test
void getPlaca() {
}
@Test
void setPlaca() {
}
@Test
void getModelo() {
}
@Test
void setModelo() {
}
@Test
void getMarca() {
}
@Test
void setMarca() {
}
@Test
void getAno() {
}
@Test
void setAno() {
}
@Test
void getDonoVeiculo() {
}
@Test
void setDonoVeiculo() {
}
@Test
void setId() {
}
@Test
void getId() {
}
}
|
package Modulos;
import HelperCore.inicializaDriver;
import PageObject.Menu;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.net.MalformedURLException;
public class SeekBar extends inicializaDriver
{
@Before
public void iniciaTeste() throws MalformedURLException {
inicializa();
}
@Test
public void seekBar() throws InterruptedException {
Menu.selecionaMenu("Formulário");
//TODO -FAZER!!!
}
@After
public void finalizaTeste() throws MalformedURLException {
driver.quit();
}
}
|
package com.zzxhdzj.ctsync.api;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zzxhdzj.ctsync.Callback;
import com.zzxhdzj.ctsync.CtSync;
import com.zzxhdzj.ctsync.api.base.ApiGateway;
import com.zzxhdzj.ctsync.api.base.ApiResponse;
import com.zzxhdzj.ctsync.api.base.ApiResponseCallbacks;
import com.zzxhdzj.ctsync.api.base.JsonApiResponse;
import com.zzxhdzj.ctsync.entity.dto.UserDto;
import org.apache.http.client.methods.HttpGet;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: yangning.roy
* Date: 11/12/13
* Time: 2:30 PM
* To change this template use File | Settings | File Templates.
*/
public class FindFriendsGateway {
private final ApiGateway apiGateway;
public ApiResponse failureResponse;
public Boolean onCompleteWasCalled;
private CtSync mCtSync;
public FindFriendsGateway(CtSync ctSync, ApiGateway apiGateway) {
this.mCtSync = ctSync;
this.apiGateway = apiGateway;
}
public void findFriends(String token, Callback callback) {
apiGateway.makeRequest(new FindFriendsRequest(HttpGet.METHOD_NAME, token),
new AuthenticationApiResponseCallback(callback));
}
class AuthenticationApiResponseCallback implements ApiResponseCallbacks<JsonApiResponse> {
private Callback callback;
public AuthenticationApiResponseCallback(Callback responseCallback) {
this.callback = responseCallback;
}
@Override
public void onSuccess(JsonApiResponse response) throws IOException {
try {
Gson gson = new Gson();
Type collectionType = new TypeToken<ArrayList<UserDto>>(){}.getType();
ArrayList<UserDto> userDtoList = gson.fromJson(response.getResponseJsonArray().toString(), collectionType);
mCtSync.userDtos = userDtoList;
callback.onSuccess();
} catch (Exception e) {
e.printStackTrace();
onFailure(response);
}
callback.onSuccess();
}
@Override
public void onFailure(ApiResponse response) {
failureResponse = response;
callback.onFailure();
}
@Override
public void onComplete() {
onCompleteWasCalled = true;
}
}
}
|
package me.lehrner.spotifystreamer;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class TopTracksFragment extends Fragment {
private static final String KEY_TRACK_LIST = "me.lehrner.spotifystreamer.tracks";
private static final String KEY_LIST_VIEW = "me.lehrner.spotifystreamer.track.listview";
private final static String KEY_ARTIST_ID = "me.lehrner.spotifystreamer.track.artistId";
private final static String KEY_ARTIST_NAME = "me.lehrner.spotifystreamer.topTracks.ARTIST_NAME";
public final static String ARRAY_ID = "me.lehrner.spotifystreamer.ARRAY_ID";
public final static String ARTIST_ID = "me.lehrner.spotifystreamer.ARTIST_ID";
public final static String ARTIST_NAME = "me.lehrner.spotifystreamer.ARTIST_NAME";
public final static String TRACK_ARRAY = "me.lehrner.spotifystreamer.TRACK_ARRAY";
private ListView mListView;
private ArrayList<SpotifyTrackSearchResult> mTracks;
private View mLoadingView, mRootView;
private int mShortAnimationDuration;
private Toast toast;
private TrackAdapter mTrackAdapter;
private Activity mActivity;
private String mArtistId, mQuery, mArtistName;
private AdapterView.OnItemClickListener mClickListener;
private OnTopTracksFragmentControlListener mTopTracksFragmentControlListener;
public TopTracksFragment() {
}
public interface OnTopTracksFragmentControlListener {
void setNotificationIntentTracks(@SuppressWarnings("SameParameterValue") boolean b);
}
public String getArtistName() {
return mArtistName;
}
public ArrayList<SpotifyTrackSearchResult> getTracks() {
return mTracks;
}
public String getArtistId() {
return mArtistId;
}
public String getQuery() {
return mQuery;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_top_tracks, container, false);
return mRootView;
}
@SuppressLint("ShowToast")
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mLoadingView = mRootView.findViewById(R.id.loading_spinner);
// Retrieve and cache the system's default "short" animation time.
mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);
Context context = getActivity();
toast = Toast.makeText(context, " ", Toast.LENGTH_SHORT);
mTrackAdapter = new TrackAdapter(
context,
new ArrayList<SpotifyTrackSearchResult>());
mListView = (ListView) mRootView.findViewById(R.id.listview_track_search_result);
mListView.setAdapter(mTrackAdapter);
if (savedInstanceState != null) {
Logfn.d("is a saved instance");
mTracks = savedInstanceState.getParcelableArrayList(KEY_TRACK_LIST);
mListView.onRestoreInstanceState(savedInstanceState.getParcelable(KEY_LIST_VIEW));
mArtistId = savedInstanceState.getString(KEY_ARTIST_ID);
mArtistName = savedInstanceState.getString(KEY_ARTIST_NAME);
mQuery = savedInstanceState.getString(MainActivity.KEY_QUERY);
addAllAdapter(mTracks);
fadeListViewIn();
}
else {
Logfn.d("is not a saved instance");
Intent intent = mActivity.getIntent();
boolean twoPane = getResources().getBoolean(R.bool.two_pane);
if ((intent != null) && (intent.getExtras() != null) && !twoPane) {
handleIntent(intent);
}
}
mListView.setOnItemClickListener(mClickListener);
}
public void updateTopTracks(String artistId, String artistName, Activity activity) {
showLoadingView();
mArtistId = artistId;
mArtistName = artistName;
mTrackAdapter.clear();
mTrackAdapter = new TrackAdapter(mActivity, new ArrayList<SpotifyTrackSearchResult>());
mListView.setAdapter(mTrackAdapter);
SpotifyTrackSearch spotifySearch = new SpotifyTrackSearch();
spotifySearch.updateListView(mArtistId, activity, this);
setSubTitle(mArtistName);
}
public void setSubTitle(String subtitle) {
try {
//noinspection ConstantConditions
((AppCompatActivity) mActivity).getSupportActionBar().setSubtitle(subtitle);
}
catch (NullPointerException e) {
Logfn.e("Can't set subtitle");
}
}
public void getSearchResult(ArrayList<SpotifyTrackSearchResult> searchResult) {
if (searchResult != null && searchResult.isEmpty()) {
showToast(getString(R.string.no_track_found));
if (mActivity.getClass().getSimpleName().equals("TopTracks")) {
mActivity.finish();
}
else {
hideListView();
}
}
else {
addAllAdapter(searchResult);
fadeListViewIn();
}
if (mTopTracksFragmentControlListener != null) {
mTopTracksFragmentControlListener.setNotificationIntentTracks(false);
}
}
public void handleSearchError() {
showToast(getString(R.string.connection_error));
if (mActivity.getClass().getSimpleName().equals("MainActivity")) {
hideListView();
}
else if (mActivity.getClass().getSimpleName().equals("TopTracks")) {
mActivity.finish();
}
fadeListViewIn();
}
private void handleIntent(Intent intent) {
Logfn.d("Intent: " + intent.getAction());
updateTopTracks(intent.getStringExtra(MainActivityFragment.ARTIST_ID),
intent.getStringExtra(MainActivityFragment.ARTIST_NAME),
mActivity);
mQuery = intent.getStringExtra(MainActivity.KEY_QUERY);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity = (Activity) context;
try {
mClickListener = (AdapterView.OnItemClickListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement AdapterView.OnItemClickListener");
}
if (getResources().getBoolean(R.bool.two_pane)) {
try {
mTopTracksFragmentControlListener = (OnTopTracksFragmentControlListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement OnTopTracksFragmentControlListener");
}
}
}
public void showToast(String message) {
toast.setText(message);
toast.show();
}
private void addAllAdapter(ArrayList<SpotifyTrackSearchResult> searchResult) {
Logfn.d("Start");
if (searchResult != null) {
mTracks = searchResult;
mTrackAdapter.addAll(mTracks);
}
}
private void fadeListViewIn() {
Logfn.d("Start");
// Set the content view to 0% opacity but visible, so that it is visible
// (but fully transparent) during the animation.
mListView.setAlpha(0f);
mListView.setVisibility(View.VISIBLE);
// Animate the content view to 100% opacity, and clear any animation
// listener set on the view.
mListView.animate()
.alpha(1f)
.setDuration(mShortAnimationDuration)
.setListener(null);
// Animate the loading view to 0% opacity. After the animation ends,
// set its visibility to GONE as an optimization step (it won't
// participate in layout passes, etc.)
mLoadingView.animate()
.alpha(0f)
.setDuration(mShortAnimationDuration)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoadingView.setVisibility(View.GONE);
}
});
}
private void showLoadingView() {
if (mLoadingView != null) {
mLoadingView.setVisibility(View.VISIBLE);
}
}
public void hideListView() {
if (mListView != null) {
mListView.setVisibility(View.GONE);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(KEY_TRACK_LIST, mTracks);
outState.putParcelable(KEY_LIST_VIEW, mListView.onSaveInstanceState());
outState.putString(KEY_ARTIST_ID, mArtistId);
outState.putString(KEY_ARTIST_NAME, mArtistName);
outState.putString(MainActivity.KEY_QUERY, mQuery);
}
}
|
package com.petersoft.mgl.utility;
public class NumberConstants {
public static final int ATTENTION_DAYS = 60;
public static final int WARNING_DAYS = 30;
private NumberConstants() {
}
public static final int MAINFRAME_WIDTH = 1200;
public static final int MAINFRAME_HEIGHT = 800;
}
|
package com.module.auth;
import com.module.model.auth.User;
import com.module.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class CustomUserDetailsService {
@Autowired
private UserRepository userRepository;
public User loadUserByUsername(String userName) throws UsernameNotFoundException {
User user = userRepository.findByUsername(userName);
if (user == null) {
throw new UsernameNotFoundException(userName);
}
return user;
}
}
|
package mx.com.azaelmorales.yurtaapp;
import android.content.Intent;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import mx.com.azaelmorales.yurtaapp.utilerias.Validar;
public class RecuperarPasswordActivity extends AppCompatActivity implements
Response.Listener<JSONObject>,Response.ErrorListener {
private EditText editTextCodigo,editTextPassword1,editTextPassword2;
private TextInputLayout textInputLayoutPass1,textInputLayoutPass2;
private String correo,codigo,newPassword;
private Button buttonCambiar;
private boolean flagb,c;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recuperar_password);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_recuperar_password);
setSupportActionBar(toolbar);
toolbar.setTitle("Recuperar contraseña");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//startActivity(new Intent(getApplicationContext(),HomeActivity.class));
finish();
}
});
Intent intent = getIntent();
Bundle b = intent.getExtras();
if(b!=null){
correo = b.getString("CORREO");
}
editTextCodigo = (EditText)findViewById(R.id.et_codigo_recuperacion);
editTextPassword1 =(EditText)findViewById(R.id.et_password1_recuperar);
editTextPassword2 =(EditText)findViewById(R.id.et_password2_recuperar);
textInputLayoutPass1 =(TextInputLayout)findViewById(R.id.til_password1);
textInputLayoutPass2 =(TextInputLayout)findViewById(R.id.til_password2);
buttonCambiar = (Button)findViewById(R.id.button_cambiar);
editTextPassword1.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
flagb = Validar.password(String.valueOf(s),textInputLayoutPass1);
}
@Override
public void afterTextChanged(Editable s) {
}
});
editTextPassword2.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
c = Validar.passwords(editTextPassword1.getText().toString().trim(),
String.valueOf(s),textInputLayoutPass2);
}
@Override
public void afterTextChanged(Editable s) {
}
});
buttonCambiar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(validaDatos()&&!editTextCodigo.getText().toString().toString().equals("")){
inicializarValores();
cambiarPassword(correo,codigo);
}else{
Toast.makeText(RecuperarPasswordActivity.this,"Error en los datos" ,Toast.LENGTH_LONG).show();
}
}
});
}
public void cambiarPassword(String correo,String codigo){
String urlBuscar = "http://dissymmetrical-diox.xyz/buscarCodigoRecuperacion.php?correo="+correo+"&codigo="+codigo;
RequestQueue requestQueue = Volley.newRequestQueue(RecuperarPasswordActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, urlBuscar, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if(response.equals("[]"))
Toast.makeText(RecuperarPasswordActivity.this,"Codigo de recuperacion incorrecto" ,Toast.LENGTH_LONG).show();
else{
actualizarPassword();
Toast.makeText(RecuperarPasswordActivity.this,"Contraseña actualizada",Toast.LENGTH_LONG).show();
finish();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast toast1 =
Toast.makeText(RecuperarPasswordActivity.this,
"Error al cargar los datos"+ error.getMessage(), Toast.LENGTH_LONG);
toast1.show();
}
});
requestQueue.add(stringRequest);
}
@Override
public void onErrorResponse(VolleyError error) {
/// Toast.makeText(this,"Error al actualizar" ,Toast.LENGTH_LONG).show();
}
@Override
public void onResponse(JSONObject response) {
Toast.makeText(this,"Contraseña actualizada",Toast.LENGTH_LONG).show();
}
private void actualizarPassword(){
RequestQueue rq;
JsonRequest jrq;
rq = Volley.newRequestQueue(this);
String url ="http://dissymmetrical-diox.xyz/cambiarPassword.php?correo="+correo+"&newpass="+newPassword+
"&codigo="+codigo;
jrq = new JsonObjectRequest(Request.Method.GET,url,null,this,this);
rq.add(jrq);
}
public void inicializarValores(){
newPassword = editTextPassword1.getText().toString().trim();
codigo = editTextCodigo.getText().toString().trim();
}
public boolean validaDatos(){
if(flagb&&c)
return true;
return false;
}
}
|
package retrogene.discover;
import java.util.Set;
import htsjdk.samtools.util.IntervalTree.Node;
import retrogene.gene.GenesLoader.Exon;
public class Pseudogene {
private int exonPoss;
private Set<Node<Exon>> foundExons;
private int totalSRs;
private int totalDPs;
public Pseudogene (int exonPoss, Set<Node<Exon>> foundExons, int totalSRs, int totalDPs) {
this.exonPoss = exonPoss;
this.foundExons = foundExons;
this.totalSRs = totalSRs;
this.totalDPs = totalDPs;
}
public int getExonHits() {
return foundExons.size();
}
public int getExonPoss() {
return exonPoss;
}
public Set<Node<Exon>> getFoundExons() {
return foundExons;
}
public int getTotalSRs() {
return totalSRs;
}
public int getTotalDPs() {
return totalDPs;
}
}
|
package com.fleet.fastdfs.util;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@Component
public class FastDFSUtil {
@Resource
private FastFileStorageClient storageClient;
/**
* 上传文件
*/
public String uploadFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
StorePath storePath = storageClient.uploadFile(is, file.length(), FilenameUtils.getExtension(file.getName()), null);
return storePath.getFullPath();
}
/**
* 上传文件
*/
public String uploadFile(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
return storePath.getFullPath();
}
/**
* 上传文件
*/
public String uploadFile(InputStream is, String fileExtName) throws IOException {
StorePath storePath = storageClient.uploadFile(is, is.available(), fileExtName, null);
return storePath.getFullPath();
}
/**
* 上传图片文件
*/
public String uploadImageFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
StorePath storePath = storageClient.uploadImageAndCrtThumbImage(is, file.length(), FilenameUtils.getExtension(file.getName()), null);
return storePath.getFullPath();
}
/**
* 上传图片文件
*/
public String uploadImageFile(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
return storePath.getFullPath();
}
/**
* 上传图片文件
*/
public String uploadImageFile(InputStream is, String fileExtName) throws IOException {
StorePath storePath = storageClient.uploadImageAndCrtThumbImage(is, is.available(), fileExtName, null);
return storePath.getFullPath();
}
/**
* 下载文件
*/
public byte[] downloadFile(String filePath) {
if (StringUtils.isEmpty(filePath)) {
return null;
}
StorePath storePath = StorePath.parseFromUrl(filePath);
return storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
}
/**
* 删除文件
*/
public void deleteFile(String filePath) {
if (StringUtils.isEmpty(filePath)) {
return;
}
StorePath storePath = StorePath.parseFromUrl(filePath);
storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
}
}
|
package edu.isi.karma.cleaning.correctness;
import edu.isi.karma.cleaning.DataRecord;
public class FatalErrorInspector implements Inspector {
@Override
public String getName() {
return this.getClass().getName();
}
@Override
public double getActionLabel(DataRecord record) {
if(record.transformed.indexOf("_FATAL_ERROR_")!= -1){
String[] tmp = record.transformed.split("((?<=_\\d_FATAL_ERROR_)|(?=_\\d_FATAL_ERROR_))");
double ret = 0.0;
for (String tmpstring : tmp) {
int errnum = 0;
if (tmpstring.indexOf("_FATAL_ERROR_") == -1) {
continue;
}
errnum = Integer.valueOf(tmpstring.substring(1, 2));
ret -= errnum;
}
return ret;
}
else{
return 1;
}
}
}
|
package com.mx.profuturo.bolsa.model.service.vacancies.vo;
import com.mx.profuturo.bolsa.model.service.vacancies.base.Persona;
public class CandidatoDatosBasicosVO extends Persona {
private Integer id;
private String tipo;
private String descripcionTipo;
private String telefono;
private String nivelEstudios;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getNivelEstudios() {
return nivelEstudios;
}
public void setNivelEstudios(String nivelEstudios) {
this.nivelEstudios = nivelEstudios;
}
public String getDescripcionTipo() {
return descripcionTipo;
}
public void setDescripcionTipo(String descripcionTipo) {
this.descripcionTipo = descripcionTipo;
}
}
|
package eiti.sag.facebookcrawler.accessor.jsoup.extractor;
import eiti.sag.facebookcrawler.accessor.util.UsernameParser;
import org.jsoup.nodes.Document;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class FriendsIdsExtractor implements DocumentExtractor<List<String>> {
private final UsernameParser usernameParser;
public FriendsIdsExtractor(UsernameParser usernameParser) {
this.usernameParser = usernameParser;
}
@Override
public List<String> extract(Document document) {
String cssQuery = "ul[data-pnref='friends'] div[class='fsl fwb fcb'] a";
return document.select(cssQuery).stream()
.map(e -> e.attr("href"))
.map(usernameParser::parseFromLink)
.collect(toList());
}
}
|
package quanye.org.chatapp.domain;
import java.io.Serializable;
public class Message implements Serializable {
private static final long serialVersionUID = 4455065920612636652L;
private String userName;
private String content;
public Message() {
}
public Message(String userName, String content) {
this.userName = userName;
this.content = content;
}
public void setUesrName(String userName) {
this.userName = userName;
}
public void setContent(String content) {
this.content = content;
}
public String getUserName() {
return this.userName;
}
public String getContent() {
return this.content;
}
}
|
package com.uptc.prg.maze.model.data.graphlist;
public enum EdgeType {
DIRECTED, UNDIRECTED;
}
|
package com.android.destranger.ui;
import com.android.destranger.data.UserInfo;
import java.util.ArrayList;
/**
* Created by ximing on 2015/5/12.
*/
public interface IHome extends IRoot {
void showStrangers(ArrayList<UserInfo> userInfos);
}
|
package com.ehootu.flow.controller;
import com.ehootu.core.generic.BaseController;
import com.ehootu.core.util.Query;
import com.ehootu.core.util.R;
import com.ehootu.flow.model.RiskAssessmentEntity;
import com.ehootu.flow.service.RiskAssessmentService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* 工程项目风险评估
*
* @author yinyujun
* @email
* @date 2017-09-21 15:10:26
*/
@RestController
@RequestMapping("/app/riskassessment")
public class RiskAssessmentController extends BaseController {
@Autowired
private RiskAssessmentService riskAssessmentService;
/**
* 列表
*/
@RequestMapping("/list")
@ResponseBody
public void list(@RequestParam Map<String, Object> params){
//查询列表数据
Query query = new Query(params,"app");
List<RiskAssessmentEntity> aidWorkRecord = riskAssessmentService.queryList(query);
resultSuccess(aidWorkRecord);
}
/**
* 信息
*/
@ResponseBody
@RequestMapping("/info")
public void info(String id){
RiskAssessmentEntity riskAssessment = riskAssessmentService.queryObject(id);
resultSuccess(riskAssessment);
}
/**
* 保存
*/
@PostMapping("/save")
public void save(RiskAssessmentEntity riskAssessment, String pageName){
riskAssessmentService.save(riskAssessment, pageName);
resultSuccess();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("riskassessment:update")
public R update(@RequestBody RiskAssessmentEntity riskAssessment){
riskAssessmentService.update(riskAssessment);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("riskassessment:delete")
public R delete(@RequestBody Integer[] ids){
riskAssessmentService.deleteBatch(ids);
return R.ok();
}
}
|
package com.designpattern.behaviorpattern.visitor;
public abstract class Element {
abstract void accept(Visitor visitor);
}
|
package br.unesp.rc.scrumboard.dao.impl;
import br.unesp.rc.scrumboard.beans.Project;
import br.unesp.rc.scrumboard.dao.ProjectDAO;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@Transactional
public class ProjectDAOImpl extends BaseDAO<Project> implements ProjectDAO {
@Override
public Class<Project> getType() {
return Project.class;
}
@Override
public String getTableName() {
return "Project";
}
@Override
public List<String> getTableFields() {
List<String> fields = new ArrayList();
fields.add("id");
fields.add("name");
fields.add("description");
fields.add("startDate");
fields.add("endDate");
return fields;
}
@Override
public Project populateObject(Object[] object) {
long id = (long) object[0];
String name = (String) object[1];
String description = (String) object[2];
Date startDate = (Date) object[3];
Date endDate = (Date) object[4];
return new Project(id, name, description, startDate, endDate);
}
@Override
public String getSearchNameField() {
return "name";
}
}
|
package model.data_structures;
import java.util.ArrayList;
/**
* 2019-01-23
* Estructura de Datos Arreglo Dinamico de Strings.
* El arreglo al llenarse (llegar a su maxima capacidad) debe aumentar su capacidad.
* @author Fernando De la Rosa
*
*/
public class ListaSencillamenteEncadenada<T> implements IListaSencillamenteEncadenada<T> {
/**
* Numero de elementos presentes en el arreglo (de forma compacta desde la posicion 0)
*/
private Node<T> first;
private Node<T> last;
private Node<T> oldLast;
private int dat = 0;
public void agregar( T viajeUber )
{
if (first == null) {
first = new Node<T>();
first.dato = viajeUber;
}
else {
Node<T> nodoActual = first;
while (nodoActual.next != null) {
nodoActual = nodoActual.next;
}
oldLast = nodoActual;
last = new Node<T>();
last.dato = viajeUber;
oldLast.next = last;
}
}
public int darTamano() {
int tamano = 0;
Node<T> nodoActual = first;
while (nodoActual != null){
nodoActual = nodoActual.next;
tamano++;
}
return tamano;
}
public void eliminar(T viajeUber) {
Node<T> nodoActual = first;
boolean eliminado = false;
if (first.dato == viajeUber) {
first = first.next;
}
else {
while (first.next != null && !eliminado) {
if (nodoActual.next.dato == viajeUber) {
if (nodoActual.next == last) {
last = nodoActual;
}
nodoActual.next = nodoActual.next.next;
eliminado = true;
}
else {
nodoActual = nodoActual.next;
}
}
}
}
public ArrayList<T> leer() {
ArrayList<T> arc = new ArrayList<>();
Node<T> nodoActual = first;
while (nodoActual != null) {
arc.add(nodoActual.dato);
nodoActual = nodoActual.next;
}
return arc;
}
private class Node<T>{
T dato;
Node<T> next;
}
}
|
import java.util.ArrayList;
//static : 객체 생성 없이 사용 가능 -> 메모리를 만들어 놓고 시작한다
//static안에서 static을 사용하고 싶으면, 사용하고자 하는 함수도 static이어야함
class Apple {
static void func01() {
System.out.println(1);
func02();
}
static void func02() {
System.out.println(2);
}
}
public class StaticEx01 {
// main에서 사용 불가
void func01() {
}
// main에서 사용 가능 -> 보통 test용도
static void func02() {
}
static void func03(int num) {
// System.out.println(num); // 10진수로 받음
String a = Integer.toBinaryString(num);
int temp = a.length() % 4; // 나머지
if (temp != 0) {
for (int i = 0; i < 4 - temp; i++) {
a = "0" + a;
}
}
int j = 0;
for (int i = 0; i < a.length() / 4; i++) {
System.out.print(a.substring(i * 4, i * 4 + 4) + " ");
}
System.out.println();
}
static void func04() {
/*
* String : 객체가 생성되고 나면, 안에 내용 수정 불가 -> 객체가 수정되는게 아니라 새로 만들어짐 StringBuffer : 데이터
* 갱신 가능 ex)CRUD
*/
String s = "호랑이";
s = "코끼리"; // 데이터가 수정된게 아니라 객체가 새로 만들어짐 -> 기존 '호랑이' 객체가 없어짐
}
static void func05(int num) {
String s1 = Integer.toBinaryString(num);
// System.out.println(s1.length());
char[] arr = new char[32 - s1.length()];
for (int i = 0; i < arr.length; i++) {
arr[i] = '0';
}
String s2 = new String(arr);
// System.out.println(s2);
String s3 = s2 + s1;
// System.out.println(s3);
StringBuffer s4 = new StringBuffer(s2 + s1);
// System.out.println(s4);
// System.out.println(s4.length());
for (int i = 0; i < 7; i++) {
s4.insert((7 - i) * 4, ' ');
}
System.out.println(s4);
}
public static void main(String[] args) {
// Apple.func01();
func03(0x3c94ab73);
func05(0x3c94ab73);
}
}
|
package com.yunkuent.sdk.compat.v2;
import com.gokuai.base.HttpEngine;
import com.gokuai.base.LogPrint;
import com.gokuai.base.RequestMethod;
import com.gokuai.base.utils.Util;
import com.yunkuent.sdk.*;
import com.yunkuent.sdk.upload.UploadCallBack;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
/**
* Created by Brandon on 2017/3/20.
*/
public class EntFileManager extends HttpEngine {
private static final String TAG = "EntFileManager";
private static final int UPLOAD_LIMIT_SIZE = 52428800;
private final String URL_API_FILELIST = HostConfig.API_ENT_HOST_V2 + "/1/file/ls";
private final String URL_API_UPDATE_LIST = HostConfig.API_ENT_HOST_V2 + "/1/file/updates";
private final String URL_API_FILE_INFO = HostConfig.API_ENT_HOST_V2 + "/1/file/info";
private final String URL_API_CREATE_FOLDER = HostConfig.API_ENT_HOST_V2 + "/1/file/create_folder";
private final String URL_API_CREATE_FILE = HostConfig.API_ENT_HOST_V2 + "/1/file/create_file";
private final String URL_API_DEL_FILE = HostConfig.API_ENT_HOST_V2 + "/1/file/del";
private final String URL_API_MOVE_FILE = HostConfig.API_ENT_HOST_V2 + "/1/file/move";
private final String URL_API_LINK_FILE = HostConfig.API_ENT_HOST_V2 + "/1/file/link";
private final String URL_API_SENDMSG = HostConfig.API_ENT_HOST_V2 + "/1/file/sendmsg";
private final String URL_API_GET_LINK = HostConfig.API_ENT_HOST_V2 + "/1/file/links";
private final String URL_API_UPDATE_COUNT = HostConfig.API_ENT_HOST_V2 + "/1/file/updates_count";
private final String URL_API_GET_SERVER_SITE = HostConfig.API_ENT_HOST_V2 + "/1/file/servers";
private final String URL_API_CREATE_FILE_BY_URL = HostConfig.API_ENT_HOST_V2 + "/1/file/create_file_by_url";
private final String URL_API_UPLOAD_SERVERS = HostConfig.API_ENT_HOST_V2 + "/1/file/upload_servers";
public EntFileManager(String clientId, String clientSecret) {
super(clientId, clientSecret);
}
/**
* 获取根目录文件列表
*
* @return
*/
public String getFileList() {
return this.getFileList("", 0, 100, false);
}
/**
* 获取文件列表
*
* @param fullPath 路径, 空字符串表示根目录
* @return
*/
public String getFileList(String fullPath) {
return this.getFileList(fullPath, 0, 100, false);
}
/**
* 获取文件列表
*
* @param fullPath 路径, 空字符串表示根目录
* @param start 起始下标, 分页显示
* @param size 返回文件/文件夹数量限制
* @param dirOnly 只返回文件夹
* @return
*/
public String getFileList(String fullPath, int start, int size, boolean dirOnly) {
String url = URL_API_FILELIST;
HashMap<String, String> params = new HashMap<>();
params.put("org_client_id", mClientId);
params.put("dateline", Util.getUnixDateline() + "");
params.put("fullpath", fullPath);
params.put("start", start + "");
params.put("size", size + "");
if (dirOnly) {
params.put("dir", "1");
}
params.put("sign", generateSign(params));
return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.GET).executeSync();
}
/**
* 获取更新列表
*
* @param isCompare
* @param fetchDateline
* @return
*/
public String getUpdateList(boolean isCompare, long fetchDateline) {
String url = URL_API_UPDATE_LIST;
HashMap<String, String> params = new HashMap<>();
params.put("org_client_id", mClientId);
params.put("dateline", Util.getUnixDateline() + "");
if (isCompare) {
params.put("mode", "compare");
}
params.put("fetch_dateline", fetchDateline + "");
params.put("sign", generateSign(params));
return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.GET).executeSync();
}
/**
* 获取文件信息
*
* @param fullPath
* @param net
* @return
*/
public String getFileInfo(String fullPath, EntFileManager.NetType net) {
String url = URL_API_FILE_INFO;
HashMap<String, String> params = new HashMap<>();
params.put("org_client_id", mClientId);
params.put("dateline", Util.getUnixDateline() + "");
params.put("fullpath", fullPath);
switch (net) {
case DEFAULT:
break;
case IN:
params.put("net", net.name().toLowerCase());
break;
}
params.put("sign", generateSign(params));
return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.GET).executeSync();
}
/**
* 创建文件夹
*
* @param fullPath
* @param opName
* @return
*/
public String createFolder(String fullPath, String opName) {
String url = URL_API_CREATE_FOLDER;
HashMap<String, String> params = new HashMap<>();
params.put("org_client_id", mClientId);
params.put("dateline", Util.getUnixDateline() + "");
params.put("fullpath", fullPath);
params.put("op_name", opName);
params.put("sign", generateSign(params));
return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync();
}
/**
* 通过文件流上传
*
* @param fullPath
* @param opName
* @param stream
* @return
*/
public String createFile(String fullPath, String opName, FileInputStream stream) {
try {
if (stream.available() > UPLOAD_LIMIT_SIZE) {
LogPrint.error(TAG, "文件大小超过50MB");
return "";
}
} catch (IOException e) {
e.printStackTrace();
}
String fileName = Util.getNameFromPath(fullPath);
try {
long dateline = Util.getUnixDateline();
HashMap<String, String> params = new HashMap<>();
params.put("org_client_id", mClientId);
params.put("dateline", dateline + "");
params.put("fullpath", fullPath);
params.put("op_name", opName);
params.put("filefield", "file");
MsMultiPartFormData multipart = new MsMultiPartFormData(URL_API_CREATE_FILE, "UTF-8");
multipart.addFormField("org_client_id", mClientId);
multipart.addFormField("dateline", dateline + "");
multipart.addFormField("fullpath", fullPath);
multipart.addFormField("op_name", opName);
multipart.addFormField("filefield", "file");
multipart.addFormField("sign", generateSign(params));
multipart.addFilePart("file", stream, fileName);
return multipart.finish();
} catch (IOException ex) {
System.err.println(ex);
}
return "";
}
/**
* 文件分块上传
*
* @param fullPath
* @param opName
* @param opId
* @param localFilePath
* @param overWrite
* @param callBack
*/
public UploadRunnable uploadByBlock(String fullPath, String opName, int opId, String localFilePath,
boolean overWrite, UploadCallBack callBack) {
UploadRunnable uploadRunnable = new UploadRunnable(URL_API_CREATE_FILE, localFilePath, fullPath, opName, opId, mClientId, Util.getUnixDateline(), callBack, mClientSecret, overWrite);
Thread thread = new Thread(uploadRunnable);
thread.start();
return uploadRunnable;
}
/**
* 通过本地路径上传
*
* @param fullPath
* @param opName
* @param localPath
* @return
*/
public String createFile(String fullPath, String opName, String localPath) {
File file = new File(localPath.trim());
if (file.exists()) {
try {
FileInputStream inputStream = new FileInputStream(file);
return createFile(fullPath, opName, inputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
LogPrint.error(TAG, "file not exist");
}
return "";
}
/**
* 删除文件
*
* @param fullPaths
* @param opName
* @return
*/
public String del(String fullPaths, String opName) {
String url = URL_API_DEL_FILE;
HashMap<String, String> params = new HashMap<>();
params.put("org_client_id", mClientId);
params.put("dateline", Util.getUnixDateline() + "");
params.put("fullpaths", fullPaths);
params.put("op_name", opName);
params.put("sign", generateSign(params));
return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync();
}
/**
* 移动文件
*
* @param fullPath
* @param destFullPath
* @param opName
* @return
*/
public String move(String fullPath, String destFullPath, String opName) {
String url = URL_API_MOVE_FILE;
HashMap<String, String> params = new HashMap<>();
params.put("org_client_id", mClientId);
params.put("dateline", Util.getUnixDateline() + "");
params.put("fullpath", fullPath);
params.put("dest_fullpath", destFullPath);
params.put("op_name", opName);
params.put("sign", generateSign(params));
return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync();
}
/**
* 获取文件链接
*
* @param fullPath
* @param deadline
* @param authType
* @param password
* @return
*/
public String link(String fullPath, int deadline, EntFileManager.AuthType authType, String password) {
String url = URL_API_LINK_FILE;
HashMap<String, String> params = new HashMap<>();
params.put("org_client_id", mClientId);
params.put("dateline", Util.getUnixDateline() + "");
params.put("fullpath", fullPath);
if (deadline != 0) {
params.put("deadline", deadline + "");
}
if (!authType.equals(com.yunkuent.sdk.EntFileManager.AuthType.DEFAULT)) {
params.put("auth", authType.toString().toLowerCase());
}
params.put("password", password);
params.put("sign", generateSign(params));
return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync();
}
/**
* 发送消息
*
* @param title
* @param text
* @param image
* @param linkUrl
* @param opName
* @return
*/
public String sendmsg(String title, String text, String image, String linkUrl, String opName) {
String url = URL_API_SENDMSG;
HashMap<String, String> params = new HashMap<>();
params.put("org_client_id", mClientId);
params.put("dateline", Util.getUnixDateline() + "");
params.put("title", title);
params.put("text", text);
params.put("image", image);
params.put("url", linkUrl);
params.put("op_name", opName);
params.put("sign", generateSign(params));
return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync();
}
/**
* 获取当前库所有外链
*
* @return
*/
public String links(boolean fileOnly) {
String url = URL_API_GET_LINK;
HashMap<String, String> params = new HashMap<>();
params.put("org_client_id", mClientId);
params.put("dateline", Util.getUnixDateline() + "");
if (fileOnly) {
params.put("file", "1");
}
params.put("sign", generateSign(params));
return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.GET).executeSync();
}
/**
* 文件更新数量
*
* @param beginDateline
* @param endDateline
* @param showDelete
* @return
*/
public String getUpdateCounts(long beginDateline, long endDateline, boolean showDelete) {
String url = URL_API_UPDATE_COUNT;
HashMap<String, String> params = new HashMap<>();
params.put("org_client_id", mClientId);
params.put("dateline", Util.getUnixDateline() + "");
params.put("begin_dateline", beginDateline + "");
params.put("end_dateline", endDateline + "");
params.put("showdel", (showDelete ? 1 : 0) + "");
params.put("sign", generateSign(params));
return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.GET).executeSync();
}
/**
* 通过链接上传文件
*
* @param fullPath
* @param opId
* @param opName
* @param overwrite
* @param fileUrl
* @return
*/
public String createFileByUrl(String fullPath, int opId, String opName, boolean overwrite, String fileUrl) {
String url = URL_API_CREATE_FILE_BY_URL;
HashMap<String, String> params = new HashMap<>();
params.put("org_client_id", mClientId);
params.put("fullpath", fullPath);
params.put("dateline", Util.getUnixDateline() + "");
if (opId > 0) {
params.put("op_id", opId + "");
} else {
params.put("op_name", opName + "");
}
params.put("overwrite", (overwrite ? 1 : 0) + "");
params.put("url", fileUrl);
params.put("sign", generateSign(params));
return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync();
}
/**
* 获取上传地址
* <p>
* (支持50MB以上文件的上传)
*
* @return
*/
public String getUploadServers() {
String url = URL_API_UPLOAD_SERVERS;
HashMap<String, String> params = new HashMap<>();
params.put("org_client_id", mClientId);
params.put("dateline", Util.getUnixDateline() + "");
params.put("sign", generateSign(params));
return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.GET).executeSync();
}
/**
* 获取服务器地址
*
* @param type
* @return
*/
public String getServerSite(String type) {
String url = URL_API_GET_SERVER_SITE;
HashMap<String, String> params = new HashMap<>();
params.put("org_client_id", mClientId);
params.put("type", type);
params.put("dateline", Util.getUnixDateline() + "");
params.put("sign", generateSign(params));
return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync();
}
/**
* 复制一个EntFileManager对象
*
* @return
*/
public EntFileManager clone() {
return new EntFileManager(mClientId, mClientSecret);
}
public enum AuthType {
DEFAULT,
PREVIEW,
DOWNLOAD,
UPLOAD
}
public enum NetType {
DEFAULT,
IN
}
}
|
package com.DoAn.HairStyle.dto;
public class CheckListResponse {
private String time;
private String timeByWords;
private Boolean isFree;
public void setTime(String time) {
this.time = time;
}
public void setTimeByWords(String timeByWords) {
this.timeByWords = timeByWords;
}
public void setFree(Boolean free) {
isFree = free;
}
public String getTime() {
return time;
}
public String getTimeByWords() {
return timeByWords;
}
public Boolean getFree() {
return isFree;
}
}
|
package Varqina;
//Given two arrays a and b write a function comp(a, b) (compSame(a, b) in Clojure) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a squared, regardless of the order.
public class CompareTable {
public static void main(String[] args) {
int[] a = new int[]{1,3,3,4,4};
int[] b = new int[]{1,4,9,16,16};
int[] c = new int[]{};
System.out.println(comp(a,b));
}
public static boolean comp(int[] a, int[] b) {
if(a ==null || b ==null){return false;}
if(a.length==0 && b.length==0 ){return true;}
if(a.length==0 || b.length==0 ){return false;}
int counter=0;
for(int i =0;i<a.length;i++)
{
for ( int j=0;j<b.length;j++)
{
if (Math.pow(a[i],2)==b[j])
{
a[i]=3;
b[j]=3;
counter++;
break;
}
}
if(counter-1!=i){return false;}
}
return counter==a.length;
}
}
|
package com.example.homeprod.assistent_begins;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
/**
* Элемент в котором отображается чат
*/
private TextView chat;
/**
* Поле для ввода сообщение
*/
private EditText message;
/**
* Кнопка "отправить"
*/
private Button send;
/**
* Кнопка "очистить"
*/
private Button clear;
/**
* объект для форматирования даты/времени
*/
private DateFormat fmt;
/**
* Метод, который вызывается при создании Activity
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* Найдем нужные элементы интерфейса по id
*/
chat = (TextView) findViewById(R.id.chatView);
chat.setMovementMethod(new ScrollingMovementMethod());
message = (EditText) findViewById(R.id.editText);
send = (Button) findViewById(R.id.sendBtn);
clear = (Button) findViewById(R.id.cleatBtn);
/**
* Назначим обработчик события "Клик" на кнопке "отправить"
*/
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String question = message.getText().toString(); // Получим текст вопроса
message.setText(""); // Очистим поле
chat.append("\n<< " + question); // Отобразим вопрос в чате
String answer = answerQuestion(question); // Вычислим тексто ответа
chat.append("\n>> " + answer); // Отобразим ответ в чате
}
});
/**
* Назначим обработчик события "Клик" на кнопке "очистить"
*/
clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
chat.setText("");
}
});
}
protected String answerQuestion(String question) {
question = question.toLowerCase(); // Привидем текст к нижнему регистру
Map<String, String> questions = new HashMap<String, String>() {{ // Заполним "карту ответов"
put("привет", "Привет! ");
put("как дела", "Шикарно");
put("чем занимаешься", "Отвечаю на дурацкие вопросы");
put("как тебя зовут", "Меня зовут Ассистентий");
put("лал", "кек");
put("кек", "чебурек");
put("спасибо", "пожалуйста! обращайся ;)");
put("в чем смысл жизни", "вычисление ответа займет....около 100500+ лет, но это не точно");
put("пока", "пока! " + goodbyeMsg(new Date()) + "");
}};
List<String> result = new ArrayList<>(); // В этом списке будем хранить ответы
for (String quest : questions.keySet()) { // Пройдем циклом по карте ответов и найдем совпадающие вопросы
if (question.contains(quest)) {
result.add(questions.get(quest)); // Если в тексте содержится вопрос, то запишем в список соотв. ответ
}
}
if (question.contains("сколько времени")) { // Отдельно предусмотрим случай, когда пользователь спрашивает время
fmt = new SimpleDateFormat("HH:mm:ss");
String time = fmt.format(new Date()); // Отформатируем текущую дату
result.add("Сейчас " + time); // Запишем ответ в список
}
if (question.contains("какой сегодня день")) {
fmt = new SimpleDateFormat("EEEE, dd MMMM", new Locale("ru"));// Отдельно предусмотрим случай, когда пользователь спрашивает текущий день
String time = fmt.format(new Date()); // Отформатируем текущую дату
result.add("Сегодня: " + time); // Запишем ответ в список
}
return TextUtils.join(", ", result); // Все получившиеся ответы объединим через запятую и вернем как результат метода
}
/**
* возвращает прощание относительно времени суток
* @param date
* @return
*/
private String goodbyeMsg(Date date) {
Date editDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(editDate);
cal.set(Calendar.HOUR_OF_DAY, 17); // устанавливаем время для ориентации во времени суток
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return date.after(cal.getTime()) ? "хорошего вечера!" : "хорошего дня!"; //возвращаем ответ в зависимости от текущего времени
}
}
|
package com.testarea;
import java.time.LocalDateTime;
public class NewMain {
public static void main(String[] args) {
int secs = LocalDateTime.now().getSecond();
System.out.println("00:00:" + secs);
}
}
|
package lesson3.intermediate;
import java.util.Arrays;
/**
* Created by apodushkina on 23.01.2017.
*/
public class Task3 {
public static void main(String[] args) {
Task3 t3 = new Task3();
System.out.println("Reverted array - " + t3.revertArr());
}
int[] arr = {1, 2, 3, 4, 5, 6};
public String revertArr() {
System.out.println("Tas - Reversed array. Write a method which takes an array and returns inverted one");
System.out.println("Initial array - " + Arrays.toString(arr));
for (int i = 0; i < arr.length / 2; i++) {
int j = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = j;
}
return Arrays.toString(arr);
}
}
|
package task5;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import java.util.Random;
import static org.junit.Assert.*;
public class ShellSortTest {
@Rule
public Timeout globalTimeout = Timeout.seconds(4000);
@Test
public void sort() {
}
@Test
public void TestShellSort() {
int size = 100000;
int[] best = new int[size];
for (int i = 0; i < size; i++)
best[i] = i;
ShellSort.sort(best);
}
@Test
public void TestShellSort2() {
int size = 10000;
int[] worst = new int[size];
for (int i = size - 1, j = 0; i >= 0; i--, j++)
worst[i] = j;
ShellSort.sort(worst);
}
@Test
public void TestShellSort3() {
int size = 10000;
Random random = new Random();
int[] average = new int[size];
for (int i = 0; i < size; i++)
average[i] = random.nextInt(size);
ShellSort.sort(average);
}
}
|
/*
自定义异常
因为项目中会出现特有问题,而这些问题并未被java所描述并封装对象;
所以对于这些特有问题可以按Java的对问题封装的思想,将特有问题进行自定
义的异常封装。
需求:在本程序中,对于除数是负数也视为是错误的,是无法进行运算的
那么就需要对这个问题进行自定义描述
当在函数内部出现了throw抛异常对象,那么就必须要给对应的处理动作:
1.java虚拟机处理(调用者处理)
2.在内部try catch处理
一般情况下,函数内出现异常,函数上需要声明。
发现打印的结果中只有异常的名称,却没有异常的信息
:因为自定义的异常并未定义信息
如何定义异常信息?
:因为父类中已经把异常信息的操作都完成了。所以子类只要在构造时,
将异常信息传递给父类通过super语句,那么就可以直接通过getMessage方
法获取自定义的异常信息。
注意:
1.必须是自定义类继承Exception(Exception 和 Error是Throwable下的两个派系
:异常体系有一个特点:因为异常类和异常对象都需要被抛出,它们都具
备可抛出性,这个可抛出性是Throwable这个体系中独有特点,只有这个体系中
的类和对象才可以被throw和throws操作
throws和throw的区别:
1.throws 使用在函数上;throw 使用在函数内
2.throws 后面跟的异常类可以是多个用逗号隔开;throw 后面跟的是异常对象
throws的都是编译时被检测异常,如果没声明,那么会编译失败
*/
// 自定义负数异常类
// java的异常可以自动抛出,但是自定义异常java不认识,必须手动抛出
class FuShuException extends Exception{
// 自定义类特有成员变量
private int value;
FuShuException(String msg, int value)
{
super(msg);
this.value = value;
}
// 自定义类特有方法
public int getValue()
{
return this.value;
}
}
class Demo{
int div(int a,int b) throws FuShuException // 一般情况下,函数内出现异常,函数上需要声明。
{
if(b < 0){
// java的异常可以自动抛出,但是自定义异常java不认识,必须手动抛出
// 手动通过throw关键字抛出一个自定义异常对象注意是throw不是throws
throw new FuShuException("负数是除数异常---/ by fushu",b);
}
return a/b;
}
}
class ExceptionDemo4{
// 错误: 未报告的异常错误FuShuException; 必须对其进行捕获或声明以便抛出
public static void main(String[] args)
{
Demo d = new Demo();
try{
int x = d.div(4,-1);
System.out.println("x="+x);
}
catch(FuShuException e){
System.out.println(e.toString());
System.out.println("错误的负数是: " + e.getValue());
}
System.out.println("over");
}
}
/*
class Throwable
{
private String message;
Throwable(Striong message)
{
this.message = message;
}
public String getMessage(){
return this.message;
}
}
class Exception extends Throwable
{
Exception(String message)
{
super(message);
}
}
*/
|
package cn.ehanmy.hospital.mvp.model.entity.store;
import cn.ehanmy.hospital.mvp.model.entity.response.BaseResponse;
public class GetStoreInfoResponse extends BaseResponse {
private StoreBean store;
@Override
public String toString() {
return "GetStoreInfoResponse{" +
"store=" + store +
'}';
}
public StoreBean getStore() {
return store;
}
public void setStore(StoreBean store) {
this.store = store;
}
}
|
package nowcoder.剑指offer;
import java.util.Arrays;
/**
* @Author: Mr.M
* @Date: 2019-03-09 12:43
* @Description: 构建乘积数组
**/
public class T51 {
public int[] multiply(int[] A) {
int[] B = new int[A.length];
for (int i = 0; i < A.length; i++) {
int sum = 1;
for (int j = 0; j < B.length; j++) {
if (j == i) {
continue;
}
sum *= A[j];
}
B[i] = sum;
}
return B;
}
public static int[] multiply1(int[] A) {
int length = A.length;
int[] B = new int[length];
if (length != 0) {
B[0] = 1;
//计算下三角连乘
for (int i = 1; i < length; i++) {
B[i] = B[i - 1] * A[i - 1];
}
int temp = 1;
//计算上三角连乘
for (int j = length - 2; j >= 0; j--) {
temp *= A[j + 1];
B[j] *= temp;
}
}
return B;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(multiply1(new int[]{2,3,4,5})));
}
}
|
package org.tinyspring.test.v3;
import org.junit.Test;
import org.tinyspring.beans.BeanDefinition;
import org.tinyspring.beans.ConstructorArgument;
import org.tinyspring.beans.factory.config.RuntimeBeanReference;
import org.tinyspring.beans.factory.config.TypedStringValue;
import org.tinyspring.beans.factory.support.DefaultBeanFactory;
import org.tinyspring.beans.factory.xml.XmlBeanDefinitionReader;
import org.tinyspring.core.io.Resource;
import org.tinyspring.core.io.support.ClassPathResource;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* @author tangyingqi
* @date 2018/7/9
*/
public class BeanDefinitionTestV3 {
@Test
public void testConstructorArgument(){
DefaultBeanFactory beanFactory = new DefaultBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
Resource resource = new ClassPathResource("petstore-v3.xml");
reader.loadBeanDefinition(resource);
BeanDefinition bd = beanFactory.getBeanDefinition("petStore");
assertEquals("org.tinyspring.service.v3.PetStoreService",bd.getBeanClassName());
ConstructorArgument args = bd.getConstructorArgument();
List<ConstructorArgument.ValueHolder> valueHolders = args.getArgumentValues();
assertEquals(3,valueHolders.size());
RuntimeBeanReference rf1 = (RuntimeBeanReference)valueHolders.get(0).getValue();
assertEquals("accountDao",rf1.getBeanName());
RuntimeBeanReference rf2 = (RuntimeBeanReference)valueHolders.get(1).getValue();
assertEquals("itemDao",rf2.getBeanName());
TypedStringValue strValue = (TypedStringValue) valueHolders.get(2).getValue();
assertEquals("1",strValue.getValue());
}
}
|
package com.github.emailtohl.integration.core.user.customer;
import static com.github.emailtohl.integration.core.role.Authority.AUDIT_USER;
import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import com.github.emailtohl.integration.core.user.entities.Customer;
import com.github.emailtohl.lib.jpa.AuditedRepository.RevTuple;
/**
* 查询被审计的客户的历史记录
* @author HeLei
*/
@PreAuthorize("hasAuthority('" + AUDIT_USER + "')")
public interface CustomerAuditedService {
/**
* 查询客户所有的历史记录
* @param id 平台账号id
* @return 元组列表,元组中包含版本详情,实体在该版本时的状态以及该版本的操作(增、改、删)
*/
List<RevTuple<Customer>> getCustomerRevision(Long id);
/**
* 查询客户在某个修订版时的历史记录
* @param id 客户的id
* @param revision 版本号,通过AuditReader#getRevisions(Customer.class, ID)获得
* @return
*/
Customer getCustomerAtRevision(Long id, Number revision);
}
|
/**
* This package contains the implementation of the clients need for accessing the services
* of the application. It also contains some other classes needed during the development
* of the final version of the client GUI.
*/
package clients;
|
/*
* @Author : fengzhi
* @date : 2019 - 04 - 14 18 : 49
* @Description :
*/
package problem55;
public class Solution {
}
|
package views.grid;
import java.awt.Dimension;
import java.util.Collection;
import javafx.scene.Group;
import javafx.scene.shape.Polygon;
import models.grid.Cell;
import resources.AppResources;
import views.styles.CellStyleGuide;
/**
* A class used to build the Grid View with hexagonal cells
* @author Guhan Muruganandam
*
*/
public class GridViewUpdateHexagon extends GridViewUpdate {
private double myEdge;
private double xOddShift;
private double yOddShift;
private double xPropagate;
private double yPropagate;
public GridViewUpdateHexagon(int width,int height,Dimension dimensions,Group root,CellStyleGuide csg,Collection<Cell> cells) {
super(width,height,dimensions,root,csg,cells);
myEdge=myCellHeight*AppResources.HALF;
xOddShift=myCellWidth*AppResources.HALF;
yOddShift=myEdge*AppResources.HALF+myHeight*AppResources.HALF;
}
@Override
public void addCell(Cell currcell) {
getCellLocation(currcell);
xPropagate=myCellx*myCellWidth;
yPropagate=myCelly*(myCellHeight+myEdge)*AppResources.HALF;
Polygon cellhexagon=new Polygon();
if(((myCelly)%2)==0){
BuildHexagon(cellhexagon);
} else {
BuildHexagonShifted(cellhexagon);
}
cellSetup(currcell,cellhexagon);
}
private void BuildHexagon(Polygon cellhexagon) {
cellhexagon.getPoints().addAll(new Double[]{
// Moving clockwise from the top
xOffset+xPropagate ,yOffset+yPropagate-myCellHeight*AppResources.HALF,
xOffset+xPropagate+myCellWidth*AppResources.HALF,yOffset+yPropagate-myEdge*AppResources.HALF,
xOffset+xPropagate+myCellWidth*AppResources.HALF,yOffset+yPropagate+myEdge*AppResources.HALF,
xOffset+xPropagate ,yOffset+yPropagate+myCellHeight*AppResources.HALF,
xOffset+xPropagate-myCellWidth*AppResources.HALF,yOffset+yPropagate+myEdge*AppResources.HALF,
xOffset+xPropagate-myCellWidth*AppResources.HALF,yOffset+yPropagate-myEdge*AppResources.HALF
});
}
private void BuildHexagonShifted(Polygon cellhexagon) {
cellhexagon.getPoints().addAll(new Double[]{
//Moving clockwise from the top
xOffset+xPropagate+xOddShift ,yOffset+yPropagate-myCellHeight*AppResources.HALF,
xOffset+xPropagate+xOddShift+myCellWidth*AppResources.HALF,yOffset+yPropagate-myEdge*AppResources.HALF,
xOffset+xPropagate+xOddShift+myCellWidth*AppResources.HALF,yOffset+yPropagate+myEdge*AppResources.HALF,
xOffset+xPropagate+xOddShift ,yOffset+yPropagate+myCellHeight*AppResources.HALF,
xOffset+xPropagate+xOddShift-myCellWidth*AppResources.HALF,yOffset+yPropagate+myEdge*AppResources.HALF,
xOffset+xPropagate+xOddShift-myCellWidth*AppResources.HALF,yOffset+yPropagate-myEdge*AppResources.HALF
});
}
}
|
/**
* TheNewSoftListView.java
* created at:2011-5-20下午03:08:11
*
* Copyright (c) 2011, 北京爱皮科技有限公司
*
* All right reserved
*/
package com.appdear.client;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
import com.appdear.client.Adapter.StorelistAdatper;
import com.appdear.client.commctrls.Common;
import com.appdear.client.commctrls.ListBaseActivity;
import com.appdear.client.commctrls.ListViewRefresh;
import com.appdear.client.commctrls.MProgress;
import com.appdear.client.commctrls.SharedPreferencesControl;
import com.appdear.client.exception.ApiException;
import com.appdear.client.exception.ServerException;
import com.appdear.client.model.ShopModel;
import com.appdear.client.service.AppContext;
import com.appdear.client.service.MyApplication;
import com.appdear.client.service.api.ApiShopListRequest;
import com.appdear.client.service.api.ApiShopListResult;
import com.appdear.client.service.api.ApiSoftListResult;
/**
* 积分
*
* @author jdan
*/
public class StoreListActivity extends ListBaseActivity {
/**
* 列表数据
*/
private ApiSoftListResult result;
ApiShopListResult shopListResult ;
/**
* 详细信息列表
*/
private List<ShopModel> listData = new ArrayList<ShopModel>();
private String area = "";
private String chcode ="";
private TextView wualert;
private boolean first;
/* (non-Javadoc)
* @see android.app.ActivityGroup#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isUpdate = true;
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.soft_list_layout);
params = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
loadingView=new MProgress(this,true);
this.addContentView(loadingView, params);
if (!AppContext.getInstance().isNetState) {
handler1.sendEmptyMessage(LOADG);
showRefreshButton();
return;
}
}
@Override
public void init() {
area = this.getIntent().getStringExtra("area");
chcode = this.getIntent().getStringExtra("androidchchode");
System.out.println(area+"-----------------"+chcode);
listView = (ListViewRefresh) findViewById(R.id.soft_list);
listView.setCacheColorHint(Color.TRANSPARENT);
first=this.getIntent().getBooleanExtra("first", false);
wualert = (TextView) findViewById(R.id.alert);
wualert.setText("请选择省市和手机品牌");
wualert.setVisibility(View.INVISIBLE);
/*listView.setDivider(getResources().getDrawable(R.drawable.listspiner));
listView.setDividerHeight(2);*/
}
@Override
public void initData() {
try {
if(area!=null&&!"".equals(area)){
try {
shopListResult = ApiShopListRequest.ShopListRequest(area,"1",chcode);
} catch (ServerException e) {
showException(e);
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
showException(e);
e.printStackTrace();
}
if(shopListResult==null)return;
listData = shopListResult.shopList;
adapter = new StorelistAdatper(this, listData);
adapter.notifyDataSetChanged();
}
} catch (ApiException e) {
showException(e.getMessage());
showRefreshButton();
}finally{
handler1.sendEmptyMessage(LOADG);
}
super.initData();
}
/* (non-Javadoc)
* @see com.appdear.client.commctrls.BaseActivity#updateUI()
*/
@Override
public void updateUI() {
if(listView==null)return;
if(listData==null||listData.size()==0){
wualert.setVisibility(View.VISIBLE);
if(first==false){
wualert.setText("抱歉,暂无数据!");
}
}else{
wualert.setVisibility(View.INVISIBLE);
}
listView.setAdapter(adapter);
}
/**
* 当前项操作
* @param position
*/
public void setSelectedValues(int position) {
}
@Override
public void refreshDataUI() {
}
@Override
public void doRefreshData() {
// if (page > PAGE_TOTAL_SIZE) {
// listView.setEndTag(true);
// return;
// }
// try {
// shopListResult = null;
// shopListResult = ApiShopListRequest.ShopListRequest(area, page+"", PAGE_SIZE+"");
// } catch (ServerException e) {
// listView.setErrTag(true);
// } catch (ApiException e) {
// listView.setErrTag(true);
// } catch (UnsupportedEncodingException e) {
// listView.setErrTag(true);
// }
}
}
|
package com.bbb.composite.ribbon.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.bbb.core.ribbon.BaseRibbonConfiguration;
import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ConfigurationBasedServerList;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerList;
/**
* Load balancer class for ProductMicroservice
*
* @author psh111
*
*/
@Configuration
public class ProductMicroserviceRibbonConfiguration extends BaseRibbonConfiguration {
private String productMicroservice = "product-microservice";
/**
* Bean creation for IClientConfig
*
* @return config obj of IClientConfig
*/
@Bean
public IClientConfig ribbonClientConfig() {
DefaultClientConfigImpl config = new DefaultClientConfigImpl();
config.loadProperties(this.productMicroservice);
return config;
}
@Bean
ServerList<Server> ribbonServerList(IClientConfig config) {
ConfigurationBasedServerList serverList = new ConfigurationBasedServerList();
serverList.initWithNiwsConfig(config);
return serverList;
}
}
|
package com.rx.mvvm.aop.anno;
import org.greenrobot.greendao.AbstractDao;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by wuwei
* 2021/3/22
* 佛祖保佑 永无BUG
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DBInit {
String dbName();
Class<? extends AbstractDao<?, ?>>[] daoClasses();
}
|
package edu.uci.ics.sdcl.firefly.report.predictive.montecarlo;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.HashMap;
import edu.uci.ics.sdcl.firefly.report.predictive.DataPoint;
/**
* Represents a sample of questions and attributes of the sample such
* - How many of the questions were oversampled
* - How many of the questions were undersampled
* - How many were not sampled at all
*
*
* @author Christian Adriano
*
*/
public class SampledQuestions {
Integer sampleSize=0;
Double countOf_OversampledQuestions=0.0;
Double countOf_UndersampledQuestions=0.0;
Double countOf_NotSampledQuestions=0.0;
Double total_SampledQuestions=0.0;
Double countOf_OversampledQuestions_bugCovering=0.0;
Double countOf_OversampledQuestions_NonBugCovering=0.0;
Double countOf_UndersampledQuestions_bugCovering=0.0;
Double countOf_UndersampledQuestions_NonBugCovering=0.0;
String top_1_oversampledQuestionID;
String top_2_oversampledQuestionID;
String top_3_oversampledQuestionID;
HashMap<String,Integer> rankOf_OversampledQuestions = new HashMap<String,Integer>();
HashMap<String,Integer> rankOf_UndersampledQuestions = new HashMap<String,Integer>();
Double percent_oversampledQuestions=0.0;
Double percent_undersampledQuestions=0.0;
Double percent_oversampledQuestions_bugCovering=0.0;
Double percent_undersampledQuestions_bugCovering=0.0;
public SampledQuestions(int sampleSize, double countOf_OversampledQuestions, double countOf_UndersampledQuestions,
double countOf_NotSampledQuestions,
double countOf_OversampledQuestions_bugCovering, double countOf_OversampledQuestions_NonBugCovering,
double countOf_UndersampledQuestions_bugCovering, double countOf_UndersampledQuestions_NonBugCovering) {
this.sampleSize = sampleSize;
this.countOf_OversampledQuestions = countOf_OversampledQuestions;
this.countOf_UndersampledQuestions = countOf_UndersampledQuestions;
this.countOf_NotSampledQuestions = countOf_NotSampledQuestions;
this.countOf_OversampledQuestions_bugCovering = countOf_OversampledQuestions_bugCovering;
this.countOf_OversampledQuestions_NonBugCovering = countOf_OversampledQuestions_NonBugCovering;
this.countOf_UndersampledQuestions_bugCovering = countOf_UndersampledQuestions_bugCovering;
this.countOf_UndersampledQuestions_NonBugCovering = countOf_UndersampledQuestions_NonBugCovering;
this.total_SampledQuestions = this.countOf_OversampledQuestions + this.countOf_UndersampledQuestions + this.countOf_NotSampledQuestions;
this.percent_oversampledQuestions = this.countOf_OversampledQuestions / this.total_SampledQuestions;
this.percent_undersampledQuestions = this.countOf_UndersampledQuestions / this.total_SampledQuestions;
this.percent_oversampledQuestions_bugCovering = this.countOf_OversampledQuestions_bugCovering / this.countOf_OversampledQuestions;
this.percent_undersampledQuestions_bugCovering = this.countOf_UndersampledQuestions_bugCovering / this.countOf_UndersampledQuestions;
}
public void setRankedQuestions(String top_1_oversampledQuestionID, String top_2_oversampledQuestionID,
String top_3_oversampledQuestionID){
this.top_1_oversampledQuestionID = top_1_oversampledQuestionID;
this.top_2_oversampledQuestionID = top_2_oversampledQuestionID;
this.top_3_oversampledQuestionID = top_3_oversampledQuestionID;
}
public void addOversampledQuestionRank(String questionID, Integer rank){
this.rankOf_OversampledQuestions.put(questionID, rank);
}
public void addUndersampledQuestionRank(String questionID, Integer rank){
this.rankOf_UndersampledQuestions.put(questionID, rank);
}
/**
* Used to print the content into a file.
* @return
*/
public static String getHeader(){
return("sampleSize, Oversampled Questions, % Oversampled Questions, " +
"BugCovering Oversampled Questions, % BugCovering Oversampled Questions, " +
"Undersampled Questions, % Undersampled Questions, " +
"BugCovering Undersampled Questions, % BugCovering Undersampled Questions, " +
"NonBugCovering Oversampled Questions, NonBugCovering Undersampled Questions, " +
"total_Sampled Questions, Not_Sampled Questions, " +
"top_1_oversampled QuestionID, top_2_oversampled QuestionID, top_3_oversampled QuestionID");
}
public String toString(){
return( this.sampleSize.toString() +","+
this.countOf_OversampledQuestions.toString() +","+
this.percent_oversampledQuestions.toString() +","+
this.countOf_OversampledQuestions_bugCovering.toString() +","+
this.percent_oversampledQuestions_bugCovering.toString() +","+
this.countOf_UndersampledQuestions.toString() + ","+
this.percent_undersampledQuestions.toString() + ","+
this.countOf_UndersampledQuestions_bugCovering.toString() +","+
this.percent_undersampledQuestions_bugCovering.toString() +","+
this.countOf_OversampledQuestions_NonBugCovering.toString() +","+
this.countOf_UndersampledQuestions_NonBugCovering.toString() +","+
this.total_SampledQuestions.toString() +","+
this.countOf_NotSampledQuestions.toString()+","+
this.top_1_oversampledQuestionID +","+
this.top_2_oversampledQuestionID +","+
this.top_3_oversampledQuestionID);
}
}
|
package com.everis.eCine.model;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Entity
@Data
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Salle extends AbstractModel<Long>{
@Column(nullable = false, length = 40)
private int numero;
@Column(nullable = false, length = 40)
private int capacite;
@OneToMany(mappedBy = "salle")
private List<Seance> seances;
@Column(name = "added_date", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP", insertable = false, updatable = false)
private Date addedDate;
}
|
package xml;
import javax.xml.bind.annotation.*;
@XmlRootElement(name = "TestDoc")
@XmlAccessorType(XmlAccessType.FIELD)
public class XMLObject {
@XmlElement(name = "age")
private int age;
@XmlElement(name = "subject")
private String subject;
@XmlElement(name = "name")
private String name;
public void setAge(int age) {
this.age = age;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public String getSubject() {
return subject;
}
public String getName() {
return name;
}
}
|
package com.projects.houronearth.activities.fragments;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.projects.houronearth.R;
import com.projects.houronearth.activities.Preferences.Constants;
import com.projects.houronearth.activities.Preferences.SharedPreferenceManager;
import com.projects.houronearth.activities.adapters.MoreInfoAdapter;
import com.projects.houronearth.activities.dialogs.CustomerPopUp;
import com.projects.houronearth.activities.fragments.profile.ViewProfileFragment;
import com.projects.houronearth.activities.interfaces.AlertMagnetic;
import com.projects.houronearth.activities.internetconnection.CheckInternetConnection;
import com.projects.houronearth.activities.models.MoreInfoModel;
import com.projects.houronearth.activities.models.UserModel;
import com.projects.houronearth.activities.server.ApiClient;
import com.projects.houronearth.activities.server.ApiInterface;
import com.projects.houronearth.activities.server.Urls;
import com.projects.houronearth.activities.utils.RecyclerClickListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* A simple {@link Fragment} subclass.
* Use the {@link MoreInfoFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MoreInfoFragment extends Fragment implements View.OnClickListener, FragmentManager.OnBackStackChangedListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
View view;
private SharedPreferenceManager sharedPreferenceManager;
public MoreInfoFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment MoreInfoFragment.
*/
// TODO: Rename and change types and number of parameters
public static MoreInfoFragment newInstance(String param1, String param2) {
MoreInfoFragment fragment = new MoreInfoFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
UserModel userModel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getContext();
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
sharedPreferenceManager = new SharedPreferenceManager(context, Constants.LoginDetails);
userModel = sharedPreferenceManager.getUserData();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_more_info, container, false);
getActivity().getSupportFragmentManager().addOnBackStackChangedListener(this);
setUprecyclerview();
loadRecyclerView();
loadProfileSnap();
return view;
}
TextView userNameTv, emailTv;
CircleImageView profileImage;
private void loadProfileSnap() {
userNameTv = (TextView) view.findViewById(R.id.userName);
emailTv = (TextView) view.findViewById(R.id.email);
profileImage = (CircleImageView) view.findViewById(R.id.profile_image);
userNameTv.setText(userModel.getName());
emailTv.setText(userModel.getEmail());
Log.e("User Image", userModel.getImage());
if (CheckInternetConnection.checkInternetConnection(context))
Glide.with(context)
.load(userModel.getImage())
.into(profileImage);
view.findViewById(R.id.profileSnapLayout).setOnClickListener(this);
}
private void loadRecyclerView() {
final ArrayList<MoreInfoModel> moreinfoModels = new ArrayList<>();
moreinfoModels.add(new MoreInfoModel(R.drawable.general_information_icon, getString(R.string.general_Information)));
moreinfoModels.add(new MoreInfoModel(R.drawable.how_it_works_icon, getString(R.string.how_it_works)));
moreinfoModels.add(new MoreInfoModel(R.drawable.terms_of_use_icon, getString(R.string.terms_of_use)));
moreinfoModels.add(new MoreInfoModel(R.drawable.company_policies_icon, getString(R.string.company_policies)));
moreinfoModels.add(new MoreInfoModel(R.drawable.rate_us_icon, getString(R.string.rate_app)));
moreinfoModels.add(new MoreInfoModel(R.drawable.about_us_icon, getString(R.string.about_us)));
moreinfoModels.add(new MoreInfoModel(R.drawable.contact_us_icon, getString(R.string.contact_us)));
moreinfoModels.add(new MoreInfoModel(R.drawable.report_icon, getString(R.string.my_report)));
moreinfoModels.add(new MoreInfoModel(R.drawable.ic_logout, getString(R.string.logout)));
MoreInfoAdapter mainMenuRecyclerAdapter = new MoreInfoAdapter(context, moreinfoModels);
recyclerView.setAdapter(mainMenuRecyclerAdapter);
recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
recyclerView.addOnItemTouchListener(new RecyclerClickListener(context,
new RecyclerClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
selectedItemName = moreinfoModels.get(position).getTitle();
switch (position) {
case 0:
key_name = "general_information";
fetchCompanyRelatedInfo();
break;
case 5:
key_name = "about_us";
fetchCompanyRelatedInfo();
break;
case 8:
showLogoutConfirmPopup();
break;
default:
Toast.makeText(context, "Work in progress", Toast.LENGTH_LONG).show();
break;
}
}
}));
}
private void showLogoutConfirmPopup() {
CustomerPopUp.getConfirmDialog(context, "Logout!",
"Are you sure, you want to Logout?",
"Yes", "No", true,
new AlertMagnetic() {
@Override
public void PositiveMethod(final DialogInterface dialog, final int id) {
deleteUserdata();
}
@Override
public void NegativeMethod(DialogInterface dialog, int id) {
}
});
}
private void deleteUserdata() {
sharedPreferenceManager.saveSplashDone(false);
Log.e("DashBoard", "logout");
sharedPreferenceManager.clearData();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.frameLayout, new LoginFragment(), LoginFragment.class.getSimpleName()).commit();
}
RecyclerView recyclerView;
private void setUprecyclerview() {
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
}
String TAG = MoreInfoFragment.class.getSimpleName();
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.profileSnapLayout:
getActivity().getSupportFragmentManager().beginTransaction()
.add(R.id.frameLayout, new ViewProfileFragment(), ViewProfileFragment.class.getSimpleName())
.addToBackStack(TAG).commit();
break;
}
}
private void fetchCompanyRelatedInfo() {
if (CheckInternetConnection.checkInternetConnection(context)) {
calleServer();
} else {
Toast.makeText(context, getResources().getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
}
}
private void calleServer() {
ApiInterface apiService =
ApiClient.getClient(Urls.More_Info_Url, TAG, "More Info ").create(ApiInterface.class);
Call<ResponseBody> call = apiService.getResponse(new HashMap<String, String>());
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String jsonResponse = response.body().string();
Log.e(TAG, "More Info Response " + jsonResponse);
parseMoreInfo(jsonResponse);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
}
String key_name = "", selectedItemName = "";
private void parseMoreInfo(String jsonResponse) {
try {
if (!jsonResponse.equals("null") || !jsonResponse.equals("")) {
JSONArray jsonArray = new JSONArray(jsonResponse);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String type_data = jsonObject.getString(key_name);
getActivity().getSupportFragmentManager().beginTransaction()
.add(R.id.frameLayout, WellnessDataFragment.newInstance(type_data, selectedItemName, ""),
WellnessDataFragment.class.getSimpleName())
.addToBackStack(WellnessDataFragment.class.getSimpleName()).commit();
}
} else {
Toast.makeText(context, "Invalid User Details", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Unknown Error Occured ... please try again later", Toast.LENGTH_SHORT).show();
}
}
Context context;
@Override
public void onBackStackChanged() {
sharedPreferenceManager = new SharedPreferenceManager(context, Constants.LoginDetails);
userModel = sharedPreferenceManager.getUserData();
loadProfileSnap();
}
}
|
package com.cse308.sbuify.playlist;
import com.cse308.sbuify.album.Album;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* Read-only DAO mapped to the playlist_albums view.
*/
@Entity
@Table(name = "playlist_albums")
@IdClass(PlaylistAlbum.PlaylistAlbumPK.class)
public class PlaylistAlbum {
@Id
@NotNull
@ManyToOne
private Playlist playlist;
@Id
@NotNull
@ManyToOne
private Album album;
@NotNull
private LocalDateTime dateSaved;
public PlaylistAlbum() {}
public Playlist getPlaylist() {
return playlist;
}
public Album getAlbum() {
return album;
}
public LocalDateTime getDateSaved() {
return dateSaved;
}
/**
* Primary key for PlaylistAlbum.
*/
public static class PlaylistAlbumPK implements Serializable {
private int playlist;
private int album;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PlaylistAlbumPK that = (PlaylistAlbumPK) o;
if (playlist != that.playlist) return false;
return album == that.album;
}
@Override
public int hashCode() {
int result = playlist;
result = 31 * result + album;
return result;
}
}
}
|
/**
* @author Amith Gopal
*/
package com.example.demo;
/*
* This class represents the parameters of the request body while adding a job to the Job table to the database.
*/
public class AddJobParameters {
private String skills;
private String location;
private String description;
private String role;
private int company_id;
/* Getters and Setters */
public String getSkills() {
return skills;
}
public void setSkills(String skills) {
this.skills = skills;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public int getCompany_id() {
return company_id;
}
public void setCompany_id(int company_id) {
this.company_id = company_id;
}
}
|
package com.bowlong.net.http;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.bowlong.bio2.B2InputStream;
import com.bowlong.net.http.urlcon.HttpUrlConEx;
/**
* @author Canyon
* @version createtime:2015年8月17日 下午10:31:15
*/
public class HttpEx extends HttpUrlConEx {
public static final byte[] readUrl(String url) throws Exception {
InputStream is = openUrl(url);
try {
return readStream(is);
} finally {
is.close();
}
}
public static final byte[] readUrl(String url, byte[] post)
throws Exception {
HttpURLConnection huc = openUrl(url, post);
InputStream is = huc.getInputStream();
try {
return readStream(is);
} finally {
is.close();
huc.disconnect();
}
}
public static final byte[] readUrl(URL url) throws Exception {
InputStream is = openUrl(url);
try {
return readStream(is);
} finally {
is.close();
}
}
public static final InputStream openUrl(String url) throws Exception {
return openUrl(new URL(url));
}
public static HttpURLConnection openUrl(String url, byte[] post)
throws Exception {
URL u = new URL(url);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setDoOutput(true);
huc.setRequestMethod("POST");
huc.setRequestProperty("Content-type", "text/html; charset=utf-8");
huc.setRequestProperty("Connection", "close");
huc.setRequestProperty("Content-Length", String.valueOf(post.length));
huc.getOutputStream().write(post);
huc.getOutputStream().flush();
huc.getOutputStream().close();
return huc;
}
public static final InputStream openUrl(URL url) throws IOException {
return url.openStream();
}
private static byte[] readStream(InputStream is) throws IOException {
return B2InputStream.readStream(is);
}
// private static final ByteOutStream newStream(int size) {
// return new ByteOutStream(size);
// }
}
|
package domein;
import java.util.List;
import persistentie.DoelkaartMapper;
import persistentie.GangkaartMapper;
import persistentie.SpelMapper;
import persistentie.SpelerMapper;
class SpelRepository {
private final SpelMapper spelMapper;
private final SpelerMapper spelerMapper;
private final GangkaartMapper gangkaartMapper;
private final DoelkaartMapper doelkaartMapper;
public SpelRepository() {
spelMapper = new SpelMapper();
spelerMapper = new SpelerMapper();
gangkaartMapper = new GangkaartMapper();
doelkaartMapper = new DoelkaartMapper();
}
public Spel kiesSpel(String spelNaam) {
int spelId = spelMapper.geefSpelId(spelNaam);
int doolhofId = spelMapper.geefDoolhofId(spelId);
int eersteSpeler = spelerMapper.eersteSpelerSpel(spelId);
int spelerAdBeurt = spelMapper.geefSpelerAdBeurt(spelId);
List<Gangkaart> gangkaarten = gangkaartMapper.laadGangkaarten(doolhofId);
Gangkaart[] gangkaartenArray = new Gangkaart[gangkaarten.size()];
int i = 0;
for(Gangkaart g : gangkaarten){
gangkaartenArray[i] = gangkaarten.get(i);
i++;
}
i =0;
List<Speler> spelers = spelerMapper.geefAlleSpelers(spelId);
Speler[] spelerArray = new Speler[spelers.size()];
for(Speler s: spelers){
int[] coord = spelerMapper.getcoordSpeler(eersteSpeler+i);
s.setPositie(gangkaartenArray[(coord[0]*7)+coord[1]]);
s.setBeginDoelkaarten(doelkaartMapper.geefDoelkaartenSpeler(eersteSpeler+i));
s.setDoelkaartenSpeler(doelkaartMapper.geefNogTeZoekenDoelkaartenSpeler(eersteSpeler+i));
spelerArray[i] = spelers.get(i);
i++;
}
Gangkaart vrijeGangkaart = gangkaartMapper.laadVrijeGangkaart(spelId);
return new Spel(spelNaam,spelerArray,spelerArray.length,vrijeGangkaart,new DoolhofSpelbord(gangkaartenArray,vrijeGangkaart),spelerAdBeurt);
}
public String[] geefAlleSpelnamen() {
return spelMapper.geefAlleSpelNamen();
}
public void slaSpelOp(Spel spel) {
int spelnummer = spelMapper.bepaalAantalSpellen() + 1;
spelMapper.slaSpelOp(spel, spelnummer);
int doolhofnr = spelMapper.bepaalDoolhoven() + 1;
spelMapper.slaDoolhofOp(doolhofnr, spelnummer);
int gkId = gangkaartMapper.bepaalAantalGk() + 1;
int dkId = doelkaartMapper.bepaalAantalDk() + 1;
Speler[] spelers = spel.getSpelers();
Gangkaart[][] sb = spel.getSpelbord();
int spelerId = spelerMapper.bepaalAantalSpelers() + 1;
for (Gangkaart[] sb1 : sb) {
for (Gangkaart gk : sb1) {
int[] coordgk = spel.bepaalCoordinaten(gk);
int rij = coordgk[0];
int kolom = coordgk[1];
gangkaartMapper.voegGangkaartToe(gk, gkId, rij, kolom, spel, doolhofnr);
gkId++;
for(Speler s: spelers){
if(gk.equals(s.getPositie())){
spelerMapper.voegToe(s, spelerId, coordgk, spelnummer);
Doelkaart[] dK = s.getBeginDoelkaarten();
for(Doelkaart dkS : dK){
doelkaartMapper.voegDoelkaartToe(dkS, dkId, spelerId, doolhofnr);
dkId++;
}
spelerId++;
}
}
}
}
Gangkaart vrije = spel.getVrijeGangkaart();
gangkaartMapper.voegVrijeGangkaartToe(vrije, gkId, spel,spelnummer);
doolhofnr++;
}
}
|
package ch.epfl.seti.server.custom;
import java.util.concurrent.atomic.AtomicInteger;
import ch.epfl.seti.client.typelib.SInteger;
import ch.epfl.seti.client.typelib.SVoid;
import ch.epfl.seti.server.IInputGenerator;
import ch.epfl.seti.shared.MapTask;
import ch.epfl.seti.shared.Pair;
import ch.epfl.seti.shared.Task;
public class MandelbrotInputGenerator implements IInputGenerator<SInteger, SVoid>{
private AtomicInteger m_counter = new AtomicInteger(0);
int N = 4096;
@Override
public boolean hasNextTask() {
return m_counter.get() < N;
}
@Override
public Task<SInteger, SVoid> nextTask() {
int offset = m_counter.getAndAdd(4);
if (offset >= N) {
m_counter.getAndAdd(-4);
return null;
}
MapTask<SInteger,SVoid> ret = new MapTask<SInteger, SVoid>();
ret.add(new Pair<SInteger, SVoid>(new SInteger(offset), SVoid.UNIT));
return ret;
}
@Override
public boolean executeReduceOnServer() {
return true;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.