text
stringlengths
10
2.72M
package org.lvzr.fast.java.patten.struct.adapter.object; import org.lvzr.fast.java.patten.struct.adapter.Source; import org.lvzr.fast.java.patten.struct.adapter.Targetable; /** * 对象的适配器模式(对象注入) * 基本思路和类的适配器模式相同,只是将Adapter类作修改,这次不继承Source类, * 而是持有Source类的实例,以达到解决兼容性的问题。看图: */ public class AdapterTest { public static void main(String[] args) { Source source = new Source(); Targetable target = new Wrapper(source); target.method1(); target.method2(); } }
package controllers.mappers; import java.util.List; /** * Mapper for union json */ public class UnionJSON { private String mode; private int id; private String name; private List<Integer> mesIds; private List<Integer> unionIds; public String getMode() { return mode; } public int getId() { return id; } public String getName() { return name; } public List<Integer> getMesIds() { return mesIds; } public List<Integer> getUnionIds() { return unionIds; } }
import org.junit.Assert; import org.junit.Test; public class FizzBuzzTest { FizzBuzz fizzBuzz = new FizzBuzz(); @Test public void fizzBuzzOne(){ Assert.assertEquals("1",fizzBuzz.convert(1)); } @Test public void fizzBuzzTwo(){ Assert.assertEquals("2",fizzBuzz.convert(2)); } @Test public void fizzBuzzThree(){ Assert.assertEquals("Fizz",fizzBuzz.convert(3)); } @Test public void fizzBuzzFour(){ Assert.assertEquals("4",fizzBuzz.convert(4)); } @Test public void fizzBuzzFive(){ Assert.assertEquals("Buzz",fizzBuzz.convert(5)); } @Test public void fizzBuzzSix(){ Assert.assertEquals("Fizz",fizzBuzz.convert(6)); } @Test public void fizzBuzzSeven(){ Assert.assertEquals("7",fizzBuzz.convert(7)); } @Test public void fizzBuzzEight(){ Assert.assertEquals("8",fizzBuzz.convert(8)); } @Test public void fizzBuzzNine(){ Assert.assertEquals("Fizz",fizzBuzz.convert(9)); } @Test public void fizzBuzz(){ Assert.assertEquals("FizzBuzz",fizzBuzz.convert(30)); } }
package aula3exercicio7; public class Calculos { // Mostra os resultados public static void showResults(int [] dados) { int media = media(dados); int impares = isImpar(dados); Leitura.print("================="); Leitura.print("Media: " + media); Leitura.print("================="); Leitura.print("Impar: " + impares); } // Verifica se o numero é impar public static int isImpar(int [] dados) { int impar = 0; for(int i = 0; i < dados.length; i++) { if(dados[i] % 2 != 0) { impar++; } } return impar; } // Soma os valores do array public static int media(int [] dados) { int soma = 0, media = 0; for(int i = 0; i < dados.length; i++) { soma += dados[i]; } media = soma / dados.length; return media; } // Se o numero é negativo solicita que informe novamente public static int isNegative(int dados) { int positiveNumber = dados; while(positiveNumber < 0) { System.out.println("Informe apenas números positivos;"); positiveNumber = Leitura.lerInt("Informe novamente: "); } return positiveNumber; } // Verifica se o numero é positivo public static boolean checkPositiveNumber(int dados) { if(dados < 0) { return false; } else { return true; } } }
package application; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateFormatterObject { public static void main(String[] args) { String dateString = "Sat Nov 10 01:06:16 GMT+05:30 2018"; SimpleDateFormat originalFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); try { Date sDate = originalFormat.parse(dateString); System.out.println(sDate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss"); Date date = new Date(); String date1 = dateFormatter.format(date); System.out.println(date1); } }
package rs.ac.su.vts.vp.stopper; import android.content.Context; import android.database.ContentObserver; import android.media.AudioManager; import android.os.Handler; import android.util.Log; public class VolumeChangeObserver extends ContentObserver { int prevVolume; Context context; int keyPressed=0; MainActivity mainA; public VolumeChangeObserver(Context c, Handler handler, MainActivity mainActivity) { super(handler); context=c; this.mainA=mainActivity; AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); prevVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC); } @Override public boolean deliverSelfNotifications() { return super.deliverSelfNotifications(); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC); int diff= prevVolume -currentVolume; MainActivity.statikTest(); if(diff>0) { Log.d("stopper_verbose","vol down!"); keyPressed=2; prevVolume =currentVolume; mainA.onResetClick(); } else if(diff<0) { Log.d("stopper_verbose", "vol up!"); keyPressed=1; prevVolume =currentVolume; mainA.onStartClick(); } } public void setKeyPressed() { keyPressed=0; } public int getKeyPressed() { return keyPressed; } }
package io.peppermint100.server.controller; import io.peppermint100.server.constant.Controller; import io.peppermint100.server.entity.Request.User.LoginRequest; import io.peppermint100.server.entity.Request.User.SignUpRequest; import io.peppermint100.server.entity.Request.User.UpdateAddressRequest; import io.peppermint100.server.entity.Request.User.UpdateUserInfoRequest; import io.peppermint100.server.entity.Response.BasicResponse; import io.peppermint100.server.entity.Response.TokenContainingResponse; import io.peppermint100.server.entity.Response.User.MeResponse; import io.peppermint100.server.entity.Response.User.TokenAndUser; import io.peppermint100.server.entity.Response.User.UserInfo; import io.peppermint100.server.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @PostMapping("/login") public ResponseEntity<TokenContainingResponse> login(@RequestBody LoginRequest loginRequest) throws Exception { TokenAndUser tokenAndUser = userService.loginAndGenerateToken(loginRequest); TokenContainingResponse response = new TokenContainingResponse(HttpStatus.OK, Controller.LOG_IN_SUCCESS_MESSAGE, tokenAndUser.getToken(), tokenAndUser.getUser()); return new ResponseEntity<>(response, HttpStatus.OK); } @PostMapping("/signup") public ResponseEntity<BasicResponse> signUp(@RequestBody SignUpRequest signUpRequest) { userService.signUp(signUpRequest); BasicResponse response = new BasicResponse(HttpStatus.OK, Controller.SIGN_UP_SUCCESS_MESSAGE); return new ResponseEntity<>(response, HttpStatus.OK); } @PostMapping("/me") public ResponseEntity<MeResponse> me(){ UserInfo user = userService.me(); MeResponse response = new MeResponse(HttpStatus.OK, Controller.LOG_IN_SUCCESS_MESSAGE, user); return new ResponseEntity<>(response, HttpStatus.OK); } @PutMapping("/{userId}/update-info") public ResponseEntity<BasicResponse> updateUserInfo( @PathVariable("userId") Long userId, @RequestBody UpdateUserInfoRequest updateUserInfoRequest ){ userService.updateUserInfo(userId, updateUserInfoRequest); BasicResponse response = new BasicResponse(HttpStatus.OK, Controller.UPDATE_USER_INFO_SUCCESS_MESSAGE); return new ResponseEntity<>(response, HttpStatus.OK); } @PostMapping("/update-address") public ResponseEntity<BasicResponse> updateAddress( @RequestBody UpdateAddressRequest updateAddressRequest ){ userService.updateAddress(updateAddressRequest); BasicResponse response = new BasicResponse(HttpStatus.OK, Controller.UPDATE_ADDRESS_SUCCESS_MESSAGE); return new ResponseEntity<>(response, HttpStatus.OK); } }
package org.terasoluna.gfw.web.view; import java.beans.PropertyDescriptor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanWrapper; import org.springframework.beans.PropertyAccessorFactory; import org.springframework.core.convert.TypeDescriptor; import org.springframework.util.ClassUtils; /** * EL functions for form object. */ public class FormFunctions { /** * status of present Joda-Time. */ private static final boolean jodaTimePresent = ClassUtils.isPresent("org.joda.time.ReadableInstant", FormFunctions.class.getClassLoader()); /** * additional simple value types. */ private static final List<Class<?>> additionalSimpleValueTypes; /** * initialize class. */ static { if (jodaTimePresent) { ClassLoader classLoader = FormFunctions.class.getClassLoader(); Class<?> readableInstantClass = ClassUtils.resolveClassName("org.joda.time.ReadableInstant", classLoader); Class<?> readablePartialClass = ClassUtils.resolveClassName("org.joda.time.ReadablePartial", classLoader); additionalSimpleValueTypes = Arrays.asList(readableInstantClass, readablePartialClass); } else { additionalSimpleValueTypes = Collections.emptyList(); } } /** * Fetch the "active path list" of specified form object. * <p> * <strong>[about "access path list"]</strong> * <ul> * <li>active path is access path of spring "form:xxx" tag.</li> * <li>active path list is contains all not-null properties.</li> * </ul> * </p> * * @param form * target form object for fetch. * @return "active path list" of specified form object. */ public static List<String> getPaths(Object form) { if (form == null) { return Collections.emptyList(); } List<String> paths = getPaths(null, form); return paths; } public static boolean isCollection(Object object) { if (object == null) { return false; } TypeDescriptor beanTypeDescriptor = TypeDescriptor.forObject(object); return beanTypeDescriptor.isCollection() || beanTypeDescriptor.isArray(); } public static boolean isMap(Object object) { if (object == null) { return false; } TypeDescriptor beanTypeDescriptor = TypeDescriptor.forObject(object); return beanTypeDescriptor.isMap(); } public static boolean isSimpleValueType(Object object) { if (object == null) { return false; } return isSimpleValueType(object.getClass()); } /** * Fetch the "active path list" of specified object(JavaBean or Simple value * object or Collection or Map). * * @param basePath * base path of specified object.(case of root object is null) * @param object * target object for fetch. * @return "active path list" of specified object. */ private static List<String> getPaths(String basePath, Object object) { BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object); TypeDescriptor beanTypeDescriptor = TypeDescriptor.forObject(object); List<String> paths = new ArrayList<String>(); if (beanTypeDescriptor.isCollection()) { collectPathsOfCollection(paths, basePath, (Collection<?>) object); } else if (beanTypeDescriptor.isArray()) { Collection<?> collection = Arrays.asList(beanWrapper.convertIfNecessary(object, Object[].class)); collectPathsOfCollection(paths, basePath, collection); } else if (beanTypeDescriptor.isMap()) { collectPathsOfMap(paths, basePath, (Map<?, ?>) object); } else if (isSimpleValueType(beanWrapper.getWrappedClass())) { paths.add(basePath); } else { collectPathsOfBeanProperties(paths, basePath, beanWrapper); } return paths; } /** * collect "active path list" of specified bean properties. * * @param paths * storing list of active path of in the bean. * @param basePath * base path name of specified bean(bean wrapper). * @param beanWrapper * wrapper object of specified bean. */ private static void collectPathsOfBeanProperties(List<String> paths, String basePath, BeanWrapper beanWrapper) { PropertyDescriptor[] beanPropertyDescriptors = beanWrapper.getPropertyDescriptors(); for (PropertyDescriptor beanPropertyDescriptor : beanPropertyDescriptors) { String propertyName = beanPropertyDescriptor.getName(); if (!beanWrapper.isReadableProperty(propertyName) || !beanWrapper.isWritableProperty(propertyName)) { continue; } Object value = beanWrapper.getPropertyValue(propertyName); if (value == null) { continue; } String path = null; if (basePath == null) { path = propertyName; } else { path = basePath + "." + propertyName; } TypeDescriptor propertyTypeDescriptor = beanWrapper.getPropertyTypeDescriptor(propertyName); if (propertyTypeDescriptor.isCollection()) { collectPathsOfCollection(paths, path, (Collection<?>) value); } else if (propertyTypeDescriptor.isArray()) { Collection<?> collection = Arrays.asList(beanWrapper.convertIfNecessary(value, Object[].class)); collectPathsOfCollection(paths, path, collection); } else if (propertyTypeDescriptor.isMap()) { collectPathsOfMap(paths, path, (Map<?, ?>) value); } else { collectPathsOfObject(paths, path, "", value); } } } /** * collect "active path list" of specified element into collection. * * @param paths * storing list of active path of in the specified collection. * @param basePath * base path name of specified collection. * @param collection * collection object. */ private static void collectPathsOfCollection(List<String> paths, String basePath, Collection<?> collection) { int index = 0; for (Object elementValue : collection) { if (elementValue != null) { String pathKey = "[" + index + "]"; collectPathsOfObject(paths, basePath, pathKey, elementValue); } index++; } } /** * collect "active path list" of specified entry into map. * * @param paths * storing list of active path of in the specified map. * @param basePath * base path name of specified map. * @param map * map object. */ private static void collectPathsOfMap(List<String> paths, String basePath, Map<?, ?> map) { for (Entry<?, ?> entry : map.entrySet()) { if (entry.getValue() != null) { String pathKey = "[" + entry.getKey() + "]"; collectPathsOfObject(paths, basePath, pathKey, entry.getValue()); } } } /** * collect "active path list" of specified object. * * @param paths * storing list of active path of in the specified object. * @param basePath * base path name of specified object. * @param pathKey * key's value of in the base path.(collection of array is * "[index]". map is "[key]", simple value is "") * @param object * target object. */ private static void collectPathsOfObject(List<String> paths, String basePath, String pathKey, Object object) { String path = basePath + pathKey; if (isSimpleValueType(object.getClass())) { paths.add(path); } else { List<String> nestedPaths = getPaths(path, object); if (!nestedPaths.isEmpty()) { paths.addAll(nestedPaths); } } } /** * Check if the given type represents a "simple" value type: a primitive, a * String or other CharSequence, a Number, a Date, a URI, a URL, a Locale or * a Class. And if present,Joda Time object. * * @param targetClass * the type to check * @return whether the given type represents a "simple" value type */ private static boolean isSimpleValueType(Class<?> targetClass) { if (BeanUtils.isSimpleValueType(targetClass)) { return true; } if (additionalSimpleValueTypes.isEmpty()) { return false; } for (Class<?> additionalSimpleValueType : additionalSimpleValueTypes) { if (additionalSimpleValueType.isAssignableFrom(targetClass)) { return true; } } return false; } }
/* */ package datechooser.beans.editor; /* */ /* */ import javax.swing.JComponent; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public abstract class VisualEditorCashed /* */ extends VisualEditor /* */ { /* */ public VisualEditorCashed() {} /* */ /* 26 */ private JComponent editor = null; /* */ /* */ protected JComponent getEditorCash() { /* 29 */ return this.editor; /* */ } /* */ /* */ protected void setEditorCash(JComponent editor) { /* 33 */ this.editor = editor; /* */ } /* */ /* */ public JComponent getCustomEditor() { /* 37 */ if (getEditorCash() == null) { /* 38 */ setEditorCash(createEditor()); /* */ } /* 40 */ return getEditorCash(); /* */ } /* */ } /* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/datechooser/beans/editor/VisualEditorCashed.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
package com.netflix.governator.auto.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.netflix.governator.auto.conditions.OnSystemCondition; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Conditional(OnSystemCondition.class) @Deprecated /** * @deprecated Moved to Karyon3 */ public @interface ConditionalOnSystem { String name(); String value(); }
package com.rsm.yuri.projecttaxilivre.adddialog; /** * Created by yuri_ on 10/11/2017. */ public class AddDialogInteractorImpl implements AddDialogInteractor { AddDialogRepository addDialogRepository; public AddDialogInteractorImpl(AddDialogRepository addDialogRepository) { this.addDialogRepository = addDialogRepository; } @Override public void add(String key, String value) { addDialogRepository.add(key, value); } }
package exercicios; import java.util.Scanner; public class Exercicio02 { public static void main(String[] args) { Scanner entrada = new Scanner(System.in); double nota1; double nota2; double media; System.out.println("Digite a nota1 do aluno:"); nota1 = entrada.nextDouble(); System.out.println("Digite a nota2 do aluno:"); nota2 = entrada.nextDouble(); media = (nota1 + nota2)/2; System.out.println("**************"); System.out.println("A nota final do aluno é: " + media); entrada.close(); } }
package com.tencent.mm.plugin.appbrand; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.text.TextUtils; import android.widget.Toast; import com.tencent.mm.g.a.bs; import com.tencent.mm.g.a.qu; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.ah.a; import com.tencent.mm.plugin.appbrand.config.WxaAttributes; import com.tencent.mm.plugin.appbrand.s.j; import com.tencent.mm.plugin.base.model.c; import com.tencent.mm.plugin.report.f; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.sdk.a.b; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.ah; import com.tencent.mm.sdk.platformtools.s; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.y.i; import com.tencent.tmassistantsdk.storage.table.DownloadSettingTable$Columns; import java.util.HashSet; import java.util.Set; public final class u extends a { public final int getType() { return 1; } public final void l(Context context, Intent intent) { Object obj; h.mEJ.a(443, 2, 1, false); String wO = c.wO(s.j(intent, "id")); String wO2 = c.wO(s.j(intent, "ext_info")); Object j = s.j(intent, "token"); int a = s.a(intent, "ext_info_1", 0); if (TextUtils.isEmpty(wO) || TextUtils.isEmpty(wO2) || TextUtils.isEmpty(j)) { x.e("MiroMsg.WxaShortcutEntry", "jump to Wxa failed, username or appId or token is null or nil."); obj = null; } else if (i.gr(wO)) { String str; StringBuilder stringBuilder = new StringBuilder(); g.Eg(); if (!j.equals(c.bU(wO2, stringBuilder.append(com.tencent.mm.kernel.a.Df()).toString()))) { SharedPreferences sharedPreferences = ad.getContext().getSharedPreferences("app_brand_global_sp", 0); if (sharedPreferences == null) { x.w("MiroMsg.WxaShortcutEntry", "jump to Wxa failed, sp is null."); obj = null; } else { Set<String> stringSet = sharedPreferences.getStringSet("uin_set", new HashSet()); if (stringSet == null || stringSet.isEmpty()) { x.w("MiroMsg.WxaShortcutEntry", "jump to Wxa failed, uin set is null or nil."); obj = null; } else { Set hashSet = new HashSet(); for (String str2 : stringSet) { hashSet.add(c.bU(wO2, str2)); } if (!hashSet.contains(j)) { x.e("MiroMsg.WxaShortcutEntry", "jump to Wxa failed, illegal token(%s).", new Object[]{j}); obj = null; } } } } if (b.chp() || a != 1) { qu quVar = new qu(); quVar.cbq.appId = wO2; quVar.cbq.userName = wO; quVar.cbq.cbt = a; quVar.cbq.scene = 1023; quVar.cbq.cbx = true; quVar.cbq.context = context; quVar.cbq.cby = false; com.tencent.mm.sdk.b.a.sFg.m(quVar); if (quVar.cbr.cbD) { x.i("MiroMsg.WxaShortcutEntry", "open wxa with id : %s", new Object[]{wO}); } else if (a == 1) { Toast.makeText(context, j.app_brand_debug_app_from_share_card_can_not_open, 0).show(); } else if (a == 2) { Toast.makeText(context, j.app_brand_not_beta_pkg, 0).show(); } Object j2 = s.j(intent, "digest"); if (!TextUtils.isEmpty(j2)) { WxaAttributes rR = ((com.tencent.mm.plugin.appbrand.n.c) g.l(com.tencent.mm.plugin.appbrand.n.c.class)).rR(wO); if (rR == null) { x.e("MiroMsg.WxaShortcutEntry", "no such WeApp(%s)", new Object[]{wO}); obj = 1; } else { if (!j2.equals(com.tencent.mm.a.g.u((rR.field_nickname + rR.field_roundedSquareIconURL + rR.field_brandIconURL + rR.field_bigHeadURL).getBytes()))) { x.i("MiroMsg.WxaShortcutEntry", "update shortcut for wxa(%s)", new Object[]{wO}); if (context == null) { x.e("MicroMsg.AppBrandShortcutManager", "remove fail, context or username is null."); } else if (intent == null) { x.e("MicroMsg.AppBrandShortcutManager", "remove fail, intent is null"); } else { bs bsVar = new bs(); bsVar.bJc.username = wO; com.tencent.mm.sdk.b.a.sFg.m(bsVar); if (bsVar.bJd.bJe == null) { x.e("MicroMsg.AppBrandShortcutManager", "no such WeApp(%s)", new Object[]{wO}); } else { str2 = TextUtils.isEmpty(bsVar.bJd.nickname) ? wO : bsVar.bJd.nickname; Intent intent2 = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT"); intent2.putExtra("android.intent.extra.shortcut.NAME", str2); intent2.putExtra("duplicate", false); intent2.putExtra("android.intent.extra.shortcut.INTENT", intent); com.tencent.mm.plugin.base.model.b.p(context, intent2); x.i("MicroMsg.AppBrandShortcutManager", "remove shortcut %s", new Object[]{wO}); } } ah.i(new 1(this, context, wO, a), 1000); } } } intent.putExtra(DownloadSettingTable$Columns.TYPE, 0); intent.putExtra("id", ""); obj = 1; } else { x.i("MiroMsg.WxaShortcutEntry", "can not open testing WeApp in released WeChat."); obj = null; } } else { x.e("MiroMsg.WxaShortcutEntry", "jump to Wxa failed, username %s invalid ", new Object[]{wO}); f.mDy.a(647, 1, 1, false); obj = null; } if (obj == null) { h.mEJ.a(443, 3, 1, false); } } }
package evilp0s; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 文件名及文件路径相关的操作 */ public class FilePathUtil { /** * 判断是否符是合法的文件路径 * * @param path * @return */ public static boolean legalFile(String path) { //下面的正则表达式有问题 String regex = "[a-zA-Z]:(?:[/][^/:*?\"<>|.][^/:*?\"<>|]{0,254})+"; //String regex ="^([a-zA-z]:)|(^\\.{0,2}/)|(^\\w*)\\w([^:?*\"><|]){0,250}"; return RegUtil.isMatche(commandPath(path), regex); } /** * 返回一个通用的文件路径 * * @param file * @return * @Summary windows中路径分隔符是\在linux中是/但windows也支持/方式 故全部使用/ */ public static String commandPath(String file) { return file.replaceAll("\\\\", "/").replaceAll("//", "/"); } /** * 返回相一个目录的对于本身的相对父目录 * * @param file * @return * @exmaple 当进入目录test/test/时他本身的相对于当前目录的路径为../../ */ public static String getParentPath(String file) { if (file.indexOf("/") != -1) { String temp = null; Pattern p = Pattern.compile("[/]+"); Matcher m = p.matcher(file); int i = 0; while (m.find()) { temp = m.group(0); i += temp.length(); } String parent = ""; for (int j = 0; j < i; j++) { parent += "../"; } return parent; } else { return "./"; } } }
package com.tencent.mm.plugin.p; import com.tencent.mm.ak.o; import com.tencent.mm.kernel.g; import com.tencent.mm.model.p; import com.tencent.mm.plugin.t.a.a; import com.tencent.mm.storage.bc; public final class b extends p { private static b knx; private b() { super(o.class); } public static synchronized b aWB() { b bVar; synchronized (b.class) { if (knx == null) { knx = new b(); } bVar = knx; } return bVar; } public static bc FY() { g.Eg().Ds(); return ((a) g.l(a.class)).FY(); } }
package sample.service; import java.util.ArrayList; import java.util.List; public class Pensja{ public SW sw=new SW(); public Result result(RandomNumbers typed,RandomNumbers winning){ List<Integer> listTyped=new ArrayList<>(typed.getResult()); List<Integer> listWinning=new ArrayList<>(winning.getResult()); Result result=new Result(); for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ if(listTyped.get(i)==listWinning.get(j))result.result++; } } if(typed.getPlus()==winning.getPlus())result.plus=true; return result; } public int playManyTimes(int howMany){ int price=howMany*-5; RandomNumbers typed=new RandomNumbers(); RandomNumbers winning=new RandomNumbers(); Result result; for(int i=0;i<howMany;i++){ typed.fill(); winning.fill(); //System.out.println(typed.getResult()+" plus "+typed.getPlus()); //System.out.println(winning.getResult()+" plus "+winning.getPlus()); result=result(typed,winning); sw.fill(result.price()); //System.out.println(result.price()); price+=result.price(); typed.clear(); winning.clear(); result.clear(); } return price; } }
package VSMBinaryFeatureVectors; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.LinkedHashMap; import java.util.Set; import VSMConstants.VSMContant; public class SerializeFeatureVectorBean { private static LinkedHashMap<String, Integer> countMap; private static int count; private static int fileIdx; /* * No args constructor */ public SerializeFeatureVectorBean() { countMap = new LinkedHashMap<String, Integer>(); count = 0; } /* * Constructor with arguments, fetch the count map and send it to this * constructor, so that the count can start making files from where we left * off in the previous iteration */ public SerializeFeatureVectorBean(LinkedHashMap<String, Integer> countMap) { SerializeFeatureVectorBean.countMap = countMap; count = 0; } public boolean serializeVectorBean(FeatureVectorBean vectorBean) { boolean flag = false; Set<String> labels = countMap.keySet(); /* * If the map already contains the label then get the count variable */ if (labels.contains(vectorBean.getLabel())) { count = countMap.get(vectorBean.getLabel()); count += 1; } else { count = 1; } /* * The put method replaces the value of the existing key */ countMap.put(vectorBean.getLabel(), count); File file = null; if (count <= 30000) { file = new File(VSMContant.BINARY_FEATURE_VECTORS + vectorBean.getLabel() + "/" + vectorBean.getLabel() + "_1"); } else if (count <= 60000) { file = new File(VSMContant.BINARY_FEATURE_VECTORS + vectorBean.getLabel() + "/" + vectorBean.getLabel() + "_2"); } else if (count <= 90000) { file = new File(VSMContant.BINARY_FEATURE_VECTORS + vectorBean.getLabel() + "/" + vectorBean.getLabel() + "_3"); } else if (count <= 120000) { file = new File(VSMContant.BINARY_FEATURE_VECTORS + vectorBean.getLabel() + "/" + vectorBean.getLabel() + "_4"); } else if (count <= 150000) { file = new File(VSMContant.BINARY_FEATURE_VECTORS + vectorBean.getLabel() + "/" + vectorBean.getLabel() + "_5"); } else if (count <= 180000) { file = new File(VSMContant.BINARY_FEATURE_VECTORS + vectorBean.getLabel() + "/" + vectorBean.getLabel() + "_6"); } else if (count <= 210000) { file = new File(VSMContant.BINARY_FEATURE_VECTORS + vectorBean.getLabel() + "/" + vectorBean.getLabel() + "_7"); } else if (count <= 240000) { file = new File(VSMContant.BINARY_FEATURE_VECTORS + vectorBean.getLabel() + "/" + vectorBean.getLabel() + "_8"); } else if (count <= 270000) { file = new File(VSMContant.BINARY_FEATURE_VECTORS + vectorBean.getLabel() + "/" + vectorBean.getLabel() + "_9"); } else if (count <= 300000) { file = new File(VSMContant.BINARY_FEATURE_VECTORS + vectorBean.getLabel() + "/" + vectorBean.getLabel() + "_10"); } else { System.out.println("**Done***"); flag = true; } if (file != null) { if (!file.exists()) { file.mkdirs(); fileIdx = 1; } /* * The .ser file name */ String filename = file.getAbsolutePath() + "/" + vectorBean.getLabel() + "_" + fileIdx + ".ser"; FileOutputStream fos = null; ObjectOutputStream out = null; try { fos = new FileOutputStream(filename, false); out = new ObjectOutputStream(fos); out.writeObject(vectorBean); fileIdx++; out.close(); fos.close(); } catch (IOException ex) { System.err.println("***File name too large***"); } } else { System.out.println("****Done no more serialization***"); } return flag; } }
package com.canby.factory.abstractFactory; import com.canby.factory.abstractFactory.model.Car; import com.canby.factory.abstractFactory.model.ford.Falcon; import com.canby.factory.abstractFactory.model.ford.Fiesta; import com.canby.factory.abstractFactory.model.ford.Focus; /** * Created by acanby on 28/10/2014. */ public class FordFactory implements AbstractCarFactory { @Override public Car createSmallCar() { return new Fiesta(); } @Override public Car createMediumCar() { return new Focus(); } @Override public Car createLargeCar() { return new Falcon(); } }
import com.fasterxml.jackson.databind.ObjectMapper; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; import java.io.IOException; import java.util.*; public class MosMetroParser { private static Map<String, List<String>> stations = new LinkedHashMap<>(); private static Map<String, String> linesItem; private static List<Map> lines = new ArrayList<>(); private static String[] lineColors = {"red", "green", "blue", "blue", "brown", "orange", "violet", "yellow", "grey", "green", "blue", "blue", "pink"}; private static LinkedHashSet<Map> linesSet = new LinkedHashSet<>(); private static Map<String, Object> mosMetro = new LinkedHashMap<>(); private static List<List> connections = new ArrayList<>(); public static void getMosMetro() throws IOException { Document page = Jsoup.connect("https://ru.wikipedia.org/wiki/Список_станций_Московского_метрополитена").get(); Element tableBody = page.select("tbody").get(3); Elements elements = tableBody.select("tr").next(); stationsAndLines(tableBody); connections.addAll(connectionsMetod(tableBody,page)); for (Element el : elements) { linesItemMetod(el); for (String key : linesItem.keySet()) { linesSet.add(linesItemMetod(el)); } } lines.addAll(linesSet); mosMetro.put("stations", stations); mosMetro.put("lines", lines); mosMetro.put("connections", connections); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File("src/main/resources/map.json"), mosMetro); } private static Map stationsAndLines(Element tbody) { final List[] list = new List[]{new ArrayList<>()}; Elements elements = tbody.select("tr").next(); elements.stream().filter(element -> !element.hasClass("shadow")) .map(element -> { String lineNumberString; Element lineNumber = element.select("span[class=sortkey]").get(0); Element station = element.select("a").get(1); lineNumberString = lineNumber.text(); if (element.select("td").get(0).select("span").size() > 3){ lineNumberString = element.select("span[class=sortkey]").get(1).text(); station = element.select("a").get(2); } if (!stations.containsKey(lineNumberString)) { list[0] = new ArrayList<>(); } list[0].add(station.text()); return lineNumberString; }).forEach(key -> stations.put(key, list[0])); addStation(stations); return stations; } private static void addStation(Map<String, List<String>> map) { for (int i = 1; i < map.get("11").size(); i++) { if (map.containsKey("8А")) { map.get("8А").add(map.get("11").get(i)); } } } private static Map linesItemMetod(Element tr) { linesItem = new LinkedHashMap<>(); String[] keys = {"number", "name", "color"}; String lineNumber; if (!tr.hasClass("shadow")) { Element td = tr.select("td").get(0); Element elSpanes = td.select("span").get(1); lineNumber = td.select("span[class=sortkey]").get(0).text(); String s = elSpanes.attr("title"); linesItem.put(keys[0], lineNumber); linesItem.put(keys[1], s); switch (td.attr("style")) { case "background:#EF161E": linesItem.put(keys[2], lineColors[0]); break; case "background:#2DBE2C": linesItem.put(keys[2], lineColors[1]); break; case "background:#0078BE": linesItem.put(keys[2], lineColors[2]); break; case "background:#00BFFF": linesItem.put(keys[2], lineColors[3]); break; case "background:#8D5B2D": linesItem.put(keys[2], lineColors[4]); break; case "background:#ED9121": linesItem.put(keys[2], lineColors[5]); break; case "background:#800080": linesItem.put(keys[2], lineColors[6]); break; case "background:#FFD702": linesItem.put(keys[2], lineColors[7]); break; case "background:#999999": linesItem.put(keys[2], lineColors[8]); break; case "background:#99CC00": linesItem.put(keys[2], lineColors[9]); break; case "background:#82C0C0": linesItem.put(keys[2], lineColors[10]); break; case "background:#A1B3D4": linesItem.put(keys[2], lineColors[11]); break; case "background:#DE64A1": linesItem.put(keys[2], lineColors[12]); break; case "background:background-color: #FFD702;" + " background-image:" + " -moz-linear-gradient(top, #FFD702, #82C0C0);" + " background-image: -o-linear-gradient(top, #FFD702, #82C0C0);" + " background-image: -webkit-gradient(linear, left top, left bottom, from(#FFD702)," + " to(#82C0C0));": linesItem.put(keys[2], lineColors[7]); break; } } return linesItem; } private static List connectionsMetod(Element tbody, Document page) throws IOException { Map<String,List<String>> allStatioons = new LinkedHashMap<>(); List<List> connectionListMetod = new ArrayList<>(); List<Map> oneConnection; HashSet<String> selection = new HashSet<>(); TreeMap<String, String> oneItemOfConnectionMap; String[] keyString = {"line", "station"}; Elements trs = tbody.select("tr").next(); allStatioons.putAll(stationsAndLinesForConection(tbody)); allStatioons.putAll(addMCK(page)); allStatioons.putAll(addMono(page)); for (Element element : trs) { boolean selectionBoolean = true; oneItemOfConnectionMap = new TreeMap<>(); if (!element.hasClass("shadow")) { String lineNumber = element.select("span[class=sortkey]").get(0).text(); String station = element.select("a").get(1).text(); oneConnection = new ArrayList<>(); if (element.select("td").get(0).select("span").size() > 3) { station = element.select("a").get(2).text(); oneItemOfConnectionMap.put(keyString[0], lineNumber); oneItemOfConnectionMap.put(keyString[1], station); oneConnection.add(oneItemOfConnectionMap); oneItemOfConnectionMap = new TreeMap<>(); lineNumber = element.select("span[class=sortkey]").get(1).text(); oneItemOfConnectionMap.put(keyString[0], lineNumber); oneItemOfConnectionMap.put(keyString[1], station); oneConnection.add(oneItemOfConnectionMap); } else { oneItemOfConnectionMap.put(keyString[0], lineNumber); oneItemOfConnectionMap.put(keyString[1], station); oneConnection.add(oneItemOfConnectionMap); } selection.add(lineNumber); Element td = element.select("td").get(3); if (!td.attr("data-sort-value").equals("Infinity")) { Elements spans = td.select("span"); String connectLineNumber; for (Element span : spans) { if (!span.text().equals("")) { oneItemOfConnectionMap = new TreeMap<>(); connectLineNumber = span.text(); oneItemOfConnectionMap.put(keyString[0], connectLineNumber); if (selection.contains(connectLineNumber)) { selectionBoolean = false; } continue; } if (!span.attr("title").equals("")){ for (String st : allStatioons.get(oneItemOfConnectionMap.get(keyString[0]))){ if (span.attr("title").contains(st)){ oneItemOfConnectionMap.put(keyString[1],st); } } } oneConnection.add(oneItemOfConnectionMap); } if (selectionBoolean) { connectionListMetod.add(oneConnection); } } } } return connectionListMetod; } private static Map stationsAndLinesForConection(Element tbody) { Map<String, List<String>> allStations = new LinkedHashMap<>(); final List[] list = new List[]{new ArrayList<>()}; Elements elements = tbody.select("tr").next(); elements.stream() .map(element -> { String lineNumberString; Element lineNumber = element.select("span[class=sortkey]").get(0); Element station = element.select("a").get(1); lineNumberString = lineNumber.text(); if (element.select("td").get(0).select("span").size() > 3){ lineNumberString = element.select("span[class=sortkey]").get(1).text(); station = element.select("a").get(2); } if (!allStations.containsKey(lineNumberString)) { list[0] = new ArrayList<>(); } list[0].add(station.text()); return lineNumberString; }).forEach(key -> allStations.put(key, list[0])); addStation(allStations); return allStations; } private static Map addMCK(Document page){ Element element = page.select("tbody").get(5); Map<String, List<String>> mono = new LinkedHashMap<>(); List<String> list = new ArrayList<>(); Elements tr = element.select("tr"); tr.stream().filter(element1 -> element1 != tr.get(1)) .map(el -> { String lineNumberString; Element lineNumber = el.select("span").get(0); Element station = el.select("a").get(1); lineNumberString = lineNumber.text(); list.add(station.text()); return lineNumberString; }).forEach(key -> mono.put(key, list)); return mono; } private static Map addMono(Document page){ Element element = page.select("tbody").get(4); Map<String, List<String>> mono = new LinkedHashMap<>(); List<String> list = new ArrayList<>(); Elements tr = element.select("tr").next().next(); tr.stream() .map(el -> { String lineNumberString; Element lineNumber = el.select("span").get(0); Element station = el.select("a").get(1); lineNumberString = lineNumber.text(); list.add(station.text()); return lineNumberString; }).forEach(key -> mono.put(key, list)); return mono; } }
package com.porfolio.service.configuration; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.porfolio.service.model.AWSCredential; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; @Configuration public class AWSConfiguration { @Autowired private AWSCredential awsCredential; @Bean @Primary public AmazonS3 generateS3Client(){ AWSCredentials credentials = new BasicAWSCredentials(awsCredential.accessKey(),awsCredential.secretKey()); return AmazonS3ClientBuilder .standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withRegion(awsCredential.region()) .build(); } }
package com.saaolheart.mumbai.invoice; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.saaolheart.mumbai.security.domain.User; @Entity @Table(name="INVOICE_RECIEPT_DETAILS") public class InvoiceRecieptDetailDomain implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Id @Column @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name="INVOICE_ID") private Long invoiceId; @Column(name="IS_PRINTED") private String isPrinted; @Column(name="PAYMENT_MODE") private String paymentMode; @Column(name="PAYMENT_REFERENCE_NO") private String paymentReferenceNo; @Column(name="PAYMENT_DATE") private Date paymentDate; @Column(name="RECIEVED_BY") private String recievedBy; @ManyToOne @JoinColumn(name="RECIEVED_BY",referencedColumnName="username",insertable=false,updatable=false) private User recievedByUser; @Column(name="IS_EMAILED") private String isEmailed; @Column(name="EMAIL_TO_ID") private String emailedToId; @Column(name="REFUND_AMOUNT") private Double refundAmount; @Column(name="PAYMENT_AMOUNT") private Double paymentAmount; public Double getPaymentAmount() { return paymentAmount; } public void setPaymentAmount(Double paymentAmount) { this.paymentAmount = paymentAmount; } public Double getRefundAmount() { return refundAmount; } public void setRefundAmount(Double refundAmount) { this.refundAmount = refundAmount; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getInvoiceId() { return invoiceId; } public void setInvoiceId(Long invoiceId) { this.invoiceId = invoiceId; } public String getIsPrinted() { return isPrinted; } public void setIsPrinted(String isPrinted) { this.isPrinted = isPrinted; } public String getPaymentMode() { return paymentMode; } public void setPaymentMode(String paymentMode) { this.paymentMode = paymentMode; } public String getPaymentReferenceNo() { return paymentReferenceNo; } public void setPaymentReferenceNo(String paymentReferenceNo) { this.paymentReferenceNo = paymentReferenceNo; } public Date getPaymentDate() { return paymentDate; } public void setPaymentDate(Date paymentDate) { this.paymentDate = paymentDate; } public String getRecievedBy() { return recievedBy; } public void setRecievedBy(String recievedBy) { this.recievedBy = recievedBy; } public User getRecievedByUser() { return recievedByUser; } public void setRecievedByUser(User recievedByUser) { this.recievedByUser = recievedByUser; } public String getIsEmailed() { return isEmailed; } public void setIsEmailed(String isEmailed) { this.isEmailed = isEmailed; } public String getEmailedToId() { return emailedToId; } public void setEmailedToId(String emailedToId) { this.emailedToId = emailedToId; } }
package com.google.android.gms.wearable.internal; import com.google.android.gms.common.api.c; import com.google.android.gms.wearable.Asset; import com.google.android.gms.wearable.c.d; class bg$4 extends aw<d> { final /* synthetic */ bg bft; final /* synthetic */ Asset bfv; bg$4(bg bgVar, c cVar, Asset asset) { this.bft = bgVar; this.bfv = asset; super(cVar); } }
package com.linkan.githubtrendingrepos.data.local.pref; public interface PrefHelper { boolean isCacheValid(); void setCacheTime(Long cacheTime); Long getCacheTime(); }
/** * Created by neelshah on 11/23/15. */ public class Constants { public static final int CLIENT_ID = -2; public static final int COORDINATOR_ID = -1; public static final int CONNECTION_TIMEOUT= 5000; public static final int VALUE_TIMEOUT= 1000; public static final int COORDINATOR_TIMEOUT= 100000; }
package com.ibeiliao.pay.balance.impl.service; import java.util.Collections; import java.util.Date; import java.util.List; import com.ibeiliao.platform.commons.utils.ParameterUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ibeiliao.pay.api.dto.response.balance.SchoolBalanceLog; import com.ibeiliao.pay.api.enums.BalanceType; import com.ibeiliao.pay.api.enums.PaymentSubject; import com.ibeiliao.pay.balance.impl.dao.SchoolBalanceLogDao; import com.ibeiliao.pay.balance.impl.entity.SchoolBalanceLogPO; import com.ibeiliao.pay.common.utils.DateUtil; import com.ibeiliao.pay.common.utils.VOUtil; /** * 处理幼儿园学校帐号的流水 * @author linyi 2016/7/25. */ @Service public class SchoolBalanceLogService { @Autowired private SchoolBalanceLogDao schoolBalanceLogDao; /** * 查询幼儿园的提现帐号的流水,按时间倒序排列 * @param schoolId 幼儿园学校ID * @param page 第几页,取值 [1, 1000] * @param pageSize 每页多少数据,取值 [10, 1000] * @return 成功返回列表,不会为 null。如果没有数据,返回size=0的 List */ public List<SchoolBalanceLog> querySchoolWithdrawBalanceLog(long schoolId, int page, int pageSize) { if (page < 1) page = 1; if (pageSize < 10 || pageSize > 1000) pageSize = 20; int offset = (page - 1) * pageSize; List<SchoolBalanceLogPO> list = schoolBalanceLogDao.querySchoolLogByBalanceType(schoolId, BalanceType.CAN_BE_WITHDRAW_BALANCE.getType(), offset, pageSize); if (list == null) return Collections.emptyList(); return VOUtil.fromList(list, SchoolBalanceLog.class); } /** * 根据时间查询所有的提现流水, 按照流水id顺序排序 * @param startDate 开始时间,不能为空, 由 指定日期的 0点0分0秒0毫秒 开始 * @param endDate 结束时间,不能为空 由 指定日期的 23点59分59秒999毫秒结束 * @param page 页码,由1开始 * @param pageSize 分页大小, 取值 [10, 1000] * @return 成功返回列表,不会为 null。如果没有数据,返回size=0的 List */ public List<SchoolBalanceLog> queryWithdrawBalanceLog(Date startDate, Date endDate, int page, int pageSize) { ParameterUtil.assertTrue(page >= 1, "页码无效"); ParameterUtil.assertTrue(pageSize >= 10 && pageSize <= 1000, "分页大小无效"); ParameterUtil.assertNotNull(startDate, "开始时间不能为空"); ParameterUtil.assertNotNull(endDate, "结束时间不能为空"); Date start = DateUtil.getStartOfDate(startDate); Date end = DateUtil.getEndOfDate(endDate); ParameterUtil.assertTrue(end.getTime() >= start.getTime(), "开始时间必须大于等于结束时间"); List<SchoolBalanceLogPO> list = schoolBalanceLogDao.queryBalanceLogBySubjectAndTime( PaymentSubject.WITHDRAW.getSubject(), start, end, (page - 1) * pageSize, pageSize); if (list == null) return Collections.emptyList(); return VOUtil.fromList(list, SchoolBalanceLog.class); } /** * 查询特定日期[00:00:00,23:59:59]幼儿园的提现帐号的流水,按时间倒序排列。</br> * * 单个幼儿园一天的数据量不会太多,此处不支持分页 * * @param schoolId 幼儿园学校ID,不能为空 * @param date 查询日期,不能为空 * @return 成功返回列表,不会为 null。如果没有数据,返回size=0的 List */ public List<SchoolBalanceLog> querySchoolBalanceLog(long schoolId, Date date) { ParameterUtil.assertNotNull(date, "汇总日期不能为空"); ParameterUtil.assertGreaterThanZero(schoolId, "幼儿园Id必须大于0"); Date start = DateUtil.getStartOfDate(date); Date end = DateUtil.getEndOfDate(date); List<SchoolBalanceLogPO> list = schoolBalanceLogDao.queryBalanceLogBySchoolIdAndTime(schoolId, start, end, 0, Integer.MAX_VALUE); if (list == null) { return Collections.<SchoolBalanceLog>emptyList(); } return VOUtil.fromList(list, SchoolBalanceLog.class); } /** * 根据时间查询所有的流水, 按照流水id顺序排序 * * @param startDate 开始时间,不能为空, 由 指定日期的 0点0分0秒0毫秒 开始 * @param endDate 结束时间,不能为空 由 指定日期的 23点59分59秒999毫秒结束 * @param page 页码,由1开始 * @param pageSize 分页大小, 取值 [10, 1000] * @return 成功返回列表,不会为 null。如果没有数据,返回size=0的 List */ public List<SchoolBalanceLog> queryBalanceLog(Date startDate, Date endDate, int page, int pageSize) { ParameterUtil.assertTrue(page >= 1, "页码无效"); ParameterUtil.assertTrue(pageSize >= 10 && pageSize <= 1000, "分页大小无效"); ParameterUtil.assertNotNull(startDate, "开始时间不能为空"); ParameterUtil.assertNotNull(endDate, "结束时间不能为空"); Date start = DateUtil.getStartOfDate(startDate); Date end = DateUtil.getEndOfDate(endDate); ParameterUtil.assertTrue(end.getTime() >= start.getTime(), "开始时间必须大于等于结束时间"); List<SchoolBalanceLogPO> list = schoolBalanceLogDao.queryBalanceLogByTime(start, end, (page - 1) * pageSize, pageSize); if (list == null) return Collections.emptyList(); return VOUtil.fromList(list, SchoolBalanceLog.class); } /** * 根据 学校id, 账户类型, 时间 获取 该账户的最后的日志记录 * * @param balanceType 账户类型 * @param beforeDate 最后记录产生的之前时间 由 指定日期的 0点0分0秒0毫秒 开始 * @return 单条日志记录, 没有时返回空 * @parma schoolId 学校id */ public SchoolBalanceLog queryLastBalanceLogBeforeDate(long schoolId, BalanceType balanceType, Date beforeDate) { ParameterUtil.assertNotNull(balanceType, "账户类型不能为空"); ParameterUtil.assertNotNull(beforeDate, "时间不能为空"); ParameterUtil.assertTrue(schoolId > 0, "学校id必须大于0"); Date before = DateUtil.getStartOfDate(beforeDate); SchoolBalanceLogPO po = schoolBalanceLogDao.queryLastBalanceLogBeforeDate(schoolId, balanceType.getType(), before); if (po != null) { SchoolBalanceLog log = new SchoolBalanceLog(); VOUtil.copy(po, log); return log; } return null; } }
package jmsproject; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.QueueSession; import javax.jms.Session; import javax.naming.Context; import javax.naming.NamingException; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import java.io.IOException; import java.io.Reader; import java.nio.file.Paths; import java.nio.file.Files; public class publisher { public static void main(String[] args) throws JMSException, NamingException, InterruptedException, IOException { Connection connection = null; final String SAMPLE_CSV_FILE_PATH = "/Users/jasvi/eclipse-workspace/jmsproject/input/user_list.csv"; try { Context context = ContextUtil.getInitialContext(); ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("ConnectionFactory"); connection = connectionFactory.createConnection(); Session session = connection.createSession(false,QueueSession.AUTO_ACKNOWLEDGE); Queue queue = (Queue) context.lookup("/queue/CouponQueue"); connection.start(); MessageProducer producer = session.createProducer(queue); // Read a record from csv file // open csv file Reader reader = Files.newBufferedReader(Paths.get(SAMPLE_CSV_FILE_PATH)); CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT); String age = null; String coupon = null; for (CSVRecord csvRecord : csvParser) { // Accessing Values by Column Index age = csvRecord.get(2); coupon = csvRecord.get(5); Message couponRecord = session.createTextMessage(age + "," + coupon); producer.send(couponRecord); Thread.sleep(500); } } finally { if (connection != null) { System.out.println("close the connection"); connection.close(); } } // TODO Auto-generated method stub } }
package com.tencent.matrix.trace.a; import android.content.Context; import java.util.HashSet; public final class a { public final boolean bsX; public final boolean bsY; public final HashSet<String> bsZ; public final long bta; public final long btb; private final long btc; public final long btd; public final long bte; private final float btf; private int mDeviceLevel; public static class a { public boolean btg = false; public boolean bth = false; public float bti = 16.666668f; public HashSet<String> btj; public long btk = 6000; public long btl = 8000; public long btm = 1000; public long bto = 1000; public long btp = 120000; } public /* synthetic */ a(boolean z, boolean z2, HashSet hashSet, long j, long j2, long j3, long j4, float f, long j5, byte b) { this(z, z2, hashSet, j, j2, j3, j4, f, j5); } private a(boolean z, boolean z2, HashSet<String> hashSet, long j, long j2, long j3, long j4, float f, long j5) { this.mDeviceLevel = 0; this.bsX = z; this.bsY = z2; this.bsZ = hashSet; this.bta = j; this.btd = 1000000 * j2; this.btc = j4; this.btb = j3; this.bte = j5; if (f == 0.0f) { f = 16.666668f; } this.btf = f; } public final String toString() { int i = 0; String str = "fpsEnable:%s,methodTraceEnable:%s,sceneSet size:%s,fpsTimeSliceMs:%s,EvilThresholdNano:%sns,frameRefreshRate:%s"; Object[] objArr = new Object[6]; objArr[0] = Boolean.valueOf(this.bsX); objArr[1] = Boolean.valueOf(this.bsY); if (this.bsZ != null) { i = this.bsZ.size(); } objArr[2] = Integer.valueOf(i); objArr[3] = Long.valueOf(this.bta); objArr[4] = Long.valueOf(this.btd); objArr[5] = Float.valueOf(this.btf); return String.format(str, objArr); } public final int aA(Context context) { if (this.mDeviceLevel != 0) { return this.mDeviceLevel; } int i = com.tencent.matrix.trace.e.a.aB(context).value; this.mDeviceLevel = i; return i; } }
import java.util.ArrayList; class Main { static void smartCombine(ArrayList<Integer> list1, ArrayList<Integer> list2, ArrayList<Integer> combined) { combined.addAll(list1); combined.addAll(list2); for (int i = 0; i < combined.size(); ++i) { for(int j = i +1; j < combined.size(); ++j) { if(combined.get(i).equals(combined.get(j))) { combined.remove(j); } } } } public static void main(String[] args) { ArrayList<Integer> list1 = new ArrayList<Integer>(); ArrayList<Integer> list2 = new ArrayList<Integer>(); ArrayList<Integer> combined = new ArrayList<Integer>(); list1.add(5); list1.add(3); list1.add(8); list2.add(7); list2.add(5); list2.add(9); smartCombine(list1, list2, combined); System.out.println(list1); System.out.println(list2); System.out.println(combined); } }
package cn.bh.view.simple; import java.io.File; import java.util.ArrayList; import java.util.List; import cn.bh.jc.DiffFileLister; import cn.bh.jc.DiffFilePacker; import cn.bh.jc.common.SysLog; import cn.bh.jc.domain.ChangeVO; import cn.bh.jc.domain.Config; import cn.bh.jc.version.GitVersion; import cn.bh.jc.version.vo.GitParaVO; /** * SVN方式打包 注意,必须保持本地最新代码,因为要取本地tomcat下编译好的class,js等文件,本项目不能自动编译 resource * 会自动跳过,配置文件自己拷贝 * * @author liubq * @since 2017年12月21日 */ public class PackerV3Main { public static void main(String[] args) { try { // 工程所用的tomcat地址(主要是为了Copy class等文件) // 配置 Config conf = new Config(); // 排除配置文件 // conf.addExclusiveFileExt(".properties"); List<GitVersion> chageList = new ArrayList<GitVersion>(); chageList.add(new GitVersion(conf, buildStaticVO())); SysLog.log("开始执行请等待。。。。。。 "); // 根据版本取得差异文件 DiffFileLister<GitVersion> oper = new DiffFileLister<GitVersion>(chageList); List<ChangeVO> list = oper.listChange(); // 打包 DiffFilePacker p = new DiffFilePacker("C:/Users/Administrator/Desktop", conf); p.pack(list); SysLog.log("\r\n 处理完成 。。。。。。 "); } catch (Exception e) { SysLog.log("异常", e); } } public static GitParaVO buildStaticVO() { String url = "http://liubq@172.16.4.195:10101/r/gsite-basic.git"; String username = "test"; String password = "test123456"; String gitBranch = "develop"; File dir = new File("C:\\Users\\Administrator\\Desktop\\dir"); String exeHome = "F:\\wk_zzb\\other\\apache-tomcat-7-site\\webapps\\gsite"; String startVerison = "98dc9dfb981ca72854d804eba7263ce485039302"; return new GitParaVO(url, username, password, gitBranch, startVerison, exeHome, dir).setExpName("gsite"); } public static GitParaVO buildStaticVO1() { String url = "http://liubq@git.jcinfo.com:7990/scm/jthy/jttsp.git"; String username = "liubq"; String password = "Lbq007624"; String gitBranch = "develop"; File dir = new File("C:\\Users\\Administrator\\Desktop\\dir"); String exeHome = "D:\\tomcat-8.5.35.8200\\webapps\\jttsp"; String startVerison = "5f50b8ae9d8997bbef9453bb8dc40ecb3718c27e"; return new GitParaVO(url, username, password, gitBranch, startVerison, exeHome, dir); } }
package com.chuxin.family.views.chat; import java.io.File; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Observable; import java.util.Timer; import java.util.TimerTask; import org.fmod.effects.RkSoundEffects; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.drawable.AnimationDrawable; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.net.Uri; import android.os.Handler; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.chuxin.family.global.CxGlobalParams; import com.chuxin.family.mate.CxMateParams; import com.chuxin.family.models.Message; import com.chuxin.family.models.VoiceMessage; import com.chuxin.family.neighbour.DialogListener; import com.chuxin.family.resource.CxResourceDarwable; import com.chuxin.family.utils.CxAudioFileResourceManager; import com.chuxin.family.utils.CxLog; import com.chuxin.family.utils.ToastUtil; import com.chuxin.family.widgets.CxImageView; import com.chuxin.family.widgets.CxInputPanel; import com.chuxin.family.widgets.VoiceTip; import com.nostra13.universalimageloader.core.ImageLoader; import com.chuxin.family.R; public class RecordEntry extends ChatLogEntry { private static final String TAG = "RecordEntry"; private static final int VIEW_RES_ID = R.layout.cx_fa_view_chat_chatting_record_row; private static final int ICON_ID = R.id.cx_fa_view_chat_chatting_record_row__icon; private static final int CONTENT_ID = R.id.cx_fa_view_chat_chatting_record_audio_length; private static final int TIMESTAMP_ID = R.id.cx_fa_view_chat_chatting_record_row__timestamp; private static final int DATESTAMP_ID = R.id.cx_fa_view_chat_chatting_record_row__datestamp; private static final int SEND_SUCCESS_BUTTON_ID = R.id.cx_fa_view_chat_chatting_record_row__exclamation; private static final int VOICE_IMAGE_VIEW_ID = R.id.cx_fa_view_chat_chatting_record_imageview; private static final int VOICE_LINEARLAYOUT_ID = R.id.cx_fa_view_chat_chatting_record_row__content; private static final int SOUND_EFFECT_TEXT_ID = R.id.cx_fa_view_chat_chatting_record_soundeffect_text; private static final int SOUND_EFFECT_IMAGEVIEW_ID = R.id.cx_fa_view_chat_chatting_record_soundimage; private static final boolean OWNER_FLAG = true; private static String dateTime = null; private ImageView mVoiceImageView; private AnimationDrawable mVoiceAd; private LinearLayout mVoiceLinearLayout; private boolean mVoicePlayFlag = true; // play voice flag private Timer mTimer = null; private TimerTask mTask = null; private ImageView newVoiceIcon = null; // 标示是否读过的小红点 // VoiceMessage message = null; // private int mCurrentMsgId; private ProgressBar mPartnerProgressBar = null; private int mRetryCount = 3; // 重试3次下载 private ChatSoundEffectDialog mEffectDialog = null; private int mEffect = 0;// 语音变声效果 public Handler recordHandler = new Handler() { public void handleMessage(android.os.Message msg) { super.handleMessage(msg); switch (msg.what) { case 0: // stopRecordAnimation(); stopVoice(); break; } }; }; public RecordEntry(Message message, Context context, boolean isShowDate) { super(message, context, isShowDate); } @Override public int getType() { return ENTRY_TYPE_RECORD; } @Override public boolean isOwner() { return OWNER_FLAG; } public int getViewResourceId() { return VIEW_RES_ID; } public int getIconId() { return ICON_ID; } public int getContentId() { return CONTENT_ID; } public int getTimeStampId() { return TIMESTAMP_ID; } public int getDateStampId() { return DATESTAMP_ID; } public int getSendSuccessButtonId() { return SEND_SUCCESS_BUTTON_ID; } public int getVoiceImageViewId() { return VOICE_IMAGE_VIEW_ID; } public int getVoiceLinearLayoutId() { return VOICE_LINEARLAYOUT_ID; } public int getSoundEffectText(){ return SOUND_EFFECT_TEXT_ID; } public int getSoundEffectImageView(){ return SOUND_EFFECT_IMAGEVIEW_ID; } @Override public View build(View view, ViewGroup parent) { ChatLogAdapter tag = null; if (view == null) { view = LayoutInflater.from(mContext).inflate(getViewResourceId(), null); } final VoiceMessage message = (VoiceMessage) mMessage; int msgType = message.getType(); final int msgId = message.getMsgId(); // mCurrentMsgId = msgId; int msgCreatTimeStamp = message.getCreateTimestamp(); final String msgVoiceUrl = message.getVoiceUrl(); final int msgVoiceLen = message.getVoiceLen(); final int audioType = message.getAudioType(); mEffect = audioType; try { tag = (ChatLogAdapter) view.getTag(); } catch (Exception e1) { e1.printStackTrace(); } if (tag == null) { tag = new ChatLogAdapter(); } tag.mChatType = msgType; tag.mMsgId = msgId; tag.mVoiceUrl = msgVoiceUrl; CxImageView icon = (CxImageView) view.findViewById(getIconId()); TextView text = (TextView) view.findViewById(getContentId()); TextView timeStamp = (TextView) view.findViewById(getTimeStampId()); TextView dateStamp = (TextView) view.findViewById(getDateStampId()); mVoiceImageView = (ImageView) view.findViewById(getVoiceImageViewId()); mVoiceLinearLayout = (LinearLayout) view .findViewById(getVoiceLinearLayoutId()); int minWidth = 110 + msgVoiceLen * (230 - 110) / 30 + 20; // ios 机制 mVoiceLinearLayout.setMinimumWidth(minWidth); // 215 // mVoiceLinearLayout.setMinimumHeight(85); TextView soundEffectText = (TextView)view.findViewById(getSoundEffectText()); ImageView soundEffectImageview = (ImageView)view.findViewById(getSoundEffectImageView()); switch(audioType){ case CxInputPanel.RKDSP_EFFECT_YUANSHENG: soundEffectText.setVisibility(View.GONE); soundEffectImageview.setVisibility(View.GONE); break; case CxInputPanel.RKDSP_EFFECT_HANHAN: soundEffectText.setVisibility(View.VISIBLE); soundEffectImageview.setVisibility(View.VISIBLE); soundEffectText.setText(R.string.cx_fa_chatview_soundeffect_text_zhuanghan); soundEffectImageview.setImageResource(R.drawable.cx_fa_sound_zhuanghan); break; case CxInputPanel.RKDSP_EFFECT_YOUYOU: soundEffectText.setVisibility(View.VISIBLE); soundEffectImageview.setVisibility(View.VISIBLE); soundEffectText.setText(R.string.cx_fa_chatview_soundeffect_text_zhuangyou); soundEffectImageview.setImageResource(R.drawable.cx_fa_sound_zhuangyou); break; case CxInputPanel.RKDSP_EFFECT_HUAIHUAI: soundEffectText.setVisibility(View.VISIBLE); soundEffectImageview.setVisibility(View.VISIBLE); soundEffectText.setText(R.string.cx_fa_chatview_soundeffect_text_zhuanghuai); soundEffectImageview.setImageResource(R.drawable.cx_fa_sound_zhuanghuai); break; case CxInputPanel.RKDSP_EFFECT_SHASHA: soundEffectText.setVisibility(View.VISIBLE); soundEffectImageview.setVisibility(View.VISIBLE); soundEffectText.setText(R.string.cx_fa_chatview_soundeffect_text_zhuangsha); soundEffectImageview.setImageResource(R.drawable.cx_fa_sound_zhuangsha); break; } if (isOwner()) { int msgSendState = message.getSendSuccess(); mVoiceImageView.setImageResource(R.drawable.chat_voice6); /*icon.setImageResource(R.drawable.cx_fa_wf_icon_small); icon.setImage(RkGlobalParams.getInstance().getIconBig(), false, 44, mContext, "head", mContext);*/ icon.displayImage(ImageLoader.getInstance(), CxGlobalParams.getInstance().getIconSmall(), CxResourceDarwable.getInstance().dr_chat_icon_small_me, true, CxGlobalParams.getInstance().getSmallImgConner()); // mVoiceImageView.setRotation(180); icon.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO update owner headimage CxLog.i(TAG, "click update owner headimage button"); ChatFragment.getInstance().updateHeadImage(); } }); final ImageButton reSendBtn = (ImageButton) view .findViewById(getSendSuccessButtonId()); ProgressBar pb = (ProgressBar) view .findViewById(R.id.cx_fa_view_chat_chatting_record_row_circleProgressBar); if (msgSendState == 0) { // 发送中 pb.setVisibility(View.VISIBLE); reSendBtn.setVisibility(View.GONE); } if (msgSendState == 1) { // 发送成功 pb.setVisibility(View.GONE); reSendBtn.setVisibility(View.GONE); } if (msgSendState == 2) { // 发送失败 pb.setVisibility(View.GONE); reSendBtn.setVisibility(View.VISIBLE); reSendBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // resend message new AlertDialog.Builder(ChatFragment.getInstance() .getActivity()) .setTitle(R.string.cx_fa_alert_dialog_tip) .setMessage(R.string.cx_fa_chat_resend_msg) .setPositiveButton( R.string.cx_fa_chat_button_resend_text, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int which) { reSendBtn .setVisibility(View.GONE); ChatFragment.getInstance() .reSendMessage( msgVoiceUrl, 4, msgId, msgVoiceLen, audioType); } }) .setNegativeButton( R.string.cx_fa_cancel_button_text, null) .show(); } }); } } else { mPartnerProgressBar = (ProgressBar) view .findViewById(R.id.cx_fa_view_chat_chatting_record_row_partner_circleProgressBar); mVoiceImageView.setImageResource(R.drawable.chat_voice3); newVoiceIcon = (ImageView) view .findViewById(R.id.cx_fa_view_chat_chatting_record_newvoice_for_partner); // 得到是否读过的小红点对象 // 如果该条信息已读过,则将小红点隐藏 if (message.getIsRead()) { newVoiceIcon.setVisibility(View.GONE); } else { newVoiceIcon.setVisibility(View.VISIBLE); } // RkLog.v(TAG, "partner:" + // RkMateParams.getInstance().getMateIcon()); // mVoiceImageView.setRotation(0); /*icon.setImageResource(R.drawable.cx_fa_hb_icon_small); icon.setImage(RkGlobalParams.getInstance().getPartnerIconBig(), false, 44, mContext, "head", mContext);*/ icon.displayImage(ImageLoader.getInstance(), CxGlobalParams.getInstance().getPartnerIconBig(), CxResourceDarwable.getInstance().dr_chat_icon_small_oppo, true, CxGlobalParams.getInstance().getMateSmallImgConner()); icon.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO 跳转到个人资料页 ChatFragment.getInstance().gotoOtherFragment("rkmate"); } }); } mVoiceLinearLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (isOwner()) { // 自己发的语音 if (mVoicePlayFlag) { playVoice(msgVoiceUrl, msgVoiceLen); if (!isOwner() && mMessage != null && !message.getIsRead()) { newVoiceIcon.setVisibility(View.GONE); // 将标示信息未读的小红点隐藏 // 将该条信息设置为已读, 并刷新聊天页面 try { mMessage.mData.put("is_read", true); mMessage.update(); ChatFragment.getInstance().updateChatViewDB(); // 强制更新一下视图中的数据,使之与数据库保持一致 } catch (JSONException e) { e.printStackTrace(); } } } else { stopVoice(); } } else { // 对方发过来的语音 getAudioFile(msgVoiceUrl, msgVoiceLen, message); } } }); text.setText(msgVoiceLen + "''"); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date((long) (msgCreatTimeStamp) * 1000)); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日"); String dateNow = dateFormat.format(new Date( (long) (msgCreatTimeStamp) * 1000)); if (mIsShowDate) { dateStamp.setVisibility(View.VISIBLE); dateStamp.setText(dateNow); } else { dateStamp.setVisibility(View.GONE); } String format = view.getResources().getString( R.string.cx_fa_nls_reminder_period_time_format); String time = String.format(format, calendar); timeStamp.setText(time); view.setTag(tag); return view; } public void playVoice(String path, int msgVoiceLen) { CxLog.v(TAG, "voice uri=" + path); if (null != ChatFragment.getInstance().mPlayRecordEntry && ChatFragment.getInstance().mPlayRecordEntry != RecordEntry.this) { ChatFragment.getInstance().mPlayRecordEntry.stopRecordAnimation(); } if (RkSoundEffects.cFmodGetIsPlay()) { // RkSoundEffects.cFmodStop(); // stopRecordAnimation(); stopVoice(); } try { RkSoundEffects.soundPlay(path, mEffect); } catch (Exception e) { e.printStackTrace(); new Handler(mContext.getMainLooper()) { public void handleMessage(android.os.Message msg) { Toast.makeText( mContext, mContext.getString(R.string.cx_fa_destroy_audio_file), Toast.LENGTH_SHORT).show(); }; }.sendEmptyMessage(1); return; } try { startTimer(msgVoiceLen); startRecordAnimation(); if(mEffect > 0){ if(null == mEffectDialog){ mEffectDialog= new ChatSoundEffectDialog(mContext, mEffect, R.style.bg_transparent_dialog, new DialogListener() { @Override public void refreshUiAndData() { stopVoice(); } }); } mEffectDialog.show(); } } catch (Exception e) { e.printStackTrace(); } ChatFragment.getInstance().mPlayRecordEntry = RecordEntry.this; } public void stopVoice() { CxLog.d("playVoice", "isplay1=" + RkSoundEffects.cFmodGetIsPlay()); CxLog.d("playVoice", "ispause1=" + RkSoundEffects.cFmodGetIsPause()); if (RkSoundEffects.cFmodGetIsPlay() || RkSoundEffects.cFmodGetIsPause()) { RkSoundEffects.cFmodStop(); } if (null != mTimer) { mTimer.cancel(); mTimer = null; } if (null != mTask) { mTask.cancel(); mTask = null; } stopRecordAnimation(); if(mEffect > 0){ if(null != mEffectDialog){ mEffectDialog.dismiss(); } } } private void startRecordAnimation() { if (isOwner()) { mVoiceImageView.setImageResource(R.anim.cx_fa_anim_chat_voice); } else { mVoiceImageView .setImageResource(R.anim.cx_fa_anim_chat_voice_for_partner); } mVoiceAd = (AnimationDrawable) mVoiceImageView.getDrawable(); mVoiceAd.start(); mVoicePlayFlag = false; } private void stopRecordAnimation() { if (null != mVoiceAd && mVoiceAd.isRunning()) { mVoiceAd.stop(); mVoicePlayFlag = true; if (isOwner()) { mVoiceImageView.setImageResource(R.drawable.chat_voice6); } else { mVoiceImageView.setImageResource(R.drawable.chat_voice3); } } } private void startTimer(int msgVoiceLen) { if (null == mTimer) { mTimer = new Timer(); } if (null == mTask) { mTask = new TimerTask() { @Override public void run() { android.os.Message message = recordHandler.obtainMessage(0); message.sendToTarget(); } }; } mTimer.schedule(mTask, (msgVoiceLen + 1) * 1000); } public String getAudioFile(final String url, final int audioLength, final VoiceMessage message) { if ((null == url) || (url.equals("null"))) { // 避免服务器返回"null" CxLog.i(TAG, " param url is null"); return ""; } final CxAudioFileResourceManager resourceManager = CxAudioFileResourceManager .getAudioFileResourceManager(ChatFragment.getInstance() .getActivity()); // File file = resourceManager.getFile(Uri.parse(url)); if (resourceManager.exists(Uri.parse(url))) { CxLog.i(TAG, "file path local="); final File file = resourceManager.getFile(Uri.parse(url)); CxLog.i("getAudioFile", "filepath0=" + file.getAbsolutePath()); new Handler(mContext.getMainLooper()) { public void handleMessage(android.os.Message msg) { preparePlayVoice(file.getAbsolutePath(), audioLength, message); } }.sendEmptyMessage(1); return file.getAbsolutePath(); } else { // checkSdCardExist(); new Handler(mContext.getMainLooper()) { public void handleMessage(android.os.Message msg) { mVoiceImageView.setVisibility(View.GONE); mPartnerProgressBar.setVisibility(View.VISIBLE); } }.sendEmptyMessage(1); CxLog.i(TAG, "ready to net download"); resourceManager .addObserver(new CxAudioFileResourceManager.ResourceRequestObserver( Uri.parse(url)) { @Override public void requestReceived(Observable observable, Uri uri, long len) { observable.deleteObserver(this); try { mRetryCount--; CxLog.i("getAudioFile", "uri="+uri.toString()); File file = resourceManager.getFile(uri); CxLog.i("getAudioFile", "contentlength>>>" + len); CxLog.i("getAudioFile", "file.length>>>" + file.length()); CxLog.i("getAudioFile", "audiolength>>>" + audioLength); if (file.length() < len || (file.length() == 0 && len == -1)) { //考虑到目前腾讯服务器的问题 CxLog.i("getAudioFile", "not download file complete, need to reload"); file.delete(); // 重试3次,失败了给出提示 if (mRetryCount > 0) { //如果重试机会还有就重试下载 getAudioFile(url, audioLength, message); } else { //重试次数没有就给出失败提示 new Handler(mContext.getMainLooper()) { public void handleMessage( android.os.Message msg) { mPartnerProgressBar .setVisibility(View.GONE); mVoiceImageView .setVisibility(View.VISIBLE); ToastUtil.getSimpleToast(mContext, -3, mContext .getString(R.string.cx_fa_not_download_file_complete), 1).show(); } }.sendEmptyMessage(1); } } else { CxLog.i("getAudioFile", "filepath1=" + file.getAbsolutePath()); final String audioFilePath = file .getAbsolutePath(); CxLog.i("getAudioFile", "audioFilePath=" + audioFilePath); new Handler(mContext.getMainLooper()) { public void handleMessage( android.os.Message msg) { mPartnerProgressBar .setVisibility(View.GONE); mVoiceImageView .setVisibility(View.VISIBLE); preparePlayVoice(audioFilePath, audioLength, message); } }.sendEmptyMessage(1); } } catch (Exception e) { e.printStackTrace(); } } }); resourceManager.request(Uri.parse(url)); return ""; } } private void preparePlayVoice(final String msgVoiceUrl, final int msgVoiceLen, VoiceMessage message) { if (mVoicePlayFlag) { playVoice(msgVoiceUrl, msgVoiceLen); if (!isOwner() && mMessage != null && !message.getIsRead()) { newVoiceIcon.setVisibility(View.GONE); // 将标示信息未读的小红点隐藏 // 将该条信息设置为已读, 并刷新聊天页面 try { mMessage.mData.put("is_read", true); mMessage.update(); ChatFragment.getInstance().updateChatViewDB(); // 强制更新一下视图中的数据,使之与数据库保持一致 } catch (JSONException e) { e.printStackTrace(); } } } else { stopVoice(); } } }
package ru.kstu.aec.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import ru.kstu.aec.models.*; import ru.kstu.aec.services.AnswerService; import ru.kstu.aec.services.QuestionService; import java.util.List; @Controller public class TestController { final AnswerService answerService; final QuestionService questionService; List<Question> questions; List<Answer> answers; public TestController(QuestionService questionService, AnswerService answerService) { this.questionService = questionService; this.answerService = answerService; } @GetMapping("/test/{id}") public String Test(Model model, @PathVariable String id) { questions = questionService.loadQuestions(); answers = answerService.loadAnswers(); model.addAttribute("questions", questions); model.addAttribute("question", questions.get(Integer.parseInt(id))); model.addAttribute("id", Integer.parseInt(id)); model.addAttribute("answers", answers); return "test"; } @GetMapping("/test") public String getTest(Model model) { String id = "0"; questions = questionService.loadQuestions(); answers = answerService.loadAnswers(); model.addAttribute("questions", questions); model.addAttribute("question", questions.get(Integer.parseInt(id))); model.addAttribute("id", Integer.parseInt(id)); model.addAttribute("answers", answers); return "test"; } @PostMapping("/test") public String postTest(@ModelAttribute("studentsQuestionsAnswers") StudentsQuestionsAnswers studentsQuestionsAnswers, BindingResult result) { return "redirect:/test"; } @GetMapping("/crud_questions") public String getCrud(Question question, Answer answer) { return "crud_questions"; } @PostMapping("/crud") public String postCrud(@ModelAttribute("question") Question question, BindingResult result) { questionService.createQuestion(question); return "redirect:/crud_questions"; } @PostMapping("/crua") public String postCrua(@ModelAttribute("answer") Answer answer, BindingResult result) { answerService.createAnswer(answer); return "redirect:/crud_questions"; } }
package com.example.demo; public class ChildCA extends ParentC{ public ChildCA(boolean sOS, String color, String power, double price) { super(sOS, color, power, price); } }
package top.zeroyiq.master_help_me.activities; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import java.util.ArrayList; import java.util.List; import java.util.Random; import top.zeroyiq.master_help_me.R; import top.zeroyiq.master_help_me.adapter.MessageAdapter; import top.zeroyiq.master_help_me.models.MessageBody; public class MessageActivity extends BaseActivity { private List<MessageBody> bodyList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_message); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); initList(); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_message); LinearLayoutManager layoutManager = new LinearLayoutManager(this); MessageAdapter adapter = new MessageAdapter(bodyList); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); } private void initList() { for (int i = 0; i < 5; i++) { bodyList.add(new MessageBody(1, "-∫(0~2π)e^sint dcost=?\n" + "为什么?", "admin", "原式化为(先当做不定积分化简)" + "∫xe^xdx=∫xde^x=xe^x-∫e^xdx=xe^x-e^x=e^x(x-1)", "2017-6-8")); bodyList.add(new MessageBody(1, "第五题(X的上角标为2n),为什么会有间断点," + "我觉得一般的间断点都是分母不能为0,这题为什么会有间断点1", "admin", "是这个样子的,你要看定义,f(x-) =f(x+)\n" + "在1 的1+ 1- 两边,f(x)不相等,所以就是间断点\n" + "简短点分两类,第一类可去和第二类无穷,这种属于第二类", "2017-5-14")); bodyList.add(new MessageBody(1, "高等数学", "admin", getRandomLengthContent("789"), "2017-5-12")); bodyList.add(new MessageBody(1, "高等数学", "admin", getRandomLengthContent("123"), "2017-5-11")); } } private String getRandomLengthContent(String content) { Random random = new Random(); int i = random.nextInt(20) + 1; StringBuffer buffer = new StringBuffer(); for (int j = 0; j < i; j++) { buffer.append(content); } return buffer.toString(); } public static void actionStart(Context context) { Intent intent = new Intent(context, MessageActivity.class); context.startActivity(intent); } }
package teszt; import java.util.*; import szallitas.*; public class Teszt3 extends Teszt { @Override public boolean teszt() { Doboz d1 = new Doboz(100); Doboz d2 = new Doboz(200); TorekenyDoboz d3 = new TorekenyDoboz(300); Doboz d4 = new TorekenyDoboz(400); Gyar gy = new Gyar(); //Gyar tesztje if (gy.getElsoNormalDoboz() != null) hiba("A Gyar getElsoNormalDoboz metodusa ures futoszalagra nem mukodik jol."); gy.legyart(d3); if (gy.getElsoNormalDoboz() != null) hiba("A Gyar getElsoNormalDoboz metodusa nem mukodik jol, ha csak torekeny doboz van a szalagon."); if (! gy.toString().equals("[!360]")) hiba("A Gyar toString metodusa hibas egy elemre."); gy.legyart(d1); gy.legyart(d2); gy.legyart(d4); if (! gy.toString().equals("[!360]_[100]_[200]_[!480]")) hiba("A Gyar toString metodusa hibas 4 elemre."); if (gy.getElsoNormalDoboz() != d1) hiba("A Gyar getElsoNormalDoboz metodusa nem az elso normal dobozt adja viszza"); if (gy.getElsoNormalDoboz() != d1) hiba("A Gyar getElsoNormalDoboz metodusa nem az elso normal dobozt adja viszza a masodik lekerdezes alkalmaval"); //TorekenyDoboz tesztje Doboz d5 = new TorekenyDoboz(100, true); Doboz d6 = new TorekenyDoboz(100, false); if (d5.getErtek() != 120) hiba("A TorekenyDoboz getErtek metodusa hibas eredmenyt ad d5-nel"); if (d6.getErtek() != 100) hiba("A TorekenyDoboz getErtek metodusa hibas eredmenyt ad d6-nal"); if (! d5.torekenyE()) hiba("A TorekenyDoboz torekenyE metodusa hibas eredmenyt ad d5-nel"); if (d6.torekenyE()) hiba("A TorekenyDoboz torekenyE metodusa hibas eredmenyt ad d6-nal"); if (! d5.toString().equals("[!120]")) hiba("A TorekenyDoboz toString metodusa hibas eredmenyt ad d5-nel"); if (! d6.toString().equals("[100]")) hiba("Az TorekenyDoboz toString metodusa hibas redmenyt ad d6-nal"); return ok; } }
package org.carter.peyton.training.rap.db.dao.impl; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; import org.carter.peyton.training.rap.db.dao.UserDAO; import org.carter.peyton.training.rap.db.entities.User; public class UserDAOImpl implements UserDAO { private EntityManagerFactory emf; @Override public List<User> getListUser() { emf = Persistence.createEntityManagerFactory("org.carter.peyton.training.rap.db"); EntityManager em = emf.createEntityManager(); Query query = em.createQuery("Select u from User u"); @SuppressWarnings("unchecked") List<User> listUser = query.getResultList(); em.close(); return listUser; } }
package ru.android.messenger; import android.app.Activity; import android.app.Application; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.text.emoji.EmojiCompat; import android.support.text.emoji.bundled.BundledEmojiCompatConfig; import java.util.ArrayList; import java.util.List; import ru.android.messenger.utils.Logger; import ru.android.messenger.view.notifications.NotificationChannels; import ru.android.messenger.view.utils.ActiveActivitiesTracker; public class MessengerApplication extends Application implements Application.ActivityLifecycleCallbacks { private List<Activity> activities; @Override public void onCreate() { super.onCreate(); registerActivityLifecycleCallbacks(this); createNotificationChannels(); initEmoji(); activities = new ArrayList<>(); } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { Logger.debug(String.format("Created %s activity", activity.getLocalClassName())); activities.add(activity); } @Override public void onActivityStarted(Activity activity) { Logger.debug(String.format("Started %s activity", activity.getLocalClassName())); activities.add(activity); ActiveActivitiesTracker.activityStarted(activity); } @Override public void onActivityResumed(Activity activity) { Logger.debug(String.format("Resumed %s activity", activity.getLocalClassName())); activities.add(activity); } @Override public void onActivityPaused(Activity activity) { Logger.debug(String.format("Paused %s activity", activity.getLocalClassName())); activities.remove(activity); } @Override public void onActivityStopped(Activity activity) { Logger.debug(String.format("Stopped %s activity", activity.getLocalClassName())); activities.remove(activity); ActiveActivitiesTracker.activityStopped(); } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { Logger.debug(String.format("SaveInstanceState %s activity", activity.getLocalClassName())); activities.remove(activity); } @Override public void onActivityDestroyed(Activity activity) { Logger.debug(String.format("Destroyed %s activity", activity.getLocalClassName())); activities.remove(activity); } @Nullable public Activity getCurrentActivity() { return activities.isEmpty() ? null : activities.get(0); } private void createNotificationChannels() { new NotificationChannels(this); } private void initEmoji() { EmojiCompat.Config config = new BundledEmojiCompatConfig(this); EmojiCompat.init(config); } }
package com.crud.medicalclinic.mapper; import com.crud.medicalclinic.domain.Doctor; import com.crud.medicalclinic.domain.DoctorDto; import com.crud.medicalclinic.domain.Office; import com.crud.medicalclinic.domain.OfficeDto; import org.springframework.stereotype.Component; import java.util.List; import java.util.stream.Collectors; @Component public class DoctorMapper { public Doctor mapToDoctor(final DoctorDto doctorDto) { return new Doctor( doctorDto.getId(), doctorDto.getName(), doctorDto.getLastname(), doctorDto.getSpecialisation(), doctorDto.getReview() ); } public DoctorDto mapToDoctorDto(final Doctor doctor) { return new DoctorDto( doctor.getId(), doctor.getName(), doctor.getLastname(), doctor.getSpecialisation(), doctor.getReview() ); } public List<DoctorDto> mapToDoctorDtoList(final List<Doctor> doctorList) { return doctorList.stream() .map(d -> new DoctorDto(d.getId(), d.getName(), d.getLastname(), d.getSpecialisation(), d.getReview())) .collect(Collectors.toList()); } }
/* * 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 learnjava; /** * * @author CongThanh */ public class TimPhanTuTrungNhau { public static void main(String[] args) { int[] mang = { 21, 2 , 21, 21, 3}; Find(mang); } public static void Find(int[] arrayNumber){ bubbleSort(arrayNumber); int count = 1; int n= arrayNumber.length; for(int i=1; i<n; i++){ if(arrayNumber[i]!= arrayNumber[i-1]) show(arrayNumber[i-1], count); else count++; } show(arrayNumber[n-1], count); } // Show ra màn hình public static void show(int number, int count){ System.out.println("Phần tử " + number + " xuất hiện: " + count + " lần."); } // Thuật toán nổi bọt: Đổi chỗ 2 cặp phần tử gần nhau. Tìm được số nhỏ nhất trong dãy sau mỗi vòng lặp public static void bubbleSort(int Array[]){ int n = Array.length; int i, j, temp; boolean swaped = true; while(swaped){ swaped = false; for(i=0; i< n-1; i++){ for(j=n-1; j>i; j--){ if(Array[j]<Array[j-1]){ temp = Array[j]; Array[j]= Array[j-1]; Array[j-1] = temp; swaped = true; } } } } } }
package com.flutterwave.raveandroid.rave_presentation.di.rwfmobilemoney; import com.flutterwave.raveandroid.rave_presentation.rwfmobilemoney.RwfMobileMoneyContract; import javax.inject.Inject; import dagger.Module; import dagger.Provides; @Module public class RwfModule { private RwfMobileMoneyContract.Interactor interactor; @Inject public RwfModule(RwfMobileMoneyContract.Interactor interactor) { this.interactor = interactor; } @Provides public RwfMobileMoneyContract.Interactor providesContract() { return interactor; } }
package de.jmda.gen.java.impl; import static de.jmda.core.mproc.ProcessingUtilities.getFields; import static de.jmda.core.mproc.ProcessingUtilities.getTypeElement; import static de.jmda.core.util.CollectionsUtil.asSet; import static java.lang.System.lineSeparator; import java.io.IOException; import java.util.List; import java.util.Set; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Before; import org.junit.Test; import de.jmda.core.mproc.task.AbstractTypeElementsTaskTypes; import de.jmda.core.mproc.task.TaskException; import de.jmda.core.mproc.task.TaskRunner; import de.jmda.gen.GeneratorException; import de.jmda.gen.java.InstanceFieldGenerator; public class JUTDefaultInstanceFieldDeclarationGenerator { private final static Logger LOGGER = LogManager.getLogger(JUTDefaultInstanceFieldDeclarationGenerator.class); private class InstanceFieldContainer { @SuppressWarnings("unused") private List<String> strings; } private class Task extends AbstractTypeElementsTaskTypes { private TypeElement type; private Task(Set<? extends Class<?>> types) { super(types); } @Override public boolean execute() throws TaskException { type = getTypeElement(InstanceFieldContainer.class); return false; } } private InstanceFieldGenerator fieldDeclarationGenerator; @Before public void before() throws IOException { fieldDeclarationGenerator = new DefaultInstanceFieldGenerator(); } @Test public void test() throws GeneratorException, IOException { Task task = new Task(asSet(InstanceFieldContainer.class)); TaskRunner.run(task); for (VariableElement field : getFields(task.type)) { fieldDeclarationGenerator.setTypeFrom(field); LOGGER.debug( field.toString() + lineSeparator() + fieldDeclarationGenerator.generate()); // LOGGER.debug("field : " + field); // LOGGER.debug("field.asType : " + field.asType()); // // DeclaredType declaredType = asDeclaredType(field.asType()); // // LOGGER.debug("field.asDeclaredType : " + declaredType); // LOGGER.debug("field.asDeclaredTypeTypeElement : " + // asTypeElement(declaredType).getQualifiedName()); // //// LOGGER.debug("useType.asDeclaredTypeTypeElement: " + //// getImportManager().useTypeOfField(field)); // // for (TypeMirror type : declaredType.getTypeArguments()) // { // LOGGER.debug("type argument: " + type); //// LOGGER.debug("useType.type: " + getImportManager().useType(type)); // } } } }
package com.example.spotifyauthentication.Models.Tracks; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class ExternalUrls { @SerializedName("spotify") @Expose private String spotify; public String getSpotify() { return spotify; } public void setSpotify(String spotify) { this.spotify = spotify; } }
// Sun Certified Java Programmer // Chapter 4, P305 // Operators class Tester305 { public static void main(String[] args) { byte b1 = 6 & 8; byte b2 = 7 | 9; byte b3 = 5 ^ 4; System.out.println(b1 + " " + b2 + " " + b3); } }
package com.tencent.mm.protocal.c; import com.tencent.mm.bk.a; public final class li extends a { public int roA; public int roB; public String rov; public String rox; public int roy; public int roz; protected final int a(int i, Object... objArr) { int h; if (i == 0) { f.a.a.c.a aVar = (f.a.a.c.a) objArr[0]; if (this.rov != null) { aVar.g(1, this.rov); } if (this.rox != null) { aVar.g(2, this.rox); } aVar.fT(3, this.roy); aVar.fT(4, this.roz); aVar.fT(5, this.roA); aVar.fT(6, this.roB); return 0; } else if (i == 1) { if (this.rov != null) { h = f.a.a.b.b.a.h(1, this.rov) + 0; } else { h = 0; } if (this.rox != null) { h += f.a.a.b.b.a.h(2, this.rox); } return (((h + f.a.a.a.fQ(3, this.roy)) + f.a.a.a.fQ(4, this.roz)) + f.a.a.a.fQ(5, this.roA)) + f.a.a.a.fQ(6, this.roB); } else if (i == 2) { f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler); for (h = a.a(aVar2); h > 0; h = a.a(aVar2)) { if (!super.a(aVar2, this, h)) { aVar2.cJS(); } } return 0; } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; li liVar = (li) objArr[1]; switch (((Integer) objArr[2]).intValue()) { case 1: liVar.rov = aVar3.vHC.readString(); return 0; case 2: liVar.rox = aVar3.vHC.readString(); return 0; case 3: liVar.roy = aVar3.vHC.rY(); return 0; case 4: liVar.roz = aVar3.vHC.rY(); return 0; case 5: liVar.roA = aVar3.vHC.rY(); return 0; case 6: liVar.roB = aVar3.vHC.rY(); return 0; default: return -1; } } } }
package com.yc.model; import java.util.List; import org.springframework.stereotype.Component; import lombok.Data; /** * 更改controller该接口对应方法接收的参数List<Integer> * @author adeline * @date 2018年9月3日 * @TODO */ @Data @Component public class ParameterVO { private List<Integer> ids; }
package com.tencent.mm.plugin.appbrand.ipc; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.os.Handler; import android.os.ResultReceiver; class AppBrandProcessProxyUI$2 extends ResultReceiver { final /* synthetic */ OnClickListener fDY; final /* synthetic */ OnClickListener fDZ; final /* synthetic */ OnClickListener fEa; AppBrandProcessProxyUI$2(Handler handler, OnClickListener onClickListener, OnClickListener onClickListener2, OnClickListener onClickListener3) { this.fDY = onClickListener; this.fDZ = onClickListener2; this.fEa = onClickListener3; super(handler); } protected final void onReceiveResult(int i, Bundle bundle) { if (-1 == i && this.fDY != null) { this.fDY.onClick(null, i); } if (-2 == i && this.fDZ != null) { this.fDZ.onClick(null, i); } if (-3 == i && this.fEa != null) { this.fEa.onClick(null, i); } } }
package nl.vdijkit.aas.aggregate; import java.util.List; public class Request { private final List<String> pricingItems; private final List<String> trackItems; private final List<String> shipmentItems; public Request(List<String> pricingItems, List<String> trackItems, List<String> shipmentItems) { this.pricingItems = pricingItems; this.trackItems = trackItems; this.shipmentItems = shipmentItems; } public List<String> getPricingItems() { return pricingItems; } public List<String> getTrackItems() { return trackItems; } public List<String> getShipmentItems() { return shipmentItems; } @Override public String toString() { return "Request{" + "pricingItems=" + pricingItems + ", trackItems=" + trackItems + ", shipmentItems=" + shipmentItems + '}'; } }
package com.gtfs.dao.interfaces; import java.util.List; import com.gtfs.bean.RoleAccessRlns; public interface RoleAccessRlnsDao { List<RoleAccessRlns> findActiveRoleAccessRlnsByAccessId(Long accessId); Long insertIntoRoleAccessRlns(RoleAccessRlns roleAccessRlns); Integer deleteRoleAccessRlnsByRoleIdAndAccessId(Long roleId,Long accessId); }
/* * created 17.07.2005 * * Copyright 2009, ByteRefinery * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * $Id: ColumnScaleOperation.java 665 2007-09-29 15:31:59Z cse $ */ package com.byterefinery.rmbench.operations; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import com.byterefinery.rmbench.EventManager; import com.byterefinery.rmbench.RMBenchPlugin; import com.byterefinery.rmbench.model.schema.Column; import com.byterefinery.rmbench.model.schema.ForeignKey; /** * Operation for changing the scale of a column * @author cse */ public class ColumnScaleOperation extends ModifyColumnOperation { private final int oldScale, newScale; public ColumnScaleOperation(Column column, int newScale) { super(Messages.Operation_ModifyColumn, column); this.oldScale = column.getScale(); this.newScale = newScale; } public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { column.setScale(newScale); updateForeignKeys(newScale); RMBenchPlugin.getEventManager().fireColumnModified( column.getTable(), EventManager.Properties.COLUMN_SCALE, column); fireForeignKeyEvents(EventManager.Properties.COLUMN_SCALE); fireReferencesEvents(EventManager.Properties.COLUMN_SCALE); return Status.OK_STATUS; } public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { column.setScale(oldScale); updateForeignKeys(oldScale); RMBenchPlugin.getEventManager().fireColumnModified( column.getTable(), EventManager.Properties.COLUMN_SCALE, column); fireForeignKeyEvents(EventManager.Properties.COLUMN_SCALE); fireReferencesEvents(EventManager.Properties.COLUMN_SCALE); return Status.OK_STATUS; } private void updateForeignKeys(int scale) { // setting referring foreignkeys if (column.belongsToPrimaryKey()) { int keyIndex=column.getTable().getPrimaryKey().getIndex(column); for (ForeignKey foreignKey : column.getTable().getReferences()) { foreignKey.getColumn(keyIndex).setScale(scale); } } } }
package com.hban.sman.mvp.complexscreen.presenter; import com.hban.sman.mvp.base.Ipresenter; import com.hban.sman.mvp.data.LoginUser; import java.util.List; /** * Created by zhuchuntao on 16-11-23. */ public interface IFirstPresenter extends Ipresenter { void sendRequestList(); void getListSuccess(List<LoginUser> userList); }
package jonceski.kliment.googlecertprepare; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import jonceski.kliment.googlecertprepare.ui.WeatherActivity; import android.support.test.espresso.Espresso; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; /** * Created by kliment on 7/22/2017. */ @RunWith(AndroidJUnit4.class) public class ExampleUiTest { @Rule public ActivityTestRule<WeatherActivity> mActivityRule = new ActivityTestRule<>( WeatherActivity.class); @Before public void initValidString() { // Specify a valid string. } @Test public void changeText_sameActivity() { // Test if refresh button is displayed in action bar. Espresso.onView(withId(R.id.action_refresh)) .check(matches(withText(R.string.menu_refresh))); Espresso.onView(withId(R.id.recyclerview_forecast)) .check(new RecyclerViewItemCountAssertion(14)); } }
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * 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.overlord.rtgov.internal.switchyard.bpm; import java.util.EventObject; import org.drools.core.event.ProcessVariableChangedEventImpl; import org.kie.api.event.process.ProcessVariableChangedEvent; import org.overlord.rtgov.internal.switchyard.AbstractEventProcessor; /** * This class provides the BPM component implementation of the * event processor. * */ public class ProcessVariableChangedEventProcessor extends AbstractEventProcessor { /** * This is the default constructor. */ public ProcessVariableChangedEventProcessor() { super(ProcessVariableChangedEventImpl.class); } /** * {@inheritDoc} */ public void handleEvent(EventObject event) { ProcessVariableChangedEvent bpmEvent=(ProcessVariableChangedEvent)event; org.overlord.rtgov.activity.model.bpm.ProcessVariableSet pvs= new org.overlord.rtgov.activity.model.bpm.ProcessVariableSet(); pvs.setVariableName(bpmEvent.getVariableId()); String type=null; if (bpmEvent.getNewValue() != null) { type = bpmEvent.getNewValue().getClass().getName(); pvs.setVariableType(type); } pvs.setVariableValue(getActivityCollector().processInformation(null, type, bpmEvent.getNewValue(), null, pvs)); pvs.setProcessType(bpmEvent.getProcessInstance().getProcessName()); pvs.setInstanceId(Long.toString(bpmEvent.getProcessInstance().getId())); recordActivity(event, pvs); } }
package facing; /** * @author admin * @version 1.0.0 * @ClassName BuLongFilter.java * @Description 模拟布隆过滤器 * @createTime 2021年03月20日 21:34:00 */ public class BuLongFilter { //首先设置位图 public static void main(String[] args) { int a = 0; //一个int 4字节 1个字节8bit int[] arr = new int[10]; //32*10 bit //想取得178bit的状态 int i= 178; //先定义在10个数中哪个数去找 int numIndex = i / 32; //这个数有32位,具体在哪个数的第几位 int bitIndex = i % 32; //拿到第178位的状态 首先把这个数右移bitIndex 位,就是把目标移到最右了,再拿出来,s不是1就是0 int s = ((arr[numIndex] >> (bitIndex)) & 1); //把i位的状态改为1 (注意 其他位保持不变) 把1左移bitIndex这么多位再或arr[numIndex] arr[numIndex] = arr[numIndex] | (1 << (bitIndex)); //把i位的状态改为0 (注意 其他位保持不变) 把1左移bitIndex这么多位再取反,那得到了除了第i位为0其余都是1这样的数 再与arr[numIndex] arr[numIndex] = arr[numIndex] & (~(1 << (bitIndex))); } }
package api.longpoll.bots.http; import java.io.File; import java.io.IOException; import java.util.Map; /** * HTTP client to send HTTP requests. */ public interface HttpClient { /** * Sets HTTP method. E.g. "GET" or "POST". * * @param method HTTP method. */ void setMethod(String method); /** * Sets request URL. * * @param url request URL. */ void setUrl(String url); /** * Sets request URL params. * * @param params URL params. */ void setParams(Map<String, String> params); /** * Sets file to be uploaded. * * @param key param name. * @param fileName file name. * @param file file to upload. */ void setFile(String key, String fileName, File file); /** * Executes HTTP request. * * @return response body. * @throws IOException if errors occur. */ String execute() throws IOException; }
package sim.usuario; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import sim.util.HibernateUtil; public class UsuarioDAOHibernate implements UsuarioDAO { private Session session; @Override public void salvar(Usuario usuario) { this.session.save(usuario); } @Override public void atualizar(Usuario usuario) { this.session.clear(); this.session.update(usuario); } @Override public void excluir(Usuario usuario) { this.session.delete(usuario); } @Override public Usuario carregar(Integer codigo) { return (Usuario) this.session.get(Usuario.class, codigo); } @Override public Usuario buscarPorLogin(String nome, String senha) { String hql = "select u from Usuario u where u.nome = :nome and u.senha = :senha"; Query q = this.session.createQuery(hql); q.setString("nome", nome); q.setString("senha", senha); return (Usuario) q.uniqueResult(); } @Override public List<Usuario> listar() { return this.session.createCriteria(Usuario.class).list(); } public Session getSession() { return session; } public void setSession(Session session) { this.session = session; } }
package com.kevin.springboot.backend.apirest.models.dao; import org.springframework.data.repository.CrudRepository; import com.kevin.springboot.backend.apirest.models.entity.Grado; public interface IGradoDao extends CrudRepository<Grado, Long>{ }
package com.vikastadge.hibernate.onetomany.dao; import com.vikastadge.hibernate.onetomany.dao.entity.EventEntity; import com.vikastadge.hibernate.onetomany.util.HibernateUtil; import org.hibernate.Session; import org.hibernate.Transaction; public class EventDAO { public void save(EventEntity eventEntity){ System.out.println("in DAO"); Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); session.save(eventEntity); transaction.commit(); HibernateUtil.shutdown(); } public EventEntity get(int id){ Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); EventEntity eventEntity = session.get(EventEntity.class, id); return eventEntity; } }
package interviews.yelp; public class SumToATarget { public boolean solution(int[] arr, int target) { if (arr == null || arr.length * target <= 0) return false; return dfs(arr, 0, target); } // Time: O(n!) public boolean dfs(int[] arr, int pos, int target) { if (target == 0) return true; if (pos >= arr.length || target < 0) return false; for (int i = pos; i < arr.length; i++) { if(dfs(arr, i + 1, target - arr[i])) return true; } return false; } public static void main(String[] args) { SumToATarget app = new SumToATarget(); System.out.println(app.solution(new int[] { 3, 5, 6, 7, 8, 10, 15 }, 15)); System.out.println(app.solution(new int[] { 8, 7, 10, 15, 5, 6, 3 }, 15)); System.out.println(app.solution(new int[] { 11, 6, 5, 1, 7, 13, 12 }, 15)); } }
import org.junit.Assert; import org.junit.Test; public class AccountTest { @Test public void accountTest(){ BankAccount account = new BankAccount(1000); account.inputMoney(60); Assert.assertEquals(1060, account.getMoney()); } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ArbeitsvorgangTypType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.REPARIERIstdatenType; import java.io.StringWriter; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; public class REPARIERIstdatenTypeBuilder { public static String marshal(REPARIERIstdatenType rEPARIERIstdatenType) throws JAXBException { JAXBElement<REPARIERIstdatenType> jaxbElement = new JAXBElement<>(new QName("TESTING"), REPARIERIstdatenType.class , rEPARIERIstdatenType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private ArbeitsvorgangTypType arbeitsvorgang; private String aggregat; private XMLGregorianCalendar zeitpunktDurchsatz; public REPARIERIstdatenTypeBuilder setArbeitsvorgang(ArbeitsvorgangTypType value) { this.arbeitsvorgang = value; return this; } public REPARIERIstdatenTypeBuilder setAggregat(String value) { this.aggregat = value; return this; } public REPARIERIstdatenTypeBuilder setZeitpunktDurchsatz(XMLGregorianCalendar value) { this.zeitpunktDurchsatz = value; return this; } public REPARIERIstdatenType build() { REPARIERIstdatenType result = new REPARIERIstdatenType(); result.setArbeitsvorgang(arbeitsvorgang); result.setAggregat(aggregat); result.setZeitpunktDurchsatz(zeitpunktDurchsatz); return result; } }
import java.util.Scanner; public class Scope { private static Scanner input = new Scanner(System.in); public static void main(String[] args) { UnitMatrix unitMatrix = new UnitMatrix(); unitMatrix.setSize(10); unitMatrix.print(); } static class UnitMatrix { int size; void setSize(int newSize) { this.size = newSize; } void print() { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (i == j) { System.out.println("1 "); } else { System.out.println("0 "); } } System.out.println(""); } } } }
package com.gft.digitalbank.exchange.actors.messages; /** * Created by krzysztof on 31/07/16. */ public enum UtilityMessages { SHUTDOWN, ACK; }
package org.fuserleer.ledger; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import org.fuserleer.collections.Bloom; import org.fuserleer.crypto.BLSPublicKey; import org.fuserleer.crypto.BLSSignature; import org.fuserleer.crypto.CryptoException; import org.fuserleer.crypto.Hash; import org.fuserleer.crypto.MerkleProof; import org.fuserleer.crypto.VoteCertificate; import org.fuserleer.serialization.DsonOutput; import org.fuserleer.serialization.SerializerId2; import org.fuserleer.utils.Numbers; import org.fuserleer.utils.UInt256; import org.fuserleer.serialization.DsonOutput.Output; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.primitives.Longs; @SerializerId2("ledger.state.certificate") public final class StateCertificate extends VoteCertificate { @JsonProperty("block") @DsonOutput(Output.ALL) private Hash block; @JsonProperty("atom") @DsonOutput(Output.ALL) private Hash atom; @JsonProperty("state") @DsonOutput(Output.ALL) private StateKey<?, ?> state; @JsonProperty("input") @DsonOutput(Output.ALL) private UInt256 input; @JsonProperty("output") @DsonOutput(Output.ALL) private UInt256 output; @JsonProperty("execution") @DsonOutput(Output.ALL) private Hash execution; // FIXME need to implement some way to have agreement on producers as maybe weakly-subjective and dishonest actors can attempt to inject vote power @JsonProperty("producer") @DsonOutput(value = {Output.API, Output.WIRE, Output.PERSIST}) private BLSPublicKey producer; // FIXME merkle and audit are for remote block proofing // not included in certificate hash currently so that aggregated state vote signatures can be verified @JsonProperty("merkle") @DsonOutput(value = {Output.API, Output.WIRE, Output.PERSIST}) private Hash merkle; @JsonProperty("audit") @DsonOutput(value = {Output.API, Output.WIRE, Output.PERSIST}) private List<MerkleProof> audit; // FIXME need to implement some way to have agreement on powers as weakly-subjective and dishonest actors can attempt to inject vote power @JsonProperty("powers") @DsonOutput(value = {Output.API, Output.WIRE, Output.PERSIST}) private Hash powers; @JsonProperty("power_bloom") @DsonOutput(value = {Output.API, Output.WIRE, Output.PERSIST}) private VotePowerBloom powerBloom; @SuppressWarnings("unused") private StateCertificate() { super(); // FOR SERIALIZER // } public StateCertificate(final StateKey<?, ?> state, final Hash atom, final Hash block, final BLSPublicKey producer, final UInt256 input, final UInt256 output, final Hash execution, final Hash merkle, final List<MerkleProof> audit, final VotePowerBloom powers, final Bloom signers, final BLSSignature signature) throws CryptoException { this(state, atom, block, producer, input, output, execution, merkle, audit, powers.getHash(), signers, signature); Objects.requireNonNull(powers, "Powers is null"); Numbers.isZero(powers.count(), "Powers is empty"); Numbers.isZero(powers.getTotalPower(), "Total vote power is zero"); this.powerBloom = powers; } public StateCertificate(final StateKey<?, ?> state, final Hash atom, final Hash block, final BLSPublicKey producer, final UInt256 input, final UInt256 output, final Hash execution, final Hash merkle, final List<MerkleProof> audit, final Hash powers, final Bloom signers, final BLSSignature signature) throws CryptoException { super(Objects.requireNonNull(execution, "Execution is null").equals(Hash.ZERO) == false ? StateDecision.POSITIVE : StateDecision.NEGATIVE, signers, signature); Objects.requireNonNull(state, "State is null"); Objects.requireNonNull(block, "Block is null"); Hash.notZero(block, "Block is ZERO"); Objects.requireNonNull(powers, "Powers is null"); Hash.notZero(powers, "Block is ZERO"); Objects.requireNonNull(producer, "Producer is null"); Objects.requireNonNull(atom, "Atom is null"); Hash.notZero(atom, "Atom is ZERO"); Objects.requireNonNull(merkle, "Merkle is null"); Hash.notZero(merkle, "Merkle is ZERO"); Objects.requireNonNull(audit, "Audit is null"); Numbers.isZero(audit.size(), "Audit is empty"); this.state = state; this.atom = atom; this.block = block; this.producer = producer; this.input = input; this.output = output; this.execution = execution; this.merkle = merkle; this.powers = powers; this.audit = new ArrayList<MerkleProof>(audit); this.powers = powers; } public Hash getBlock() { return this.block; } public BLSPublicKey getProducer() { return this.producer; } public long getHeight() { return Longs.fromByteArray(this.block.toByteArray()); } public Hash getAtom() { return this.atom; } public <T extends StateKey<?, ?>> T getState() { return (T) this.state; } public UInt256 getInput() { return this.input; } public UInt256 getOutput() { return this.output; } public Hash getExecution() { return this.execution; } @Override public <T> T getObject() { return (T) this.state; } public Hash getMerkle() { return this.merkle; } public List<MerkleProof> getAudit() { return Collections.unmodifiableList(this.audit); } public Hash getPowers() { return this.powers; } public VotePowerBloom getPowerBloom() { return this.powerBloom; } @Override protected Hash getTarget() throws CryptoException { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(this.getState().toByteArray()); baos.write(this.atom.toByteArray()); baos.write(this.block.toByteArray()); baos.write(this.producer.toByteArray()); baos.write(this.execution.toByteArray()); // TODO input AND output can be null?? if (this.output != null) baos.write(this.output.toByteArray()); if (this.input != null) baos.write(this.input.toByteArray()); return Hash.from(baos.toByteArray()); } catch (IOException ioex) { throw new CryptoException(ioex); } } }
package responses; public class ResponsePagamento extends ResponsePagamentoAbstract{ private String valor; private String protocolo; private ValidaPagamentoService validaPagamentoService; public ResponsePagamento(String valor, String nomeJms) { super(nomeJms); String[] split = valor.split(";"); this.valor = split[0]; this.protocolo = split[1]; } @Override public boolean isSucessPagto() { return validaPagamentoService.isPagamentoValido(this.valor); } @Override public String getProtocolo(){ return this.protocolo; } public ValidaPagamentoService getValidaPagamentoService() { return validaPagamentoService; } public void setValidaPagamentoService(ValidaPagamentoService validaPagamentoService) { this.validaPagamentoService = validaPagamentoService; } }
package com.snab.tachkit.allForm; import com.snab.tachkit.asyncTaskCustom.AsyncTaskGet; import com.snab.tachkit.additional.ParamOfField; import com.snab.tachkit.asyncTaskCustom.LoginTask; import com.snab.tachkit.globalOptions.SharedPreferencesCustom; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import com.snab.tachkit.R; import com.snab.tachkit.adapters.FormItemAdapter; import com.snab.tachkit.globalOptions.Global; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.snab.tachkit.globalOptions.fieldOptions.*; import static com.snab.tachkit.globalOptions.fieldOptions.LIST_VIEW_DIALOG; import static com.snab.tachkit.globalOptions.fieldOptions.SEARCH_LIST_VIEW_CITY; /** * Created by Ringo on 28.01.2015. * Родительский фрагмент для всех форм, где есть поля ввода */ public abstract class ParentFormFragment extends Fragment implements View.OnClickListener{ public View view = null; // корневая вьюшка public View viewAdd = null; // вьюшка с ошибками public ListView containerForm; // ListView с полями public LinearLayout container; // Родитель фрагмента // список полей формы public ArrayList<ParamOfField> fields; // адаптер для листвью public FormItemAdapter formItemAdapter; // выбранный на данный момент элемент int selectedField = -1; /** * отвечает за сохранение фрагмента во всех состояниях активити * @param fragment * @return */ public static ParentFormFragment newInstance(ParentFormFragment fragment) { fragment.setRetainInstance(true); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if(view == null) { view = inflater.inflate(R.layout.form, container, false); this.container = (LinearLayout)view; initForm(); }else{ container.removeView(view); } return view; } /** * Возвращает список с описанием полей, по которому будет строиться форма * * @return */ public ArrayList<ParamOfField> generationField(){ return null; } @Override /** * Обработка закрытия диалоговых окон */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { if(resultCode == getActivity().RESULT_OK) { ParamOfField paramOfField = fields.get(selectedField); switch (requestCode) { // возврат результата при снятии с камеры фотки case FormItemAdapter.REQUEST_CODE_PHOTO: formItemAdapter.addPhotoInListView(intent); break; // возврат результата при выборе фоток из галереи case FormItemAdapter.GALLERY_REQUEST: formItemAdapter.addPhotoInListView(intent); break; // возврат результата при выборе двух значений из диалогового окна case PICKER_DIALOG: ArrayList<ParamOfField.VariableStructure> valueA = intent.getParcelableArrayListExtra("value"); if(valueA.get(0).id > valueA.get(1).id){ ParamOfField.VariableStructure a = valueA.get(1); valueA.set(1, valueA.get(0)); valueA.set(0, a); } paramOfField.setResult(valueA); formItemAdapter.notifyDataSetChanged(); break; // возврат результата при выборе одного резльтата из диалогового окна case LIST_VIEW_DIALOG: case SEARCH_LIST_VIEW_DIALOG: case SEARCH_LIST_VIEW_CITY: ParamOfField.VariableStructure value = intent.getParcelableExtra("value"); if(value != null){ paramOfField.setResult(new ArrayList(Arrays.asList(value))); setDataDifferent(paramOfField, value); }else{ paramOfField.setResult(null); } formItemAdapter.notifyDataSetChanged(); break; default: break; } } } /** * Инициализация формы. */ private void initForm(){new initForm(getActivity(), this).execute();} /** * запись результата выбора в диалоговом окней со списокм * @param paramOfField * @param value */ public abstract void setDataDifferent(ParamOfField paramOfField, ParamOfField.VariableStructure value); public void initFormElements(){ view.findViewById(R.id.loadingPanel).setVisibility(View.GONE); containerForm = (ListView) view.findViewById(R.id.container_form); formItemAdapter = new FormItemAdapter(getActivity(), android.R.layout.simple_list_item_1, fields); formItemAdapter.setFragment(this); containerForm.setAdapter(formItemAdapter); containerForm.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectedField = position; switch (fields.get(position).type) { case SEARCH_LIST_VIEW_DIALOG: formItemAdapter.searchListViewDialogInit(position); break; case PICKER_DIALOG: formItemAdapter.pickerDialogInit(position); break; case LIST_VIEW_DIALOG: formItemAdapter.customAdapterSelectDialogFragmentInit(position); break; case SEARCH_LIST_VIEW_CITY: formItemAdapter.selectCityDialogInit(position); break; } } }); } /** * добавляет форму ошибок */ public void initError(){ view.findViewById(R.id.loadingPanel).setVisibility(View.GONE); container.addView(viewAdd); viewAdd.findViewById(R.id.event_btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { initTask(); } }); if(containerForm != null){ containerForm.setVisibility(View.GONE); } } /** * повторная попытка загрузить */ public void initTask(){ view.findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE); if(viewAdd != null){ container.removeView(viewAdd); } if(containerForm != null) { containerForm.setVisibility(View.VISIBLE); } initForm(); } /** * генерация информации в нужный вид для отправки на сервер */ public void sendToServer(){} /** * очиска всех полей формы (пока необъодимо только для поиска) */ public void sendToServerClear(){} public String getSubStr(String string, String pattern) { Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(string); if(m.find()) { return m.group(1); } else { return null; } } /** * очищаем все заполненные поля */ public void clearField(){ for(int i = 2 ; i < fields.size(); i++){ fields.get(i).setResult(null); } formItemAdapter.notifyDataSetChanged(); } /** * поток загрузки информации о полях * @param name * @param fields * @return */ public int indexField(String name, ArrayList<ParamOfField> fields){ return fields.indexOf(new ParamOfField(name)); } public class initForm extends AsyncTaskGet { private ParentFormFragment fragment; public initForm(Context context, ParentFormFragment fragment){ this.ctx = context; this.fragment = fragment; } public void requestBefore(){ fields = generationField(); fragment.requestBefore(this); } @Override protected String doInBackground(Void... params) { fragment.doInBackground(this); return null; } @Override public void initJson(String str) { fragment.initJson(this, str); } @Override public void initNotConnection() { viewAdd = getActivity().getLayoutInflater().inflate(R.layout.is_online, container, false); initError(); } @Override public void initRuntimeError() { viewAdd = getActivity().getLayoutInflater().inflate(R.layout.runtime_exeption, container, false); initError(); } @Override public void initErrorLoadData() { viewAdd = getActivity().getLayoutInflater().inflate(R.layout.error_load_data, container, false); initError(); } @Override protected void onPostExecute(String strJson) { super.onPostExecute(strJson); if (showCard) { initFormElements(); fragment.onPostExecute(); } } } public abstract void requestBefore(initForm task); public abstract void doInBackground(initForm task); public abstract void initJson(initForm task, String str); public abstract void onPostExecute(); /** * заполнение поля "Город", если таковой имеется * @param atr */ public void setCity(ArrayList<ParamOfField> atr){ if(SharedPreferencesCustom.containsCityId(getActivity())) { for (int i = 0; i < atr.size(); i++) { if (atr.get(i).name.equals("city")) { atr.get(i).setResult(new ArrayList((Arrays.asList(new ParamOfField.VariableStructure(SharedPreferencesCustom.getCityId(getActivity()), SharedPreferencesCustom.getCityName(getActivity())))))); break; } } } } /** * заполнение данных для отправки на сервер при пост запросе * @return */ public ArrayList<NameValuePair> fillFormData(){ ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("app_key", Global.appKey)); return nameValuePairs; } /** * получение значения статуса из строки * @param string - строка с сервера * @return */ public Boolean getStatusSendFromSever(String string) { return Boolean.valueOf(getSubStr(string, "\"status\":(\\w+)")); } /** * ошибка подключения при отправки на сервер */ public void errorSentFromServerPost(){ view.findViewById(R.id.loadingPanel).setVisibility(View.GONE); container.addView(viewAdd); viewAdd.findViewById(R.id.event_btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ViewGroup)(viewAdd.getParent())).removeView(viewAdd); sendToServer(); } }); } @Override public void onClick(View v) { } /** * попытка авторизироваться */ public void authorization(){ new LoginTask(getActivity(), getNameValuePairs()) { @Override public void okLoginDo() { } @Override public void reloadLogin() { authorization(); } @Override public void notLoginDo() { view.findViewById(R.id.loadingPanel).setVisibility(View.GONE); view.findViewById(R.id.container_form).setVisibility(View.VISIBLE); } }.execute(); } public List<NameValuePair> getNameValuePairs(){ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("app_key", Global.appKey)); for(int i = 0; i < fields.size(); i++) { if(nameValuePairs.size() == 3) break; ParamOfField paramOfField = fields.get(i); if(paramOfField.name.equals("login") || paramOfField.name.equals("phone1") || paramOfField.name.equals("phone")) { nameValuePairs.add(new BasicNameValuePair("login", paramOfField.result.get(0).name)); }else{ if(paramOfField.name.equals("password")) { nameValuePairs.add(new BasicNameValuePair(paramOfField.name, paramOfField.result.get(0).name)); } } } return nameValuePairs; } }
package com.kh.runLearn.board.model.vo; import java.sql.Date; public class Board_Image { private String b_changed_name; private String b_origin_name; private String b_file_path; private Date b_upload_date; private int b_num; public Board_Image() {} public Board_Image(String b_changed_name, String b_origin_name, String b_file_path, Date b_upload_date, int b_num) { super(); this.b_changed_name = b_changed_name; this.b_origin_name = b_origin_name; this.b_file_path = b_file_path; this.b_upload_date = b_upload_date; this.b_num = b_num; } public String getB_changed_name() { return b_changed_name; } public void setB_changed_name(String b_changed_name) { this.b_changed_name = b_changed_name; } public String getB_origin_name() { return b_origin_name; } public void setB_origin_name(String b_origin_name) { this.b_origin_name = b_origin_name; } public String getB_file_path() { return b_file_path; } public void setB_file_path(String b_file_path) { this.b_file_path = b_file_path; } public Date getB_upload_date() { return b_upload_date; } public void setB_upload_date(Date b_upload_date) { this.b_upload_date = b_upload_date; } public int getB_num() { return b_num; } public void setB_num(int b_num) { this.b_num = b_num; } @Override public String toString() { return "BoardImage [b_changed_name=" + b_changed_name + ", b_origin_name=" + b_origin_name + ", b_file_path=" + b_file_path + ", b_upload_date=" + b_upload_date + ", b_num=" + b_num + "]"; } }
package com.CoreJava; import java.util.*; public class StackEx { public static void main(String[] args) { Stack s=new Stack(); s.push("Karishma"); s.push("Susan"); s.push("Elena"); s.push("Dawny"); s.push("Akhil"); System.out.println("stack elements:"+s); System.out.println("First Element:"+s.peek()); System.out.println("stack elements:"+s); System.out.println("Popping out:"+s.pop()); System.out.println("stack elements:"+s); s.push("Java"); System.out.println("stack elements after adding:"+s); System.out.println("Popping out:"+s.pop()); System.out.println("stack elements:"+s); System.out.println("First element:"+s.peek()); Enumeration e=s.elements(); System.out.println("stack elements are:"); while(e.hasMoreElements()) System.out.println(e.nextElement()); } }
package com.qgil.common.utils; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import org.codehaus.jackson.map.ObjectMapper; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.alibaba.fastjson.JSONObject; import com.qgil.common.pojo.AccessToken; import com.qgil.common.pojo.AuthToken; import com.qgil.common.pojo.Constant; import com.qgil.common.pojo.PaySendData; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder; public class PayUtils { /** * 扩展xstream,使其支持name带有"_"的节点 */ public static XStream xStream = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_"))); public static ObjectMapper jsonObjectMapper = new ObjectMapper(); /** * 根据code获取微信授权access_token */ public static AuthToken getTokenByAuthCode(String code) { AuthToken authToken = null; StringBuilder json = new StringBuilder(); try { URL url = new URL(Constant.Authtoken_URL(code)); URLConnection uc = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { json.append(inputLine); } in.close(); // 将json字符串转成javaBean authToken = jsonToEntity(json.toString(), AuthToken.class); } catch (IOException ex) { System.out.println("获取access_token异常"); } return authToken; } public static String getTicket(String access_token) { String res = ""; StringBuilder json = new StringBuilder(); try { URL url = new URL("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi"); URLConnection uc = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { json.append(inputLine); } in.close(); // 将json字符串转成javaBean JSONObject result = JSONObject.parseObject(json.toString()); res = (String) result.get("ticket"); } catch (IOException ex) { System.out.println("获取access_token异常"); } return res; } public static String SHA1(String str) { try { MessageDigest digest = java.security.MessageDigest .getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可 digest.update(str.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexStr = new StringBuffer(); // 字节数组转换为 十六进制 数 for (int i = 0; i < messageDigest.length; i++) { String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); if (shaHex.length() < 2) { hexStr.append(0); } hexStr.append(shaHex); } return hexStr.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } /** * 获取微信签名 * * @param map * 请求参数集合 * @return 微信请求签名串 */ public static String getSign(SortedMap<String, Object> map) { StringBuffer buffer = new StringBuffer(); Set<Map.Entry<String, Object>> set = map.entrySet(); Iterator<Map.Entry<String, Object>> iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry<String, Object> entry = iterator.next(); String k = entry.getKey(); Object v = entry.getValue(); // 参数中sign、key不参与签名加密 if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) { buffer.append(k + "=" + v + "&"); } } buffer.append("key=" + Constant.KEY); String sign = MD5.MD5Encode(buffer.toString()).toUpperCase(); return sign; } /** * 解析微信服务器发来的请求 * * @param inputStream * @return 微信返回的参数集合 */ @SuppressWarnings("unchecked") public static Map<String, String> parseXml(InputStream inputStream) { SortedMap<String, String> map = new TreeMap<String, String>(); try { // 获取request输入流 SAXReader reader = new SAXReader(); Document document = reader.read(inputStream); // 得到xml根元素 Element root = document.getRootElement(); // 得到根元素所有节点 List<Element> elementList = root.elements(); // 遍历所有子节点 for (Element element : elementList) { map.put(element.getName(), element.getText()); } // 释放资源 inputStream.close(); } catch (Exception e) { e.printStackTrace(); System.out.println("微信工具类:解析xml异常"); } return map; } /** * 请求参数转换成xml * * @param data * @return xml字符串 */ public static String sendDataToXml(PaySendData data) { xStream.autodetectAnnotations(true); xStream.alias("xml", PaySendData.class); return xStream.toXML(data); } /** * 获取当前时间戳 * * @return 当前时间戳字符串 */ public static String getTimeStamp() { return String.valueOf(System.currentTimeMillis() / 1000); } /** * 获取指定长度的随机字符串 * * @param length * @return 随机字符串 */ public static String getRandomStr(int length) { String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); } /** * 判断空字符串 */ public static boolean isEmpty(String string) { if (string == null) { return true; } string = string.trim(); if (string.equals("")) { return true; } return false; } /** * Json字符转Java实体 * * @param jsonString * Json字符串 * @param entityType * 实体类型 * @return default null,表示转换失败 */ public static <T> T jsonToEntity(String jsonString, Class<T> entityType) { T entity = null; try { entity = jsonObjectMapper.readValue(jsonString, entityType); } catch (Exception e) { System.out.println("Json转换异常");; } return entity; } /** * 将微信服务器发送的Request请求中Body的XML解析为Map * * @param request * @return * @throws Exception */ public static Map<String, String> parseRequestXmlToMap(HttpServletRequest request) { // 解析结果存储在HashMap中 Map<String, String> resultMap = null; try { InputStream inputStream = request.getInputStream(); resultMap = parseInputStreamToMap(inputStream); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("parseRequestXmlToMap解析支付回调xml报错IOException==>" + e.getMessage()); } return resultMap; } /** * 将输入流中的XML解析为Map * * @param inputStream * @return * @throws DocumentException * @throws IOException */ public static Map<String, String> parseInputStreamToMap(InputStream inputStream){ // 解析结果存储在HashMap中 Map<String, String> map = new HashMap<String, String>(); //释放资源 try { // 读取输入流 SAXReader reader = new SAXReader(); Document document = reader.read(inputStream); //得到xml根元素 Element root = document.getRootElement(); // 得到根元素的所有子节点 List<Element> elementList = root.elements(); //遍历所有子节点 for (Element e : elementList) { map.put(e.getName(), e.getText()); } inputStream.close(); } catch (IOException e1) { System.out.println("parseInputStreamToMap解析支付回调xml报错IOException==>" + e1.getMessage()); } catch (DocumentException e1) { // TODO Auto-generated catch block System.out.println("parseInputStreamToMap解析支付回调xml报错DocumentException==>" + e1.getMessage()); } return map; } /** * 将String类型的XML解析为Map * * @param str * @return * @throws Exception */ public static Map<String, String> parseXmlStringToMap(String str) { Map<String, String> resultMap = null; try { InputStream inputStream = new ByteArrayInputStream(str.getBytes("UTF-8")); resultMap = parseInputStreamToMap(inputStream); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block System.out.println("parseXmlStringToMap解析支付回调xml报错UnsupportedEncodingException==>" + e.getMessage()); } return resultMap; } }
package com.banlv.road.support.network.nio; import com.banlv.road.exception.RemoteSendRequestException; import java.io.IOException; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; /** * @author :Lambert Wang * @date :Created in 2021/8/12 9:46 * @description: * @modified By: * @version: 1.0.0 */ public class RemoteHelper { public static void invokeSysn(final String addr, final long timeoutMills) { SocketAddress socketAddress = RemoteUtil.string2SocketAddress(addr); SocketChannel socketChannel = RemoteUtil.connect(socketAddress); long beginTime = System.currentTimeMillis(); if(socketChannel != null) { boolean sendRequestOk = false; try{ socketChannel.configureBlocking(true); socketChannel.socket().setSoTimeout((int) timeoutMills); ByteBuffer byteBuffer = ByteBuffer.allocate(4); byteBuffer.putInt(2); while(byteBuffer.hasRemaining()) { int length = socketChannel.write(byteBuffer); if(length >0 ) { if(byteBuffer.hasRemaining()) { if((System.currentTimeMillis() - beginTime) > timeoutMills) { throw new RemoteSendRequestException(addr); } } } else { throw new RemoteSendRequestException(addr); } } Thread.sleep(1); sendRequestOk = true; } catch (Exception e) { e.printStackTrace(); } finally { try{ socketChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
package com.duanxr.yith.midium; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author 段然 2021/10/8 */ public class RepeatedDNASequences { /** * The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'. * * For example, "ACGAATTCCG" is a DNA sequence. * When studying DNA, it is useful to identify repeated sequences within the DNA. * * Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order. * *   * * Example 1: * * Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" * Output: ["AAAAACCCCC","CCCCCAAAAA"] * Example 2: * * Input: s = "AAAAAAAAAAAAA" * Output: ["AAAAAAAAAA"] *   * * Constraints: * * 1 <= s.length <= 105 * s[i] is either 'A', 'C', 'G', or 'T'. * * 所有 DNA 都由一系列缩写为 'A','C','G' 和 'T' 的核苷酸组成,例如:"ACGAATTCCG"。在研究 DNA 时,识别 DNA 中的重复序列有时会对研究非常有帮助。 * * 编写一个函数来找出所有目标子串,目标子串的长度为 10,且在 DNA 字符串 s 中出现次数超过一次。 * *   * * 示例 1: * * 输入:s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" * 输出:["AAAAACCCCC","CCCCCAAAAA"] * 示例 2: * * 输入:s = "AAAAAAAAAAAAA" * 输出:["AAAAAAAAAA"] *   * * 提示: * * 0 <= s.length <= 105 * s[i] 为 'A'、'C'、'G' 或 'T' * */ class Solution { public List<String> findRepeatedDnaSequences(String s) { Set<String> list = new HashSet<>(); Set<String> set = new HashSet<>(); for (int i = 0; i < s.length() - 9; i++) { String s1 = s.substring(i, i + 10); if (!set.add(s1)) { list.add(s1); } } return new ArrayList<>(list); } } }
/* * 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 Helper.Iterables; import java.util.Map; /** * * @author Michi */ public class MapExtensions { public static <A,B> String MapToString(Map<A,B> map){ StringBuilder builder = new StringBuilder(); builder.append("{"); for(Map.Entry<A,B> e : map.entrySet()){ builder.append(" "); builder.append(e.getKey().toString()); builder.append("->"); builder.append(e.getValue().toString()); builder.append(" ;"); } if(!map.entrySet().isEmpty()){ builder.delete(builder.length()-1, builder.length()); } builder.append("}"); return builder.toString(); } }
package dominio; /** * Clase que va ganando el personaje al ganar una * batalla, mejoran los atributos del mismo y se * guardan en un inventario */ public class Objeto { private Integer id; private static final int CANTIDADDEOBJETOS = 19; protected String nombre; protected int valor; protected String atributoModificado; protected MyRandom rand = new MyRandom(); /** * Creo un Objeto random */ public Objeto() { id = rand.nextInt(CANTIDADDEOBJETOS) + 1; asignarObjeto(); } /** * Creo un objeto con una key definida * @param key Numero del ID del objeto a crear */ public Objeto(final int key) { id = key; asignarObjeto(); } /** * Los objetos dan bonus para los atributos : saludTope, energiaTope, * destreza, defensa, inteligencia y fuerza */ private void asignarObjeto() { String matrizObjetos[][] = {{"Brazalete", "10", "saludTope" }, {"Collar", "25", "saludTope" }, {"Amuleto", "50", "saludTope" }, {"Botas", "10", "energiaTope" }, {"Anillo", "25", "energiaTope" }, {"Pendientes", "50", "energiaTope" }, {"Guantes", "5", "destreza" }, {"Shuriken", "15", "destreza" }, {"Katana", "25", "destreza" }, {"Casco", "10", "defensa" }, {"Escudo", "15", "defensa" }, {"Armadura", "20", "defensa" }, {"Capa", "10", "inteligencia" }, {"Sombrero", "20", "inteligencia" }, {"Cetro", "30", "inteligencia" }, {"Cuchillo", "5", "fuerza" }, {"Martillo", "10", "fuerza" }, {"Lanza", "15", "fuerza" }, {"Hacha", "20", "fuerza" }, {"Espada", "20", "fuerza" } }; if (id > 0 && id < matrizObjetos.length) { nombre = matrizObjetos[id - 1][0]; valor = Integer.parseInt(matrizObjetos[id - 1][1]); atributoModificado = matrizObjetos[id - 1][2]; } } /** * Obtengo el atributo que modifica el objeto * @return String Nombre del atributo modificado */ public String getAtributoModificado() { return atributoModificado; } /** * Obtengo el nombre del objeto * EJ: Casco, Espada, Hacha * @return String nombre del objeto */ public String getNombre() { return nombre; } /** * Obtengo el valor Int del objeto * ej: Espada +20 * @return int el valor del objeto */ public int getValor() { return valor; } /** * Genera un numero random * @return MyRandom numero random */ public MyRandom getRand() { return rand; } /** * Obtengo el ID del objeto * @return Integer ID del objeto */ public Integer getId() { return id; } /** * Se le ingresa una ID al objeto * @param id Integer como ID del objeto */ public void setId(final Integer id) { this.id = id; } }
package com.axis.myinterface; import android.content.Context; import com.axis.util.AboutSong; import org.json.JSONException; import java.io.IOException; import java.util.List; /** * Created by mjaso on 2016/1/18. */ public interface ISearchFor { String UTF_8 = "utf-8"; String GB_2312 = "gb2312"; void search(String want) throws IOException, JSONException; /** * @return return the result of search * use String as result's type */ List<AboutSong> getResult(Context context, String want) throws IOException, JSONException; }
package cn.bs.zjzc.model.impl; import cn.bs.zjzc.model.IRegisterNextModel; import cn.bs.zjzc.model.bean.RegisterRequestBody; import cn.bs.zjzc.model.callback.HttpTaskCallback; import cn.bs.zjzc.model.response.FinishRegisterResponse; import cn.bs.zjzc.net.GsonCallback; import cn.bs.zjzc.net.PostHttpTask; import cn.bs.zjzc.net.RequestUrl; /** * Created by Ming on 2016/6/7. */ public class RegisterNextModel implements IRegisterNextModel { @Override public void register(final RegisterRequestBody registerRequestBody, final HttpTaskCallback<FinishRegisterResponse.DataBean> callback) { String url = RequestUrl.getRequestPath(RequestUrl.SubPaths.regPath); //注册请求 PostHttpTask<FinishRegisterResponse> httpTask = new PostHttpTask<>(url); httpTask.addParams("token", registerRequestBody.token) .addParams("acount", registerRequestBody.acount) .addParams("name", registerRequestBody.name) .addParams("passwd", registerRequestBody.passwd) .addParams("code", registerRequestBody.code) .execute(new GsonCallback<FinishRegisterResponse>() { @Override public void onFailed(String errorInfo) { callback.onTaskFailed(errorInfo); } @Override public void onSuccess(FinishRegisterResponse response) { callback.onTaskSuccess(response.data); } }); } }
package com.comsoftacuity.controller; import java.util.ArrayList; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.comsoftacuity.dto.AccountTypedto; import com.comsoftacuity.dto.Accountdto; import com.comsoftacuity.dto.PaymentLogdto; import com.comsoftacuity.dto.Suggestiondto; import com.comsoftacuity.entity.Account; import com.comsoftacuity.entity.AccountType; import com.comsoftacuity.entity.PaymentLog; import com.comsoftacuity.mapper.Mapper; import com.comsoftacuity.service.ReportManagerService; import com.comsoftacuity.specifications.AccountTypeSpecification; import com.comsoftacuity.specifications.PaymentLogSpecification; import com.comsoftacuity.specifications.SuggestionSpecification; @CrossOrigin(origins = "http://localhost:8081") @RestController public class AccountController { @Autowired private ReportManagerService reportManagerService; /* Create Operation */ @RequestMapping(method = RequestMethod.POST, value = "/accounts/{description}/create") public String createAccount(@RequestBody Accountdto accountdto, @PathVariable String description) { AccountType accountType = reportManagerService.getAccountTypeRepository().findByDescription(description); if (accountType != null) { reportManagerService.getAccountRepository().save(Mapper.mapToAccount(accountdto, accountType)); return "Account creation success"; } return "Account creation failed"; } @RequestMapping(method = RequestMethod.POST, value = "/accounts/payment") public String makePayment(@RequestBody PaymentLogdto paymentLogdto) { if (paymentLogdto != null) { reportManagerService.getPaymentLogRepository().save(Mapper.mapToPaymentLog(paymentLogdto)); return "Payment successfull"; } return "Error"; } /* Read Operation */ @RequestMapping("/accounts/{id}") public Accountdto getAccount(@PathVariable Integer id) { return Mapper.mapToAccountdto(reportManagerService.getAccountRepository().findById(id).get()); } @RequestMapping("/accounts/account-types") public List<AccountTypedto> getAllAccountType() { List<AccountType> accountType = new ArrayList<>(); reportManagerService.getAccountTypeRepository().findAll().forEach(accountType::add); return Mapper.mapToAccountTypedtoList(accountType); } @RequestMapping("/accounts/account-types/{description}") public AccountType getAccountTypeByDescription(@PathVariable String description) { return reportManagerService.getAccountTypeRepository().findByDescription(description); } @RequestMapping("/accounts") public List<Accountdto> getAllAccounts() { List<Account> accounts = new ArrayList<>(); reportManagerService.getAccountRepository().findAll().forEach(accounts::add); return Mapper.mapToAccountdtoList(accounts); } @GetMapping("/accounts/payment-logs") public List<PaymentLogdto> getAllPaymentLog() { List<PaymentLog> paymentLogs = new ArrayList<>(); reportManagerService.getPaymentLogRepository().findAll().forEach(paymentLogs::add); List<PaymentLogdto> paymentLogdtoList = Mapper.mapToPaymentLogList(paymentLogs); return paymentLogdtoList; } // Update Operation @RequestMapping(method = RequestMethod.PUT, value = "/accounts/update") public String updateAccount(@RequestBody Accountdto accountdto) { try { reportManagerService.getAccountRepository() .save(Mapper.mapToAccount(accountdto, accountdto.getAccountType())); return "Account updated successful"; } catch (Exception e) { return "update failed"; } } // Delete Operation @RequestMapping(method = RequestMethod.DELETE, value = "/accounts/delete/{id}") public String deleteAccount(@PathVariable String id) { try { reportManagerService.getAccountRepository().deleteById(Integer.parseInt(id)); return "Account deleted successful"; } catch (Exception e) { return "Account deletion failed"; } } // search operation //@CrossOrigin(origins = "http://localhost:8081") @GetMapping("/accounts/account-type/{searchTerm}") public List<AccountTypedto> search(@PathVariable String searchTerm) { //List<AccountType> accountTypes = new ArrayList<>(); // accountTypes.add(reportManagerService.getAccountTypeRepository().findByDescriptionIgnoreCase(search)); /* * accountTypes = reportManagerService.getAccountTypeRepository(). * findByDescriptionContainsIgnoreCase(search); try { if * (Integer.valueOf(search) instanceof Integer) { accountTypes = * reportManagerService.getAccountTypeRepository() * .findByIdContainsOrCodeContainsAllIgnoreCase(Integer.parseInt(search), * Integer.parseInt(search)); } } catch (Exception exception) { * * } */ /*accountTypes = reportManagerService.getAccountTypeRepository() .findAll(AccountTypeSpecification.searchTerm(searchTerm)); return accountTypes;*/ return Mapper.mapToAccountTypedtoList(reportManagerService.getAccountTypeRepository().findAll(AccountTypeSpecification.searchTerm(searchTerm))); } @GetMapping("/accounts/search/paymentlog") public List<PaymentLogdto> searchPaymentLog(@RequestParam(required=false) String queryTerm) { return Mapper.mapToPaymentLogList(reportManagerService.getPaymentLogRepository().findAll(PaymentLogSpecification.queryTerm(queryTerm))); } @GetMapping("/accounts/paymentlog/suggestion") public List<Suggestiondto> getSuggestion(@RequestParam("q") String queryTerm) { //reportManagerService.getSuggestionRepository().findAll().forEach(suggestions::add); return Mapper.mapToSuggestiondtoList(reportManagerService.getSuggestionRepository() .findAll(SuggestionSpecification.queryTerm(queryTerm))); } }
package com.tencent.mm.plugin.appbrand.jsapi.file; import com.tencent.mm.plugin.appbrand.q.c; import java.nio.ByteBuffer; import java.nio.charset.Charset; class e$a$1 implements e { private final Charset lt = Charset.forName("US-ASCII"); e$a$1() { } public final String i(ByteBuffer byteBuffer) { return new String(c.k(byteBuffer), this.lt); } public final ByteBuffer ty(String str) { return ByteBuffer.wrap(str.getBytes(this.lt)); } }
/** */ package nassishneiderman.impl; import java.util.Collection; import nassishneiderman.MultipleBranchingBlock; import nassishneiderman.NassishneidermanPackage; import nassishneiderman.Sequence; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Multiple Branching Block</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link nassishneiderman.impl.MultipleBranchingBlockImpl#getSequences <em>Sequences</em>}</li> * </ul> * </p> * * @generated */ public class MultipleBranchingBlockImpl extends EObjectImpl implements MultipleBranchingBlock { /** * The cached value of the '{@link #getSequences() <em>Sequences</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSequences() * @generated * @ordered */ protected EList<Sequence> sequences; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected MultipleBranchingBlockImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return NassishneidermanPackage.Literals.MULTIPLE_BRANCHING_BLOCK; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Sequence> getSequences() { if (sequences == null) { sequences = new EObjectContainmentEList<Sequence>(Sequence.class, this, NassishneidermanPackage.MULTIPLE_BRANCHING_BLOCK__SEQUENCES); } return sequences; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case NassishneidermanPackage.MULTIPLE_BRANCHING_BLOCK__SEQUENCES: return ((InternalEList<?>)getSequences()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case NassishneidermanPackage.MULTIPLE_BRANCHING_BLOCK__SEQUENCES: return getSequences(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case NassishneidermanPackage.MULTIPLE_BRANCHING_BLOCK__SEQUENCES: getSequences().clear(); getSequences().addAll((Collection<? extends Sequence>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case NassishneidermanPackage.MULTIPLE_BRANCHING_BLOCK__SEQUENCES: getSequences().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case NassishneidermanPackage.MULTIPLE_BRANCHING_BLOCK__SEQUENCES: return sequences != null && !sequences.isEmpty(); } return super.eIsSet(featureID); } } //MultipleBranchingBlockImpl
package kata.wallet.model; public class Stock { private final StockType type; private final Integer quantity; public Stock(StockType type, Integer quantity) { this.type = type; this.quantity = quantity; } public StockType getType() { return type; } public Integer getQuantity() { return quantity; } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ArbeitsvorgangTypType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.TRANSPORTSolldatenType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.TransportArtType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.VersandTypType; import java.io.StringWriter; import java.math.BigInteger; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; public class TRANSPORTSolldatenTypeBuilder { public static String marshal(TRANSPORTSolldatenType tRANSPORTSolldatenType) throws JAXBException { JAXBElement<TRANSPORTSolldatenType> jaxbElement = new JAXBElement<>(new QName("TESTING"), TRANSPORTSolldatenType.class , tRANSPORTSolldatenType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private double tapoSuffix; private TransportArtType transportArt; private String abgangStelle; private String zielStelle; private VersandTypType versandTyp; private BigInteger tapoVariante; private Boolean geaendertKz; private ArbeitsvorgangTypType arbeitsvorgang; public TRANSPORTSolldatenTypeBuilder setTapoSuffix(double value) { this.tapoSuffix = value; return this; } public TRANSPORTSolldatenTypeBuilder setTransportArt(TransportArtType value) { this.transportArt = value; return this; } public TRANSPORTSolldatenTypeBuilder setAbgangStelle(String value) { this.abgangStelle = value; return this; } public TRANSPORTSolldatenTypeBuilder setZielStelle(String value) { this.zielStelle = value; return this; } public TRANSPORTSolldatenTypeBuilder setVersandTyp(VersandTypType value) { this.versandTyp = value; return this; } public TRANSPORTSolldatenTypeBuilder setTapoVariante(BigInteger value) { this.tapoVariante = value; return this; } public TRANSPORTSolldatenTypeBuilder setGeaendertKz(Boolean value) { this.geaendertKz = value; return this; } public TRANSPORTSolldatenTypeBuilder setArbeitsvorgang(ArbeitsvorgangTypType value) { this.arbeitsvorgang = value; return this; } public TRANSPORTSolldatenType build() { TRANSPORTSolldatenType result = new TRANSPORTSolldatenType(); result.setTapoSuffix(tapoSuffix); result.setTransportArt(transportArt); result.setAbgangStelle(abgangStelle); result.setZielStelle(zielStelle); result.setVersandTyp(versandTyp); result.setTapoVariante(tapoVariante); result.setGeaendertKz(geaendertKz); result.setArbeitsvorgang(arbeitsvorgang); return result; } }
package org.mge.general; import java.util.ArrayList; import java.util.List; public class MissingDigit { public static void main(String[] args) { System.out.println(findDigit("3x + 12 = 46")); System.out.println(findDigit("1X0 * 12 =12000")); System.out.println(findDigit("3+4=X")); System.out.println(findDigit("100* 25 = 2X00")); System.out.println(findDigit("100 / 1X =10")); System.out.println(findDigit("15 - X = 3")); } public static int findDigit(String str) { char sign = 0; int j = 0; List<String> list = new ArrayList<>(3); StringBuilder sb = new StringBuilder(); int index = -1; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c == '+' || c == '-' || c == '/' || c == '*' || c == '=') { if (c != '=') sign = c; list.add(sb.toString()); sb = new StringBuilder(); } else if (c != ' ') { if (c == 'x' || c == 'X') { j = list.size() + 1; index = sb.length(); } sb.append(c); } } list.add(sb.toString()); String res = ""; switch (sign) { case '+': if (j == 1) { res = performOperation(list.get(2), list.get(1), '-'); } else if (j == 2) { res = performOperation(list.get(2), list.get(0), '-'); } else { res = performOperation(list.get(0), list.get(1), sign); } break; case '-': if (j == 1) { res = performOperation(list.get(2), list.get(1), '+'); } else if (j == 2) { res = performOperation(list.get(0), list.get(2), '-'); } else { res = performOperation(list.get(0), list.get(1), sign); } break; case '*': if (j == 1) { res = performOperation(list.get(2), list.get(1), '/'); } else if (j == 2) { res = performOperation(list.get(2), list.get(0), '/'); } else { res = performOperation(list.get(0), list.get(1), sign); } break; case '/': if (j == 1) { res = performOperation(list.get(2), list.get(1), '*'); } else if (j == 2) { res = performOperation(list.get(0), list.get(2), '/'); } else { res = performOperation(list.get(0), list.get(1), sign); } break; } return res.charAt(index) - '0'; } static String performOperation(String s1, String s2, char sign) { int op1 = Integer.parseInt(s1); int op2 = Integer.parseInt(s2); int res = -1; switch (sign) { case '+': res = op1 + op2; break; case '-': res = op1 - op2; break; case '*': res = op1 * op2; break; case '/': res = op1 / op2; } return String.valueOf(res); } public static int findDigit1(String str) { str = str.replace(" ", "").toLowerCase(); String[] arr = str.split("-|\\+|\\*|/|="); int index = -1; if (str.contains("+")) { index = arr[0].indexOf("x"); if (index != -1) { String r = Integer.parseInt(arr[2]) - Integer.parseInt(arr[1]) + ""; return Integer.parseInt(r.substring(index, index + 1)); } index = arr[1].indexOf("x"); if (index != -1) { String r = Integer.parseInt(arr[2]) - Integer.parseInt(arr[0]) + ""; return Integer.parseInt(r.substring(index, index + 1)); } index = arr[2].indexOf("x"); if (index != -1) { String r = Integer.parseInt(arr[0]) + Integer.parseInt(arr[1]) + ""; return Integer.parseInt(r.substring(index, index + 1)); } } if (str.contains("-")) { index = arr[0].indexOf("x"); if (index != -1) { String r = Integer.parseInt(arr[2]) + Integer.parseInt(arr[1]) + ""; return Integer.parseInt(r.substring(index, index + 1)); } index = arr[1].indexOf("x"); if (index != -1) { String r = Integer.parseInt(arr[0]) - Integer.parseInt(arr[2]) + ""; return Integer.parseInt(r.substring(index, index + 1)); } index = arr[2].indexOf("x"); if (index != -1) { String r = Integer.parseInt(arr[0]) - Integer.parseInt(arr[1]) + ""; return Integer.parseInt(r.substring(index, index + 1)); } } if (str.contains("*")) { index = arr[0].indexOf("x"); if (index != -1) { String r = Integer.parseInt(arr[2]) / Integer.parseInt(arr[1]) + ""; return Integer.parseInt(r.substring(index, index + 1)); } index = arr[1].indexOf("x"); if (index != -1) { String r = Integer.parseInt(arr[2]) / Integer.parseInt(arr[0]) + ""; return Integer.parseInt(r.substring(index, index + 1)); } index = arr[2].indexOf("x"); if (index != -1) { String r = Integer.parseInt(arr[0]) * Integer.parseInt(arr[1]) + ""; return Integer.parseInt(r.substring(index, index + 1)); } } if (str.contains("/")) { index = arr[0].indexOf("x"); if (index != -1) { String r = Integer.parseInt(arr[2]) * Integer.parseInt(arr[1]) + ""; return Integer.parseInt(r.substring(index, index + 1)); } index = arr[1].indexOf("x"); if (index != -1) { String r = Integer.parseInt(arr[0]) / Integer.parseInt(arr[2]) + ""; return Integer.parseInt(r.substring(index, index + 1)); } index = arr[2].indexOf("x"); if (index != -1) { String r = Integer.parseInt(arr[0]) / Integer.parseInt(arr[1]) + ""; return Integer.parseInt(r.substring(index, index + 1)); } } return -1; } }
package com.company; public interface Figure { void show(); void move(double x, double y); void scale(double factor); double getSquare(); }
/* * 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 pboulang.pkg10117185.latihan42.tabungan; import java.util.Scanner; /** * * @author user * Nama : Andhyka Widariyanto * NIM : 10117185 * Kelas: PBO-Ulang * Tugas: Menghitung sisa pengambilan saldo */ public class PBOUlang10117185Latihan42Tabungan { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner inputer = new Scanner(System.in); System.out.println("====Program Penarikan Uang===="); System.out.print("Masukan Saldo Awal : " ); int jmh_tabungan = inputer.nextInt(); Tabungan tabungan = new Tabungan(jmh_tabungan); System.out.print("Jumlah uang yang diambil : "); int jmlh_diambil = inputer.nextInt(); tabungan.ambilUang(jmlh_diambil); tabungan.cekSaldo(); } }
package com.ai.provider; import com.ai.entity.DataLog; import org.apache.ibatis.jdbc.SQL; /** * @author : kevin * @version : Ver 1.0 * @description : * @date : 2017/10/27 */ public class DataLogDaoProvider { // public String findByCondition(@Param("id") String id, @Param("instanceName")String instanceName, String message) { public String findByCondition(DataLog dataLog) { // <if test="id != null"> // AND ID = #{id} // </if> // if (id != null) { // WHERE() // } // <if test="instanceName != null and instanceName !=''"> // AND INSTANCE_NAME = #{instanceName} // </if> // <if test="message != null and message !=''"> // AND MESSAGE = #{message} // </if> // <if test="createTimeBegin != null"> // AND CREATE_TIME >= #{createTimeBegin} // </if> // <if test="createTimeEnd != null"> // AND CREATE_TIME &lt;= #{createTimeEnd} // </if> SQL sql = new SQL().SELECT("ID,INSTANCE_NAME,CREATE_TIME").FROM("data_log"); if (dataLog.getId() != null) { sql.WHERE("ID = #{id}"); } if (dataLog.getInstanceName() != null) { sql.OR().WHERE("INSTANCE_NAME = #{instanceName}"); } String s = sql.toString(); System.out.println("sql:\n" + s); return s; } }
package com.api.automation.scenarios; import com.api.automation.helpers.PetsRequestHelper; import com.api.automation.pojo.ApiResponse; import com.api.automation.pojo.Pet; import io.restassured.response.Response; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import static com.api.automation.pojo.Status.available; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.http.HttpStatus.SC_NOT_FOUND; import static org.apache.http.HttpStatus.SC_OK; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.with; import static org.awaitility.pollinterval.FibonacciPollInterval.fibonacci; @DisplayName("Tests for pets deletion") public class DeletePetTest extends BaseTest { @Autowired private PetsRequestHelper petsRequestHelper; @Test @DisplayName("Pet deletion via /pet/{petId} endpoint") public void shouldDeleteExistingPet() { final Pet requestBody = petsRequestHelper.createPetAndAssert(available); petsRequestHelper.findByIdAndAssert(requestBody); assertThatPetWasSuccessfullyDeleted(requestBody, petsRequestHelper.deletePetById(requestBody.getId())); } @Test @DisplayName("Pet deletion via /pet/{petId} endpoint with not existing ID - 404 expected") public void shouldReturn404ForNotExistingPetWhileDeletion() { response = petsRequestHelper.deletePetById(-1); assertThat(response.getStatusCode()).isEqualTo(SC_NOT_FOUND); } private void assertThatPetWasSuccessfullyDeleted(Pet requestBody, Response response) { with().pollInterval(fibonacci(MILLISECONDS)).await().atMost(30, SECONDS).untilAsserted(() -> { assertThat(response.getStatusCode()).isEqualTo(SC_OK); ApiResponse apiResponse = response.getBody().as(ApiResponse.class); assertThat(apiResponse.getCode()).isEqualTo(200); assertThat(apiResponse.getType()).isEqualTo("unknown"); assertThat(apiResponse.getMessage()).isEqualTo(Long.toString(requestBody.getId())); }); } }
package com.mxf.course.controller; import com.mxf.course.config.BaseController; import com.mxf.course.config.ScExtException; import com.mxf.course.dao.TeacherMapper; import com.mxf.course.entity.CourseEntity; import com.mxf.course.entity.TeacherEntity; import com.mxf.course.service.TeacherService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; /** * Created by baimao * Time:2021/5/17 */ @Controller @RequestMapping("/api/v1/teacher") public class TeacherController extends BaseController { @Resource TeacherService teacherService; @RequestMapping("selectTeacherByConditions") public @ResponseBody String selectTeacherByConditions(@RequestParam("currentPage")int currentPage, @RequestParam("pageSize")int pageSize, @RequestParam(value = "teachername",required = false)String teachername, HttpServletRequest request){ return toJson(teacherService.selectTeacherByConditions(currentPage, pageSize, teachername),request); } @RequestMapping("insertTeacher") public @ResponseBody String insertTeacher(@RequestBody TeacherEntity teacherEntity, HttpServletRequest request) throws ScExtException { return toJson(teacherService.insertTeacher(teacherEntity),request); } @RequestMapping("updateTeacher") public @ResponseBody String updateTeacher(@RequestBody TeacherEntity teacherEntity, HttpServletRequest request) throws ScExtException { return toJson(teacherService.updateTeacher(teacherEntity),request); } @RequestMapping("deleteTeacher") public @ResponseBody String deleteTeacher(@RequestParam("id")int id, HttpServletRequest request) throws ScExtException { return toJson(teacherService.deleteTeacher(id),request); } }
/** * Created by edreichua on 3/2/16. */ public class PageRankDriver { // filename private static final String DartmouthCSClasses = "dartcsclass.txt"; private static final String Simple = "simple.txt"; private static final String Medium = "medium.txt"; private static final String Physics = "physcitation.txt"; // boolean flags private static final boolean isDangling = true; private static final boolean isJump = true; private static final boolean isSorted = true; public static void main(String[] args){ PageRank p = new PageRank(DartmouthCSClasses, isDangling, isJump); if(isSorted) p.printSortedResults(); else p.printResults(); } }
package com.tencent.mm.plugin.appbrand.widget.input; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Point; import android.os.Build.VERSION; import com.tencent.mm.pluginsdk.e; import com.tencent.mm.sdk.platformtools.x; public final class a { public static final boolean gGe = (VERSION.SDK_INT < 20); public final Activity activity; public boolean gGf = false; public int gGg = 0; public a(Activity activity) { this.activity = activity; } /* renamed from: apf */ public final void a() { if (this.gGf && !this.activity.isFinishing() && gGe) { l m = l.m(this.activity); if (m == null) { x.w("MicroMsg.AppBrandFixInputIssuesActivityHelper", "fixLayoutHeightIfNeed get null rootLayout"); } else { a(m); } } } public final void a(l lVar) { int i; Point point = new Point(); this.activity.getWindowManager().getDefaultDisplay().getSize(point); int eL = e.eL(this.activity); int i2 = point.y; if (this.activity.getWindow() == null || (this.activity.getWindow().getAttributes().flags & 1024) <= 0) { i = 0; } else { i = 1; } if (i != 0) { eL = 0; } x.i("MicroMsg.AppBrandFixInputIssuesActivityHelper", "fixLayoutHeightBelow20 forceHeight %d", new Object[]{Integer.valueOf(i2 - eL)}); lVar.setForceHeight(eL); } public static boolean cO(Context context) { boolean z; Resources resources = context.getResources(); int identifier = resources.getIdentifier("config_showNavigationBar", "bool", "android"); if (identifier > 0) { z = resources.getBoolean(identifier); } else { z = false; } try { Class cls = Class.forName("android.os.SystemProperties"); String str = (String) cls.getMethod("get", new Class[]{String.class}).invoke(cls, new Object[]{"qemu.hw.mainkeys"}); if ("1".equals(str)) { return false; } if ("0".equals(str)) { return true; } return z; } catch (Exception e) { } } }
package com.tencent.mm.plugin.game.wepkg.utils; import com.tencent.mm.plugin.game.wepkg.model.WepkgCrossProcessTask; import com.tencent.mm.plugin.game.wepkg.model.a; class d$1 implements Runnable { final /* synthetic */ a kfC; final /* synthetic */ WepkgCrossProcessTask kfs; d$1(WepkgCrossProcessTask wepkgCrossProcessTask, a aVar) { this.kfs = wepkgCrossProcessTask; this.kfC = aVar; } public final void run() { this.kfs.aai(); if (this.kfC != null) { this.kfC.a(this.kfs); } } }
package com.example.demo.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.example.demo.dao.UserDao; import com.example.demo.dao.UserRepository; import com.example.demo.model.User; @RestController public class UserController { @Autowired UserRepository dao; @GetMapping("/users/{uid}") public Optional<User> getUser(@PathVariable(value = "uid") int uid) { return dao.findById(uid); } @GetMapping("/users") public List<User> allUsers() { return dao.findAll(); } @PostMapping("/users") public User createUser(@RequestBody User user) { User newUser=dao.save(user); return newUser; } @PutMapping("/deposit/{uid}/{amount}) public Optional<User> updateAmount(@PathVariable(value = "uid") int uid, @RequestParam("amount") double amount) { Optional<User> user = dao.findById(uid); if(user.getBalance()>=100000.00) { System.out.println("you cannot deposit!!! you have reached maximun limit"); } user.setBalance(user.getBalance() + amount); Optional<User> updatedUser = dao.save(user); return updatedUser; } @PutMapping("/withdraw/{uid}/{withdrawalAmt}") public Optional<User> withdraw(@PathVariable("uid") int uid,@PathVariable("withdrawalAmt") double withdrawalAmt) { Optional<User> user= getUser(uid); double balance= user.getBalance(); if(balance<withdrawalAmt||balance<=1000) System.out.println("Amount cannot be withdrawn!!!!"); double newBalance= balance-withdrawalAmt; user.setBalance(newBalance); return dao.save(user); } @GetMapping("/users/balance/{uid}") public double getTotalBalance(@PathVariable(value = "uid") int uid) { Optional<User> user=dao.findById(uid); return user.getBalance(); } }
package com.mum.web.functional; import com.mum.web.entities.*; import com.mum.web.dtos.CommentInfo; import com.mum.web.dtos.PostInfo; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; public class PostFunctionUtils { @FunctionalInterface public interface PentaFunction<S, T, U, V, R> { R apply(S s, T t, U u, V v); } public static BiFunction<List<Interaction>, InteractionType, List<User>> getInteractionUserList = (interactions, interactionType) -> interactions.stream() .filter(interaction -> interaction.getInteractionType() == interactionType) .map(interaction -> interaction.getUser()) .collect(Collectors.toList()); //return all posts of all followings of the targetUser //and all posts of the targetUser //and all posts of all friends of the targetUser //and all posts of all users who the targetUser is their friends //A following B, C, D //A has list of friends D, E, F //Result: list of posts of A, [B, C, D], [D,E, F] public static BiFunction<List<User>, User, List<Post>> getTimeline = (users, targetUser) -> //B, C, D; and D, E, F; and A users.stream() .filter(u -> targetUser.getFollowings().contains(u)//return all followings of the targetUser || targetUser.getFriends().contains(u)//return all friends of the targetUser || u.equals(targetUser)) .distinct()//remove duplicate user D //Posts of B, C, D, E, F and A .flatMap(user -> user.getPosts().stream()) .sorted(Comparator.comparing(Post::getPostedDate, Comparator.reverseOrder())) .collect(Collectors.toList()); public static Function<User, List<Post>> getProfile = (user) -> //B, C, D; and D, E, F; and A user.getPosts().stream() .sorted(Comparator.comparing(Post::getPostedDate, Comparator.reverseOrder())) .collect(Collectors.toList()); public static PentaFunction<List<User>, User, Integer, Integer, List<Post>> getTimelineForPaging = (users, targetUser, m, n) -> getTimeline.apply(users, targetUser).stream().skip(m).limit(n - m + 1).collect(Collectors.toList()); public static Function<Comment, CommentInfo> convertToCommentInfo = (comment -> new CommentInfo(comment.getCommentId(), comment.getContent(), comment.getPostedDate(), AuthenticationFunctionUtils.convertToUserInfo.apply(comment.getUser()) , comment.getLikeCount() , AuthenticationFunctionUtils.converToListUserInfo.apply(comment.getLikeUserList()) , PostFunctionUtils.convertToListCommentInfo.apply(comment.getComments()))); public static Function<List<Comment>, List<CommentInfo>> convertToListCommentInfo = (comments -> comments.stream() .map(comment -> convertToCommentInfo.apply(comment)).collect(Collectors.toList())); public static Function<Post, PostInfo> convertToPostInfo = (post -> post.getPostInfo()); public static Function<List<Post>, List<PostInfo>> convertToListPostInfo = (posts -> posts.stream() .map(post -> convertToPostInfo.apply(post)).collect(Collectors.toList())); public static BiFunction<Long, List<User>, Optional<Post>> getCommentByPostId = (postId, users) -> users.stream() .flatMap(u -> u.getPosts().stream()) .filter(p -> p.getPostId().equals(postId)).findFirst(); }
package com.devcamp.currencyconverter.tools.scrapers.impl; import com.devcamp.currencyconverter.constants.Qualifiers; import com.devcamp.currencyconverter.tools.converters.impl.LocConverter; import com.devcamp.currencyconverter.tools.scrapers.api.Scraper; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; import java.math.BigDecimal; @Component(value = Qualifiers.LOC_SCRAPER) public class LocRateScraper implements Scraper { private static final String URL = "https://digitalcoinprice.com/coins/lockchain"; private static final String LOC_PRICE_ID = "quote_price"; private static final int LOC_PRICE_START_INDEX = 1; private LocConverter locConverter; @Autowired public LocRateScraper(LocConverter locConverter) { this.locConverter = locConverter; } @Override public void scrape() throws IOException { Document document = Jsoup.connect(URL).timeout(0).get(); Element priceElement = document.getElementById(LOC_PRICE_ID); BigDecimal price = new BigDecimal(priceElement.text().substring(LOC_PRICE_START_INDEX)); this.locConverter.setLocToUsdRate(price); } }
//给定一个整数数组 nums,求出数组从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i、j 两点。 // // // // 实现 NumArray 类: // // // NumArray(int[] nums) 使用数组 nums 初始化对象 // int sumRange(int i, int j) 返回数组 nums 从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i、j 两点(也就是 s //um(nums[i], nums[i + 1], ... , nums[j])) // // // // // 示例: // // //输入: //["NumArray", "sumRange", "sumRange", "sumRange"] //[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] //输出: //[null, 1, -1, -3] // //解释: //NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); //numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3) //numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1)) //numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1)) // // // // // 提示: // // // 0 <= nums.length <= 104 // -105 <= nums[i] <= 105 // 0 <= i <= j < nums.length // 最多调用 104 次 sumRange 方法 // // // // Related Topics 动态规划 // 👍 328 👎 0 package me.alvin.leetcode.editor.cn; public class RangeSumQueryImmutable { public static void main(String[] args) { NumArray2 solution = new RangeSumQueryImmutable().new NumArray2(new int[]{-2, 0, 3, -5, 2, -1}); System.out.println(solution.sumRange(0, 2)); System.out.println(solution.sumRange(2, 5)); System.out.println(solution.sumRange(0, 5)); } //leetcode submit region begin(Prohibit modification and deletion) class NumArray { //前缀和 int[] preSum; int[] nums; public NumArray(int[] nums) { this.nums = nums; preSum = new int[nums.length]; preSum[0] = nums[0]; for (int i = 1; i < nums.length; i++) { preSum[i] = preSum[i - 1] + nums[i]; } } public int sumRange(int left, int right) { return preSum[right] - preSum[left] + nums[left]; } } /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(left,right); */ //leetcode submit region end(Prohibit modification and deletion) class NumArray2 { //前缀和 int[] preSum; public NumArray2(int[] nums) { //前缀和数组多一个占位元素0,统一操作以及消除index=0的特殊情况 preSum = new int[nums.length + 1]; for (int i = 0; i < nums.length; i++) { preSum[i + 1] = preSum[i] + nums[i]; } } public int sumRange(int left, int right) { return preSum[right + 1] - preSum[left]; } } }
package com.tencent.mm.plugin.appbrand.game; import com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.i; import com.tencent.mm.sdk.platformtools.x; import java.lang.ref.WeakReference; import java.util.LinkedList; class GameGLSurfaceView$j extends Thread { public boolean fcO; boolean fzA; private boolean fzB; public boolean fzC = true; private boolean fzD = false; public boolean fzE; LinkedList<Runnable> fzF = new LinkedList(); boolean fzG = true; private i fzH; private WeakReference<GameGLSurfaceView> fzn; private boolean fzp; public boolean fzq; private boolean fzr; public boolean fzs; boolean fzt; public boolean fzu; boolean fzv; private boolean fzw; boolean fzx; boolean fzy; boolean fzz; int mHeight = 0; private int mRenderMode = 1; int mWidth = 0; GameGLSurfaceView$j(WeakReference<GameGLSurfaceView> weakReference) { this.fzn = weakReference; } public final void run() { setName("GLThread " + getId()); x.i("MicroMsg.GLThread", "starting tid=" + getId()); i.fAb.afX(); try { afM(); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.GLThread", e, "hy: InterruptedException", new Object[0]); } finally { GameGLSurfaceView.afI().g(this); } i.fAb.afY(); i iVar = i.fAb; iVar.fAc.clear(); iVar.fAd = null; } private void afK() { if (this.fzz) { this.fzz = false; this.fzA = false; } } private void afL() { if (this.fzy) { this.fzy = false; GameGLSurfaceView.afI().notifyAll(); } } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ private void afM() { /* r22 = this; r4 = new com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView$i; r0 = r22; r5 = r0.fzn; r4.<init>(r5); r0 = r22; r0.fzH = r4; r4 = 0; r0 = r22; r0.fzy = r4; r4 = 0; r0 = r22; r0.fzz = r4; r5 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); monitor-enter(r5); r4 = 0; r0 = r22; r0.fzD = r4; Catch:{ all -> 0x003b } monitor-exit(r5); Catch:{ all -> 0x003b } r14 = 0; r15 = 0; r13 = 0; r12 = 0; r11 = 0; r10 = 0; r9 = 0; r8 = 0; r7 = 0; r6 = 0; r4 = 0; r5 = r4; L_0x002e: r17 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); monitor-enter(r17); L_0x0033: r0 = r22; r4 = r0.fzp; Catch:{ all -> 0x02d7 } if (r4 == 0) goto L_0x003e; L_0x0039: monitor-exit(r17); Catch:{ all -> 0x02d7 } return; L_0x003b: r4 = move-exception; monitor-exit(r5); Catch:{ all -> 0x003b } throw r4; L_0x003e: r0 = r22; r4 = r0.fcO; Catch:{ all -> 0x02d7 } if (r4 != 0) goto L_0x0069; L_0x0044: r0 = r22; r4 = r0.fzA; Catch:{ all -> 0x02d7 } if (r4 == 0) goto L_0x0069; L_0x004a: r0 = r22; r4 = r0.fzF; Catch:{ all -> 0x02d7 } r4 = r4.isEmpty(); Catch:{ all -> 0x02d7 } if (r4 != 0) goto L_0x0069; L_0x0054: r0 = r22; r4 = r0.fzF; Catch:{ all -> 0x02d7 } r5 = 0; r4 = r4.remove(r5); Catch:{ all -> 0x02d7 } r4 = (java.lang.Runnable) r4; Catch:{ all -> 0x02d7 } r5 = r4; L_0x0060: monitor-exit(r17); Catch:{ all -> 0x02d7 } if (r5 == 0) goto L_0x0432; L_0x0063: r5.run(); r4 = 0; r5 = r4; goto L_0x002e; L_0x0069: r4 = 0; r0 = r22; r0 = r0.fcO; Catch:{ all -> 0x02d7 } r16 = r0; r0 = r22; r0 = r0.fzs; Catch:{ all -> 0x02d7 } r18 = r0; r0 = r16; r1 = r18; if (r0 == r1) goto L_0x079d; L_0x007c: r0 = r22; r0 = r0.fzs; Catch:{ all -> 0x02d7 } r16 = r0; r0 = r22; r4 = r0.fzs; Catch:{ all -> 0x02d7 } r0 = r22; r0.fcO = r4; Catch:{ all -> 0x02d7 } if (r16 == 0) goto L_0x02c2; L_0x008c: r0 = r22; r4 = r0.fzn; Catch:{ all -> 0x02d7 } r4 = r4.get(); Catch:{ all -> 0x02d7 } r4 = (com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView) r4; Catch:{ all -> 0x02d7 } if (r4 == 0) goto L_0x009f; L_0x0098: r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.g(r4); Catch:{ all -> 0x02d7 } r4.onPause(); Catch:{ all -> 0x02d7 } L_0x009f: r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); Catch:{ all -> 0x02d7 } r4.notifyAll(); Catch:{ all -> 0x02d7 } r4 = "MicroMsg.GLThread"; r18 = new java.lang.StringBuilder; Catch:{ all -> 0x02d7 } r19 = "mPaused is now "; r18.<init>(r19); Catch:{ all -> 0x02d7 } r0 = r22; r0 = r0.fcO; Catch:{ all -> 0x02d7 } r19 = r0; r18 = r18.append(r19); Catch:{ all -> 0x02d7 } r19 = " tid="; r18 = r18.append(r19); Catch:{ all -> 0x02d7 } r20 = r22.getId(); Catch:{ all -> 0x02d7 } r0 = r18; r1 = r20; r18 = r0.append(r1); Catch:{ all -> 0x02d7 } r18 = r18.toString(); Catch:{ all -> 0x02d7 } r0 = r18; com.tencent.mm.sdk.platformtools.x.i(r4, r0); Catch:{ all -> 0x02d7 } L_0x00d7: r0 = r22; r4 = r0.fzB; Catch:{ all -> 0x02d7 } if (r4 == 0) goto L_0x0107; L_0x00dd: r4 = "MicroMsg.GLThread"; r8 = new java.lang.StringBuilder; Catch:{ all -> 0x02d7 } r18 = "releasing EGL context because asked to tid="; r0 = r18; r8.<init>(r0); Catch:{ all -> 0x02d7 } r18 = r22.getId(); Catch:{ all -> 0x02d7 } r0 = r18; r8 = r8.append(r0); Catch:{ all -> 0x02d7 } r8 = r8.toString(); Catch:{ all -> 0x02d7 } com.tencent.mm.sdk.platformtools.x.i(r4, r8); Catch:{ all -> 0x02d7 } r22.afK(); Catch:{ all -> 0x02d7 } r22.afL(); Catch:{ all -> 0x02d7 } r4 = 0; r0 = r22; r0.fzB = r4; Catch:{ all -> 0x02d7 } r8 = 1; L_0x0107: if (r12 == 0) goto L_0x0111; L_0x0109: r22.afK(); Catch:{ all -> 0x02d7 } r22.afL(); Catch:{ all -> 0x02d7 } r4 = 0; r12 = r4; L_0x0111: if (r16 == 0) goto L_0x013c; L_0x0113: r0 = r22; r4 = r0.fzz; Catch:{ all -> 0x02d7 } if (r4 == 0) goto L_0x013c; L_0x0119: r4 = "MicroMsg.GLThread"; r18 = new java.lang.StringBuilder; Catch:{ all -> 0x02d7 } r19 = "releasing EGL surface because paused tid="; r18.<init>(r19); Catch:{ all -> 0x02d7 } r20 = r22.getId(); Catch:{ all -> 0x02d7 } r0 = r18; r1 = r20; r18 = r0.append(r1); Catch:{ all -> 0x02d7 } r18 = r18.toString(); Catch:{ all -> 0x02d7 } r0 = r18; com.tencent.mm.sdk.platformtools.x.i(r4, r0); Catch:{ all -> 0x02d7 } r22.afK(); Catch:{ all -> 0x02d7 } L_0x013c: if (r16 == 0) goto L_0x017a; L_0x013e: r0 = r22; r4 = r0.fzy; Catch:{ all -> 0x02d7 } if (r4 == 0) goto L_0x017a; L_0x0144: r0 = r22; r4 = r0.fzn; Catch:{ all -> 0x02d7 } r4 = r4.get(); Catch:{ all -> 0x02d7 } r4 = (com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView) r4; Catch:{ all -> 0x02d7 } if (r4 != 0) goto L_0x02da; L_0x0150: r4 = 0; L_0x0151: if (r4 != 0) goto L_0x017a; L_0x0153: r22.afL(); Catch:{ all -> 0x02d7 } r4 = "MicroMsg.GLThread"; r16 = new java.lang.StringBuilder; Catch:{ all -> 0x02d7 } r18 = "releasing EGL context because paused tid="; r0 = r16; r1 = r18; r0.<init>(r1); Catch:{ all -> 0x02d7 } r18 = r22.getId(); Catch:{ all -> 0x02d7 } r0 = r16; r1 = r18; r16 = r0.append(r1); Catch:{ all -> 0x02d7 } r16 = r16.toString(); Catch:{ all -> 0x02d7 } r0 = r16; com.tencent.mm.sdk.platformtools.x.i(r4, r0); Catch:{ all -> 0x02d7 } L_0x017a: r0 = r22; r4 = r0.fzv; Catch:{ all -> 0x02d7 } if (r4 != 0) goto L_0x01c4; L_0x0180: r0 = r22; r4 = r0.fzx; Catch:{ all -> 0x02d7 } if (r4 != 0) goto L_0x01c4; L_0x0186: r4 = "MicroMsg.GLThread"; r16 = new java.lang.StringBuilder; Catch:{ all -> 0x02d7 } r18 = "noticed surfaceView surface lost tid="; r0 = r16; r1 = r18; r0.<init>(r1); Catch:{ all -> 0x02d7 } r18 = r22.getId(); Catch:{ all -> 0x02d7 } r0 = r16; r1 = r18; r16 = r0.append(r1); Catch:{ all -> 0x02d7 } r16 = r16.toString(); Catch:{ all -> 0x02d7 } r0 = r16; com.tencent.mm.sdk.platformtools.x.i(r4, r0); Catch:{ all -> 0x02d7 } r0 = r22; r4 = r0.fzz; Catch:{ all -> 0x02d7 } if (r4 == 0) goto L_0x01b3; L_0x01b0: r22.afK(); Catch:{ all -> 0x02d7 } L_0x01b3: r4 = 1; r0 = r22; r0.fzx = r4; Catch:{ all -> 0x02d7 } r4 = 0; r0 = r22; r0.fzw = r4; Catch:{ all -> 0x02d7 } r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); Catch:{ all -> 0x02d7 } r4.notifyAll(); Catch:{ all -> 0x02d7 } L_0x01c4: r0 = r22; r4 = r0.fzv; Catch:{ all -> 0x02d7 } if (r4 == 0) goto L_0x0200; L_0x01ca: r0 = r22; r4 = r0.fzx; Catch:{ all -> 0x02d7 } if (r4 == 0) goto L_0x0200; L_0x01d0: r4 = "MicroMsg.GLThread"; r16 = new java.lang.StringBuilder; Catch:{ all -> 0x02d7 } r18 = "noticed surfaceView surface acquired tid="; r0 = r16; r1 = r18; r0.<init>(r1); Catch:{ all -> 0x02d7 } r18 = r22.getId(); Catch:{ all -> 0x02d7 } r0 = r16; r1 = r18; r16 = r0.append(r1); Catch:{ all -> 0x02d7 } r16 = r16.toString(); Catch:{ all -> 0x02d7 } r0 = r16; com.tencent.mm.sdk.platformtools.x.i(r4, r0); Catch:{ all -> 0x02d7 } r4 = 0; r0 = r22; r0.fzx = r4; Catch:{ all -> 0x02d7 } r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); Catch:{ all -> 0x02d7 } r4.notifyAll(); Catch:{ all -> 0x02d7 } L_0x0200: if (r9 == 0) goto L_0x0799; L_0x0202: r4 = "MicroMsg.GLThread"; r9 = new java.lang.StringBuilder; Catch:{ all -> 0x02d7 } r16 = "sending render notification tid="; r0 = r16; r9.<init>(r0); Catch:{ all -> 0x02d7 } r18 = r22.getId(); Catch:{ all -> 0x02d7 } r0 = r18; r9 = r9.append(r0); Catch:{ all -> 0x02d7 } r9 = r9.toString(); Catch:{ all -> 0x02d7 } com.tencent.mm.sdk.platformtools.x.i(r4, r9); Catch:{ all -> 0x02d7 } r4 = 0; r0 = r22; r0.fzD = r4; Catch:{ all -> 0x02d7 } r4 = 0; r9 = 1; r0 = r22; r0.fzE = r9; Catch:{ all -> 0x02d7 } r9 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); Catch:{ all -> 0x02d7 } r9.notifyAll(); Catch:{ all -> 0x02d7 } r16 = r4; L_0x0234: r4 = r22.afO(); Catch:{ all -> 0x02d7 } if (r4 == 0) goto L_0x0796; L_0x023a: r0 = r22; r4 = r0.fzy; Catch:{ all -> 0x02d7 } if (r4 != 0) goto L_0x03b8; L_0x0240: r4 = "MicroMsg.GLThread"; r9 = "not HaveEglContext"; com.tencent.mm.sdk.platformtools.x.i(r4, r9); Catch:{ all -> 0x02d7 } if (r8 == 0) goto L_0x02e0; L_0x024b: r8 = 0; r4 = r8; L_0x024d: r0 = r22; r8 = r0.fzy; Catch:{ all -> 0x02d7 } if (r8 == 0) goto L_0x0792; L_0x0253: r0 = r22; r8 = r0.fzz; Catch:{ all -> 0x02d7 } if (r8 != 0) goto L_0x0792; L_0x0259: r8 = "MicroMsg.GLThread"; r9 = "Have EglContext but no EglSurface"; com.tencent.mm.sdk.platformtools.x.i(r8, r9); Catch:{ all -> 0x02d7 } r8 = 1; r0 = r22; r0.fzz = r8; Catch:{ all -> 0x02d7 } r15 = 1; r13 = 1; r11 = 1; r8 = r11; r9 = r15; L_0x026c: r0 = r22; r11 = r0.fzz; Catch:{ all -> 0x02d7 } if (r11 == 0) goto L_0x03ef; L_0x0272: r0 = r22; r11 = r0.fzG; Catch:{ all -> 0x02d7 } if (r11 == 0) goto L_0x02a8; L_0x0278: r8 = 1; r0 = r22; r7 = r0.mWidth; Catch:{ all -> 0x02d7 } r0 = r22; r6 = r0.mHeight; Catch:{ all -> 0x02d7 } r9 = 1; r0 = r22; r0.fzD = r9; Catch:{ all -> 0x02d7 } r9 = "MicroMsg.GLThread"; r11 = new java.lang.StringBuilder; Catch:{ all -> 0x02d7 } r15 = "noticing that we want render notification tid="; r11.<init>(r15); Catch:{ all -> 0x02d7 } r18 = r22.getId(); Catch:{ all -> 0x02d7 } r0 = r18; r11 = r11.append(r0); Catch:{ all -> 0x02d7 } r11 = r11.toString(); Catch:{ all -> 0x02d7 } com.tencent.mm.sdk.platformtools.x.i(r9, r11); Catch:{ all -> 0x02d7 } r9 = 1; r11 = 0; r0 = r22; r0.fzG = r11; Catch:{ all -> 0x02d7 } L_0x02a8: r11 = r8; r15 = r9; r8 = 0; r0 = r22; r0.fzC = r8; Catch:{ all -> 0x02d7 } r8 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); Catch:{ all -> 0x02d7 } r8.notifyAll(); Catch:{ all -> 0x02d7 } r0 = r22; r8 = r0.fzD; Catch:{ all -> 0x02d7 } if (r8 == 0) goto L_0x078d; L_0x02bc: r10 = 1; r8 = r4; r9 = r16; goto L_0x0060; L_0x02c2: r0 = r22; r4 = r0.fzn; Catch:{ all -> 0x02d7 } r4 = r4.get(); Catch:{ all -> 0x02d7 } r4 = (com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView) r4; Catch:{ all -> 0x02d7 } if (r4 == 0) goto L_0x009f; L_0x02ce: r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.g(r4); Catch:{ all -> 0x02d7 } r4.onResume(); Catch:{ all -> 0x02d7 } goto L_0x009f; L_0x02d7: r4 = move-exception; monitor-exit(r17); Catch:{ all -> 0x02d7 } throw r4; L_0x02da: r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.h(r4); Catch:{ all -> 0x02d7 } goto L_0x0151; L_0x02e0: r0 = r22; r9 = r0.fzH; Catch:{ RuntimeException -> 0x0327 } r4 = "MicroMsg.GLThread"; r14 = new java.lang.StringBuilder; Catch:{ RuntimeException -> 0x0327 } r18 = "start() tid="; r0 = r18; r14.<init>(r0); Catch:{ RuntimeException -> 0x0327 } r18 = java.lang.Thread.currentThread(); Catch:{ RuntimeException -> 0x0327 } r18 = r18.getId(); Catch:{ RuntimeException -> 0x0327 } r0 = r18; r14 = r14.append(r0); Catch:{ RuntimeException -> 0x0327 } r14 = r14.toString(); Catch:{ RuntimeException -> 0x0327 } com.tencent.mm.sdk.platformtools.x.w(r4, r14); Catch:{ RuntimeException -> 0x0327 } r4 = javax.microedition.khronos.egl.EGLContext.getEGL(); Catch:{ RuntimeException -> 0x0327 } r4 = (javax.microedition.khronos.egl.EGL10) r4; Catch:{ RuntimeException -> 0x0327 } r9.fbb = r4; Catch:{ RuntimeException -> 0x0327 } r4 = r9.fbb; Catch:{ RuntimeException -> 0x0327 } r14 = javax.microedition.khronos.egl.EGL10.EGL_DEFAULT_DISPLAY; Catch:{ RuntimeException -> 0x0327 } r4 = r4.eglGetDisplay(r14); Catch:{ RuntimeException -> 0x0327 } r9.fbc = r4; Catch:{ RuntimeException -> 0x0327 } r4 = r9.fbc; Catch:{ RuntimeException -> 0x0327 } r14 = javax.microedition.khronos.egl.EGL10.EGL_NO_DISPLAY; Catch:{ RuntimeException -> 0x0327 } if (r4 != r14) goto L_0x0330; L_0x031e: r4 = new java.lang.RuntimeException; Catch:{ RuntimeException -> 0x0327 } r5 = "eglGetDisplay failed"; r4.<init>(r5); Catch:{ RuntimeException -> 0x0327 } throw r4; Catch:{ RuntimeException -> 0x0327 } L_0x0327: r4 = move-exception; r5 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); Catch:{ all -> 0x02d7 } r5.notifyAll(); Catch:{ all -> 0x02d7 } throw r4; Catch:{ all -> 0x02d7 } L_0x0330: r4 = 2; r4 = new int[r4]; Catch:{ RuntimeException -> 0x0327 } r14 = r9.fbb; Catch:{ RuntimeException -> 0x0327 } r0 = r9.fbc; Catch:{ RuntimeException -> 0x0327 } r18 = r0; r0 = r18; r4 = r14.eglInitialize(r0, r4); Catch:{ RuntimeException -> 0x0327 } if (r4 != 0) goto L_0x034a; L_0x0341: r4 = new java.lang.RuntimeException; Catch:{ RuntimeException -> 0x0327 } r5 = "eglInitialize failed"; r4.<init>(r5); Catch:{ RuntimeException -> 0x0327 } throw r4; Catch:{ RuntimeException -> 0x0327 } L_0x034a: r4 = r9.fzn; Catch:{ RuntimeException -> 0x0327 } r4 = r4.get(); Catch:{ RuntimeException -> 0x0327 } r4 = (com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView) r4; Catch:{ RuntimeException -> 0x0327 } if (r4 != 0) goto L_0x03bb; L_0x0354: r4 = 0; r9.fzo = r4; Catch:{ RuntimeException -> 0x0327 } r4 = 0; r9.fbd = r4; Catch:{ RuntimeException -> 0x0327 } L_0x035a: r4 = r9.fbd; Catch:{ RuntimeException -> 0x0327 } if (r4 == 0) goto L_0x0364; L_0x035e: r4 = r9.fbd; Catch:{ RuntimeException -> 0x0327 } r14 = javax.microedition.khronos.egl.EGL10.EGL_NO_CONTEXT; Catch:{ RuntimeException -> 0x0327 } if (r4 != r14) goto L_0x0373; L_0x0364: r4 = 0; r9.fbd = r4; Catch:{ RuntimeException -> 0x0327 } r4 = "createContext"; r14 = r9.fbb; Catch:{ RuntimeException -> 0x0327 } r14 = r14.eglGetError(); Catch:{ RuntimeException -> 0x0327 } com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.i.az(r4, r14); Catch:{ RuntimeException -> 0x0327 } L_0x0373: r4 = "MicroMsg.GLThread"; r14 = new java.lang.StringBuilder; Catch:{ RuntimeException -> 0x0327 } r18 = "createContext "; r0 = r18; r14.<init>(r0); Catch:{ RuntimeException -> 0x0327 } r0 = r9.fbd; Catch:{ RuntimeException -> 0x0327 } r18 = r0; r0 = r18; r14 = r14.append(r0); Catch:{ RuntimeException -> 0x0327 } r18 = " tid="; r0 = r18; r14 = r14.append(r0); Catch:{ RuntimeException -> 0x0327 } r18 = java.lang.Thread.currentThread(); Catch:{ RuntimeException -> 0x0327 } r18 = r18.getId(); Catch:{ RuntimeException -> 0x0327 } r0 = r18; r14 = r14.append(r0); Catch:{ RuntimeException -> 0x0327 } r14 = r14.toString(); Catch:{ RuntimeException -> 0x0327 } com.tencent.mm.sdk.platformtools.x.w(r4, r14); Catch:{ RuntimeException -> 0x0327 } r4 = 0; r9.fbe = r4; Catch:{ RuntimeException -> 0x0327 } r4 = 1; r0 = r22; r0.fzy = r4; Catch:{ all -> 0x02d7 } r14 = 1; r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); Catch:{ all -> 0x02d7 } r4.notifyAll(); Catch:{ all -> 0x02d7 } L_0x03b8: r4 = r8; goto L_0x024d; L_0x03bb: r14 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.b(r4); Catch:{ RuntimeException -> 0x0327 } r0 = r9.fbb; Catch:{ RuntimeException -> 0x0327 } r18 = r0; r0 = r9.fbc; Catch:{ RuntimeException -> 0x0327 } r19 = r0; r0 = r18; r1 = r19; r14 = r14.chooseConfig(r0, r1); Catch:{ RuntimeException -> 0x0327 } r9.fzo = r14; Catch:{ RuntimeException -> 0x0327 } r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.c(r4); Catch:{ RuntimeException -> 0x0327 } r14 = r9.fbb; Catch:{ RuntimeException -> 0x0327 } r0 = r9.fbc; Catch:{ RuntimeException -> 0x0327 } r18 = r0; r0 = r9.fzo; Catch:{ RuntimeException -> 0x0327 } r19 = r0; r20 = javax.microedition.khronos.egl.EGL10.EGL_NO_CONTEXT; Catch:{ RuntimeException -> 0x0327 } r0 = r18; r1 = r19; r2 = r20; r4 = r4.b(r14, r0, r1, r2); Catch:{ RuntimeException -> 0x0327 } r9.fbd = r4; Catch:{ RuntimeException -> 0x0327 } goto L_0x035a; L_0x03ef: r11 = "MicroMsg.GLThread"; r15 = "readyToDraw but not haveEglSurface"; com.tencent.mm.sdk.platformtools.x.e(r11, r15); Catch:{ all -> 0x02d7 } r11 = r8; r15 = r9; L_0x03fa: r8 = r22.afP(); Catch:{ all -> 0x02d7 } if (r8 == 0) goto L_0x0426; L_0x0400: r8 = "MicroMsg.GLThread"; r9 = "readyToPauseAlsoDoDraw mPaused = [%b]"; r18 = 1; r0 = r18; r0 = new java.lang.Object[r0]; Catch:{ all -> 0x02d7 } r18 = r0; r19 = 0; r0 = r22; r0 = r0.fcO; Catch:{ all -> 0x02d7 } r20 = r0; r20 = java.lang.Boolean.valueOf(r20); Catch:{ all -> 0x02d7 } r18[r19] = r20; Catch:{ all -> 0x02d7 } r0 = r18; com.tencent.mm.sdk.platformtools.x.i(r8, r9, r0); Catch:{ all -> 0x02d7 } r8 = r4; r9 = r16; goto L_0x0060; L_0x0426: r8 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); Catch:{ all -> 0x02d7 } r8.wait(); Catch:{ all -> 0x02d7 } r8 = r4; r9 = r16; goto L_0x0033; L_0x0432: if (r15 == 0) goto L_0x051d; L_0x0434: r4 = "MicroMsg.GLThread"; r16 = "egl createSurface"; r0 = r16; com.tencent.mm.sdk.platformtools.x.w(r4, r0); r0 = r22; r0 = r0.fzH; r16 = r0; r4 = "MicroMsg.GLThread"; r17 = new java.lang.StringBuilder; r18 = "createSurface() tid="; r17.<init>(r18); r18 = java.lang.Thread.currentThread(); r18 = r18.getId(); r17 = r17.append(r18); r17 = r17.toString(); r0 = r17; com.tencent.mm.sdk.platformtools.x.w(r4, r0); r0 = r16; r4 = r0.fbb; if (r4 != 0) goto L_0x0474; L_0x046b: r4 = new java.lang.RuntimeException; r5 = "egl not initialized"; r4.<init>(r5); throw r4; L_0x0474: r0 = r16; r4 = r0.fbc; if (r4 != 0) goto L_0x0483; L_0x047a: r4 = new java.lang.RuntimeException; r5 = "eglDisplay not initialized"; r4.<init>(r5); throw r4; L_0x0483: r0 = r16; r4 = r0.fzo; if (r4 != 0) goto L_0x0492; L_0x0489: r4 = new java.lang.RuntimeException; r5 = "mEglConfig not initialized"; r4.<init>(r5); throw r4; L_0x0492: r16.afJ(); r0 = r16; r4 = r0.fzn; r4 = r4.get(); r4 = (com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView) r4; if (r4 == 0) goto L_0x06e8; L_0x04a1: r17 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.d(r4); r0 = r16; r0 = r0.fbb; r18 = r0; r0 = r16; r0 = r0.fbc; r19 = r0; r0 = r16; r0 = r0.fzo; r20 = r0; r4 = r4.getHolder(); r0 = r17; r1 = r18; r2 = r19; r3 = r20; r4 = r0.createWindowSurface(r1, r2, r3, r4); r0 = r16; r0.fbe = r4; L_0x04cb: r0 = r16; r4 = r0.fbe; if (r4 == 0) goto L_0x04db; L_0x04d1: r0 = r16; r4 = r0.fbe; r17 = javax.microedition.khronos.egl.EGL10.EGL_NO_SURFACE; r0 = r17; if (r4 != r0) goto L_0x06ef; L_0x04db: r0 = r16; r4 = r0.fbb; r4 = r4.eglGetError(); r16 = 12299; // 0x300b float:1.7235E-41 double:6.0765E-320; r0 = r16; if (r4 != r0) goto L_0x04f4; L_0x04e9: r4 = "MicroMsg.GLThread"; r16 = "createWindowSurface returned EGL_BAD_NATIVE_WINDOW."; r0 = r16; com.tencent.mm.sdk.platformtools.x.e(r4, r0); L_0x04f4: r4 = 0; L_0x04f5: if (r4 == 0) goto L_0x0739; L_0x04f7: r0 = r22; r4 = r0.fzn; r4 = r4.get(); r4 = (com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView) r4; if (r4 == 0) goto L_0x050a; L_0x0503: r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.g(r4); r4.onCreateEglSurface(); L_0x050a: r15 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); monitor-enter(r15); r4 = 1; r0 = r22; r0.fzA = r4; Catch:{ all -> 0x0736 } r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); Catch:{ all -> 0x0736 } r4.notifyAll(); Catch:{ all -> 0x0736 } monitor-exit(r15); Catch:{ all -> 0x0736 } r15 = 0; L_0x051d: if (r13 == 0) goto L_0x0573; L_0x051f: r4 = "MicroMsg.GLThread"; r13 = "createGLInterface"; com.tencent.mm.sdk.platformtools.x.w(r4, r13); r0 = r22; r4 = r0.fzH; r13 = r4.fbd; r13 = r13.getGL(); r4 = r4.fzn; r4 = r4.get(); r4 = (com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView) r4; if (r4 == 0) goto L_0x0572; L_0x053c: r16 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.e(r4); if (r16 == 0) goto L_0x054a; L_0x0542: r13 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.e(r4); r13 = r13.afR(); L_0x054a: r16 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.f(r4); r16 = r16 & 3; if (r16 == 0) goto L_0x0572; L_0x0552: r16 = 0; r17 = 0; r18 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.f(r4); r18 = r18 & 1; if (r18 == 0) goto L_0x0560; L_0x055e: r16 = 1; L_0x0560: r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.f(r4); r4 = r4 & 2; if (r4 == 0) goto L_0x0789; L_0x0568: r4 = new com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView$m; r4.<init>(); L_0x056d: r0 = r16; android.opengl.GLDebugHelper.wrap(r13, r0, r4); L_0x0572: r13 = 0; L_0x0573: if (r14 == 0) goto L_0x0588; L_0x0575: r0 = r22; r4 = r0.fzn; r4 = r4.get(); r4 = (com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView) r4; if (r4 == 0) goto L_0x0588; L_0x0581: r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.i(r4); r4.ahm(); L_0x0588: if (r14 == 0) goto L_0x05b1; L_0x058a: r4 = "MicroMsg.GLThread"; r14 = "createEglContext"; com.tencent.mm.sdk.platformtools.x.w(r4, r14); r0 = r22; r4 = r0.fzn; r4 = r4.get(); r4 = (com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView) r4; if (r4 == 0) goto L_0x05b0; L_0x059f: r14 = com.tencent.mm.plugin.appbrand.game.i.fAb; r14.afZ(); r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.g(r4); r4.afS(); r4 = com.tencent.mm.plugin.appbrand.game.i.fAb; r4.aga(); L_0x05b0: r14 = 0; L_0x05b1: if (r11 == 0) goto L_0x05fa; L_0x05b3: r4 = "MicroMsg.GLThread"; r11 = new java.lang.StringBuilder; r16 = "onSurfaceChanged("; r0 = r16; r11.<init>(r0); r11 = r11.append(r7); r16 = ", "; r0 = r16; r11 = r11.append(r0); r11 = r11.append(r6); r16 = ")"; r0 = r16; r11 = r11.append(r0); r11 = r11.toString(); com.tencent.mm.sdk.platformtools.x.w(r4, r11); r0 = r22; r4 = r0.fzn; r4 = r4.get(); r4 = (com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView) r4; if (r4 == 0) goto L_0x05f9; L_0x05ed: r11 = com.tencent.mm.plugin.appbrand.game.i.fAb; r11.agb(); r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.g(r4); r4.bI(r7, r6); L_0x05f9: r11 = 0; L_0x05fa: r0 = r22; r4 = r0.fzn; r4 = r4.get(); r4 = (com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView) r4; if (r4 == 0) goto L_0x0620; L_0x0606: r16 = com.tencent.mm.plugin.appbrand.game.i.fAb; r16.age(); r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.g(r4); r16 = 0; r0 = r16; r4.cC(r0); r4 = com.tencent.mm.plugin.appbrand.game.i.fAb; r4.agc(); r4 = com.tencent.mm.plugin.appbrand.game.i.fAb; r4.agd(); L_0x0620: r0 = r22; r4 = r0.fzn; r4 = r4.get(); r4 = (com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView) r4; if (r4 == 0) goto L_0x0639; L_0x062c: r16 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.i(r4); r4 = r4.getIsSwapNow(); r0 = r16; r0.cH(r4); L_0x0639: r16 = 12288; // 0x3000 float:1.7219E-41 double:6.071E-320; r17 = 1; r0 = r22; r4 = r0.fzn; r4 = r4.get(); r4 = (com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView) r4; if (r4 == 0) goto L_0x064d; L_0x0649: r17 = r4.getIsSwapNow(); L_0x064d: if (r17 == 0) goto L_0x06a5; L_0x064f: r0 = r22; r0 = r0.fzH; r17 = r0; r16 = 12288; // 0x3000 float:1.7219E-41 double:6.071E-320; r0 = r17; r0 = r0.fbc; r18 = r0; if (r18 == 0) goto L_0x06a5; L_0x065f: r0 = r17; r0 = r0.fbc; r18 = r0; r19 = javax.microedition.khronos.egl.EGL10.EGL_NO_DISPLAY; r0 = r18; r1 = r19; if (r0 == r1) goto L_0x06a5; L_0x066d: r0 = r17; r0 = r0.fbe; r18 = r0; if (r18 == 0) goto L_0x06a5; L_0x0675: r0 = r17; r0 = r0.fbe; r18 = r0; r19 = javax.microedition.khronos.egl.EGL10.EGL_NO_SURFACE; r0 = r18; r1 = r19; if (r0 == r1) goto L_0x06a5; L_0x0683: r0 = r17; r0 = r0.fbb; r18 = r0; r0 = r17; r0 = r0.fbc; r19 = r0; r0 = r17; r0 = r0.fbe; r20 = r0; r18 = r18.eglSwapBuffers(r19, r20); if (r18 != 0) goto L_0x06a5; L_0x069b: r0 = r17; r0 = r0.fbb; r16 = r0; r16 = r16.eglGetError(); L_0x06a5: if (r4 == 0) goto L_0x06ae; L_0x06a7: r17 = 1; r0 = r17; r4.setSwapNow(r0); L_0x06ae: switch(r16) { case 12288: goto L_0x06d5; case 12302: goto L_0x0760; default: goto L_0x06b1; }; L_0x06b1: r17 = "GLThread"; r18 = "eglSwapBuffers"; r0 = r17; r1 = r18; r2 = r16; com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.i.n(r0, r1, r2); r16 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); monitor-enter(r16); r17 = 1; r0 = r17; r1 = r22; r1.fzw = r0; Catch:{ all -> 0x0783 } r17 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); Catch:{ all -> 0x0783 } r17.notifyAll(); Catch:{ all -> 0x0783 } monitor-exit(r16); Catch:{ all -> 0x0783 } L_0x06d5: if (r4 == 0) goto L_0x06de; L_0x06d7: r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.i(r4); r4.ahm(); L_0x06de: if (r10 == 0) goto L_0x0786; L_0x06e0: r4 = 1; r10 = 0; L_0x06e2: r22.afN(); r9 = r4; goto L_0x002e; L_0x06e8: r4 = 0; r0 = r16; r0.fbe = r4; goto L_0x04cb; L_0x06ef: r0 = r16; r4 = r0.fbb; r0 = r16; r0 = r0.fbc; r17 = r0; r0 = r16; r0 = r0.fbe; r18 = r0; r0 = r16; r0 = r0.fbe; r19 = r0; r0 = r16; r0 = r0.fbd; r20 = r0; r0 = r17; r1 = r18; r2 = r19; r3 = r20; r4 = r4.eglMakeCurrent(r0, r1, r2, r3); if (r4 != 0) goto L_0x0733; L_0x0719: r4 = "EGLHelper"; r17 = "eglMakeCurrent"; r0 = r16; r0 = r0.fbb; r16 = r0; r16 = r16.eglGetError(); r0 = r17; r1 = r16; com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.i.n(r4, r0, r1); r4 = 0; goto L_0x04f5; L_0x0733: r4 = 1; goto L_0x04f5; L_0x0736: r4 = move-exception; monitor-exit(r15); Catch:{ all -> 0x0736 } throw r4; L_0x0739: r4 = "MicroMsg.GLThread"; r16 = "egl createSurface error"; r0 = r16; com.tencent.mm.sdk.platformtools.x.e(r4, r0); r16 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); monitor-enter(r16); r4 = 1; r0 = r22; r0.fzA = r4; Catch:{ all -> 0x075d } r4 = 1; r0 = r22; r0.fzw = r4; Catch:{ all -> 0x075d } r4 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); Catch:{ all -> 0x075d } r4.notifyAll(); Catch:{ all -> 0x075d } monitor-exit(r16); Catch:{ all -> 0x075d } goto L_0x002e; L_0x075d: r4 = move-exception; monitor-exit(r16); Catch:{ all -> 0x075d } throw r4; L_0x0760: r12 = "MicroMsg.GLThread"; r16 = new java.lang.StringBuilder; r17 = "egl context lost tid="; r16.<init>(r17); r18 = r22.getId(); r0 = r16; r1 = r18; r16 = r0.append(r1); r16 = r16.toString(); r0 = r16; com.tencent.mm.sdk.platformtools.x.i(r12, r0); r12 = 1; goto L_0x06d5; L_0x0783: r4 = move-exception; monitor-exit(r16); Catch:{ all -> 0x0783 } throw r4; L_0x0786: r4 = r9; goto L_0x06e2; L_0x0789: r4 = r17; goto L_0x056d; L_0x078d: r8 = r4; r9 = r16; goto L_0x0060; L_0x0792: r8 = r11; r9 = r15; goto L_0x026c; L_0x0796: r4 = r8; goto L_0x03fa; L_0x0799: r16 = r9; goto L_0x0234; L_0x079d: r16 = r4; goto L_0x00d7; */ throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView$j.afM():void"); } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ private void afN() { /* r8 = this; r1 = 0; r7 = 0; r0 = r1; L_0x0003: r3 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); monitor-enter(r3); r2 = r8.afP(); Catch:{ all -> 0x0022 } if (r2 != 0) goto L_0x0010; L_0x000e: monitor-exit(r3); Catch:{ all -> 0x0022 } L_0x000f: return; L_0x0010: r2 = r8.fzt; Catch:{ all -> 0x0022 } if (r2 == 0) goto L_0x0025; L_0x0014: r0 = 0; r8.fzt = r0; Catch:{ all -> 0x0022 } r0 = "MicroMsg.GLThread"; r1 = "Request leave PAUSE_ALSO_DO_DRAW"; com.tencent.mm.sdk.platformtools.x.i(r0, r1); Catch:{ all -> 0x0022 } monitor-exit(r3); Catch:{ all -> 0x0022 } goto L_0x000f; L_0x0022: r0 = move-exception; monitor-exit(r3); Catch:{ all -> 0x0022 } throw r0; L_0x0025: r2 = r8.fzF; Catch:{ all -> 0x0022 } r2 = r2.isEmpty(); Catch:{ all -> 0x0022 } if (r2 != 0) goto L_0x007b; L_0x002d: r0 = r8.fzF; Catch:{ all -> 0x0022 } r2 = 0; r0 = r0.remove(r2); Catch:{ all -> 0x0022 } r0 = (java.lang.Runnable) r0; Catch:{ all -> 0x0022 } r2 = r0; L_0x0037: monitor-exit(r3); Catch:{ all -> 0x0022 } if (r2 == 0) goto L_0x003f; L_0x003a: r2.run(); r0 = r1; goto L_0x0003; L_0x003f: r0 = r8.fzn; r0 = r0.get(); r0 = (com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView) r0; if (r0 == 0) goto L_0x006e; L_0x0049: r3 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.g(r0); Catch:{ Exception -> 0x0061 } r4 = 1; r3.cC(r4); Catch:{ Exception -> 0x0061 } L_0x0051: r3 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.i(r0); r3.cH(r7); r0 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.i(r0); r0.ahm(); r0 = r2; goto L_0x0003; L_0x0061: r3 = move-exception; r4 = "MicroMsg.GLThread"; r5 = "readyToPauseAlsoDoDraw while() "; r6 = new java.lang.Object[r7]; com.tencent.mm.sdk.platformtools.x.printErrStackTrace(r4, r3, r5, r6); goto L_0x0051; L_0x006e: r1 = com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView.afI(); monitor-enter(r1); r0 = 1; r8.fzp = r0; Catch:{ all -> 0x0078 } monitor-exit(r1); Catch:{ all -> 0x0078 } goto L_0x000f; L_0x0078: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x0078 } throw r0; L_0x007b: r2 = r0; goto L_0x0037; */ throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.plugin.appbrand.game.GameGLSurfaceView$j.afN():void"); } final boolean afO() { return !this.fcO && this.fzv && !this.fzw && this.mWidth > 0 && this.mHeight > 0 && (this.fzC || this.mRenderMode == 1); } private boolean afP() { return this.fcO && this.fzu && this.mWidth > 0 && this.mHeight > 0 && (!this.fzC || this.mRenderMode == 1); } public final void setRenderMode(int i) { if (i < 0 || i > 1) { throw new IllegalArgumentException("renderMode"); } synchronized (GameGLSurfaceView.afI()) { this.mRenderMode = i; GameGLSurfaceView.afI().notifyAll(); } } public final int getRenderMode() { int i; synchronized (GameGLSurfaceView.afI()) { i = this.mRenderMode; } return i; } public final void afQ() { synchronized (GameGLSurfaceView.afI()) { x.i("MicroMsg.GLThread", "requestExitAndWaitForDestory tid=" + getId()); this.fzp = true; this.fzr = true; this.fzt = true; GameGLSurfaceView.afI().notifyAll(); while (!this.fzq) { try { GameGLSurfaceView.afI().wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates; import com.sun.squawk.util.MathUtils; //import java.text.DecimalFormat; /** * * @author Rex */ public class AutoBalance { private RobotOut rOut; private RobotIn rIn; private DSIn dsIn; private Drive myDrive; private double xDeg1, yDeg1, zDeg1; private double xVal, yVal, zVal; public double xOffSet, yOffSet, zOffSet; private double myPval, myIval, myDval; public int smplNum, smplTot, smplTotLast; private int itr1, itr2, itr3; private boolean smplRdy; private double[] xVals; private double[] yVals; private double[] zVals; private double factor = 1e5; private double tltDeg, rotDeg; private double xDeg, yDeg, zDeg; private boolean modValsLast; private boolean prnInitVals; private boolean newInitVals; private double myValue; private double speedMax; private double angleMax; private int driveCnt; private double inCmd; private double kP; private double revAngle; private boolean revActive; private int drCntMax; private double range = 1.0; // DecimalFormat dec8 = new DecimalFormat("0.00000000"); /** * Constructor */ public AutoBalance (RobotIn rIn, int smplNum) { // Map argument references to local names this.rIn = rIn; this.smplNum = smplNum; // Force at least two samples if (this.smplNum <= 1) {this.smplNum = 2;} // Create the averaging arrays xVals = new double[smplNum]; yVals = new double[smplNum]; zVals = new double[smplNum]; // Initialize all values smplRdy = false; itr1 = 0; itr2 = 0; itr3 = 0; smplTot = 0; for (itr1 = 0; itr1 < smplNum; itr1++) { xVals[itr1] = 0; zVals[itr1] = 0; yVals[itr1] = 0; } speedMax = 0.5; angleMax = 15.0; driveCnt = 0; inCmd = 0.0; kP = 1.0; revAngle = 0; revActive = false; drCntMax = 20; System.out.println("AutoBalance: Object created with " + smplNum + " samples!"); } /** * Print out the x, y, and z values */ public void prnVals() { if (MathUtils.round(xDeg * factor) - (MathUtils.round(xDeg * (factor - 1)) * 10) == 0) { xDeg1 = (MathUtils.round(xDeg * factor)+1)/factor; } else { xDeg1 = (MathUtils.round(xDeg * factor))/factor; } if (MathUtils.round(yDeg * factor) - (MathUtils.round(yDeg * (factor - 1)) * 10) == 0) { yDeg1 = (MathUtils.round(yDeg * factor)+1)/factor; } else { yDeg1 = (MathUtils.round(yDeg * factor))/factor; } if (MathUtils.round(zDeg * factor) - (MathUtils.round(zDeg * (factor - 1)) * 10) == 0) { zDeg1 = (MathUtils.round(zDeg * factor)+1)/factor; } else { zDeg1 = (MathUtils.round(zDeg * factor))/factor; } if (prnInitVals == false) { System.out.println("xOffSet = " + xOffSet + ", yOffSet = " + yOffSet + ", zOffSet = " + zOffSet); prnInitVals = true; } System.out.println("xDeg = " + xDeg1 + ", yDeg = " + yDeg1 + ", zDeg = " + zDeg1); // System.out.println("tltDeg = " + tltDeg + ", rotDeg = " + rotDeg); } /** * read the current value and generate a total of all readings. * Since we are dividing later, we don't need to divide by the number * of samples taken to get an average. * @return - True when the number of samples needed to have a valid average * have been captured. */ public boolean getVals() { // System.out.println("itr2 = " + itr2); xVals[itr2] = rIn.getAccelX(); yVals[itr2] = rIn.getAccelY(); zVals[itr2] = rIn.getAccelZ(); // Select which location in array to store data if (itr2 < smplNum - 1) {itr2++;} else {itr2 = 0;} // Detect when the array is full if (smplTot < smplNum) {smplTot++;} // Perform average on valid data in array xVal = 0; yVal = 0; zVal = 0; for (itr3 = 0; itr3 < smplTot; itr3++) { xVal = xVal + xVals[itr3]; yVal = yVal + yVals[itr3]; zVal = zVal + zVals[itr3]; } xVal = xVal / smplTot; yVal = yVal / smplTot; zVal = zVal / smplTot; System.out.println("xVal" + xVal); System.out.println("yVal" + yVal); System.out.println("zVal" + zVal); if (smplTotLast == smplTot && smplRdy == false) { smplRdy = true; xOffSet = xVal; yOffSet = yVal; zOffSet = zVal; System.out.println("xOffSet = " + xOffSet + ", yOffSet = " + yOffSet + ", zOffSet = " + zOffSet); } smplTotLast = smplTot; if (smplRdy == true) { xVal = xVal + xOffSet; yVal = yVal + yOffSet; zVal = zVal + 1 - zOffSet; } // Convert to degree values xDeg = Math.toDegrees(MathUtils.atan(xVal / (Math.sqrt((yVal * yVal) + (zVal * zVal))))); yDeg = Math.toDegrees(MathUtils.atan(yVal / (Math.sqrt((xVal * xVal) + (zVal * zVal))))); zDeg = Math.toDegrees(MathUtils.atan(zVal / (Math.sqrt((xVal * xVal) + (yVal * yVal))))); tltDeg = Math.toDegrees(MathUtils.acos(zVal / (Math.sqrt((xVal * xVal) + (yVal * yVal) + (zVal * zVal))))); rotDeg = Math.toDegrees(MathUtils.atan(xVal / yVal)); return smplRdy; } /** * This drives the base using the values read by the Accelerometer * and feeds into a PID controller. * Only the P is implemented now. */ public double getTiltCmdVal() { if (revActive == false) { driveCnt = 0; inCmd = 0.0; revAngle = 2.0; } if (Math.abs(yDeg) < revAngle || revActive == true) { revActive = true; if (driveCnt < drCntMax) { driveCnt++; inCmd = -0.2; } else { inCmd = 0.0; } } myValue = ((yDeg / angleMax) - inCmd) * kP; if (myValue > speedMax ) { myValue = speedMax ; } if (myValue < (-speedMax)) { myValue = -speedMax; } return myValue; } public boolean areWeBalanced() { if((yDeg1 > -range) && (yDeg1 < range)) { return true; } else { return false; } } }
package Task05; import java.util.Scanner; public class Task05 { public static void main(String args[]) { Scanner keyboard = new Scanner(System.in); System.out.print("Type length of rectangle: "); int length = keyboard.nextInt(); System.out.print("Type height of rectangle: "); int height = keyboard.nextInt(); int perimeter, area; perimeter = 2 * (length + height); area = length * height; System.out.println("Perimeter = 2 * (" + length + " + " + height + ") = " + perimeter); System.out.println("Area = " + length + " * " + height + " = " + area); keyboard.close(); } }
package com.tencent.mm.plugin.appbrand.ui.autofill; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.protocal.c.bnm; import com.tencent.mm.protocal.c.ei; class a$7 implements OnClickListener { final /* synthetic */ a gxq; final /* synthetic */ bnm gxr; a$7(a aVar, bnm bnm) { this.gxq = aVar; this.gxr = bnm; } public final void onClick(View view) { if (a.a(this.gxq) != null) { a.a(this.gxq).vI(((ei) this.gxr.slD.get(1)).url); } } }
package chapter10.Exercise10_05; import java.util.Scanner; public class DisplayPrimeFactors { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter number "); int number = input.nextInt(); StackOfIntegers st = new StackOfIntegers(); factors(number, st); for (int i = st.getSize() - 1; 0 <= i; i--) { System.out.print(st.peek() + (i!=0?", ":" ")); st.pop(); } } public static boolean isPrime(int number) { if (number < 2) { return false; } else { for (int i = 2; i < number; i++) { if (number % i == 0) { return false; } } } return true; } public static void factors(int number, StackOfIntegers st) { // int size = 0; // int length = 10; // int[] factors = new int[length]; int factor = 2; while (number >= factor) { /* * if (number % factor == 0) { if (size >= factors.length) { int[] temp = new * int[size * 2]; System.arraycopy(factors, 0, temp, 0, factors.length); * factors=temp; } factors[size++] = factor; */ if (number % factor == 0) { st.push(factor); number /= factor; continue; } for (int i = factor + 1; i <= number; i++) { if (isPrime(i)) { factor = i; break; } } } } // return factors; }
/** * Coppyright (C) 2020 Luvina * TblUserDao.java, Nov 17, 2020, BuiTienDung */ package Manageruser.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import Manageruser.dao.impl.TblUserDaoImpl; import Manageruser.entities.TblUserEntities; import Manageruser.entities.UserInforEntities; /** * @author Bùi Tiến Dũng * */ public interface TblUserDao { public TblUserEntities getUserByUserName(String userName) throws SQLException, ClassNotFoundException; public int getTotalUser(int groupID,String fullName ); public List<UserInforEntities> getListUsers(int ofset,int limit,int groupId,String fullName,String sortType,String sortByFullName,String sortByCodeLevel,String sortByEndDate); public boolean getColumn(String column, String table); }
package com.board.action; public class BoardBean { private String dng_id; private int dng_board_id; private String dng_board_writer; private String dng_board_content; private String dng_board_pwd; private String dng_board_likecount; private String dng_board_regdate; public String getDng_id() { return dng_id; } public void setDng_id(String string) { this.dng_id = string; } public int getDng_board_id() { return dng_board_id; } public void setDng_board_id(int dng_board_id) { this.dng_board_id = dng_board_id; } public String getDng_board_writer() { return dng_board_writer; } public void setDng_board_writer(String dng_board_writer) { this.dng_board_writer = dng_board_writer; } public String getDng_board_content() { return dng_board_content; } public void setDng_board_content(String dng_board_content) { this.dng_board_content = dng_board_content; } public String getDng_board_pwd() { return dng_board_pwd; } public void setDng_board_pwd(String dng_board_pwd) { this.dng_board_pwd = dng_board_pwd; } public String getDng_board_likecount() { return dng_board_likecount; } public void setDng_board_likecount(String dng_board_likecount) { this.dng_board_likecount = dng_board_likecount; } public String getDng_board_regdate() { return dng_board_regdate; } public void setDng_board_regdate(String dng_board_regdate) { this.dng_board_regdate = dng_board_regdate; } }
package com.example.senior.fragment; import java.util.ArrayList; import com.example.senior.R; import com.example.senior.ScheduleActivity; import com.example.senior.adapter.CalendarGridAdapter; import com.example.senior.adapter.ScheduleListAdapter; import com.example.senior.bean.CalendarTransfer; import com.example.senior.bean.ScheduleArrange; import com.example.senior.calendar.Constant; import com.example.senior.calendar.SpecialCalendar; import com.example.senior.database.DbHelper; import com.example.senior.database.ScheduleArrangeHelper; import com.example.senior.util.DateUtil; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; @SuppressLint(value={"SimpleDateFormat", "DefaultLocale"}) public class ScheduleFragment extends Fragment { private static final String TAG = "ScheduleFragment"; protected View mView; // 声明一个视图对象 protected Context mContext; // 声明一个上下文对象 private int mSelectedWeek, mNowWeek; // 当前选择的周数,以及今天所处的周数 private ListView lv_shedule; // 声明一个列表视图对象 private int mYear, mMonth, mDay; // 当前选择周数的星期一对应的年、月、日 private int first_pos = 0; // 当前选择周数的星期一在该月月历中的位置 private String thisDate; // 当前选择周数的星期一的具体日期 private ArrayList<CalendarTransfer> tranArray = new ArrayList<CalendarTransfer>(); private ScheduleArrangeHelper mArrangeHelper; // 声明一个日程安排的数据库帮助器 // 获取该碎片的一个实例 public static ScheduleFragment newInstance(int week) { ScheduleFragment fragment = new ScheduleFragment(); // 创建该碎片的一个实例 Bundle bundle = new Bundle(); // 创建一个新包裹 bundle.putInt("week", week); // 往包裹存入周数 fragment.setArguments(bundle); // 把包裹塞给碎片 return fragment; // 返回碎片实例 } // 创建碎片视图 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mContext = getActivity(); // 获取活动页面的上下文 if (getArguments() != null) { // 如果碎片携带有包裹,则打开包裹获取参数信息 mSelectedWeek = getArguments().getInt("week", 1); } // 获取今天所处的周数 mNowWeek = SpecialCalendar.getTodayWeek(); initDate(mSelectedWeek - mNowWeek); Log.d(TAG, "thisDate=" + thisDate + ",fisrt_pos=" + first_pos); Log.d(TAG, "mYear=" + mYear + ",mMonth=" + mMonth + ",mDay=" + mDay); // 根据年月日计算当周位于哪个日历网格适配器 CalendarGridAdapter calV = new CalendarGridAdapter(mContext, mYear, mMonth, mDay); for (int i = first_pos; i < first_pos + 7; i++) { // 从月历中取出当周的七天 CalendarTransfer trans = calV.getCalendarList(i); Log.d(TAG, "trans.solar_month=" + trans.solar_month + ",trans.solar_day=" + trans.solar_day + ",trans.lunar_month=" + trans.lunar_month + ",trans.lunar_day=" + trans.lunar_day); tranArray.add(trans); // 添加到日历转换队列中 } // 根据布局文件fragment_schedule.xml生成视图对象 mView = inflater.inflate(R.layout.fragment_schedule, container, false); // 从布局视图中获取名叫lv_shedule的列表视图 lv_shedule = mView.findViewById(R.id.lv_shedule); return mView; // 返回该碎片的视图对象 } // 初始化当周的星期一对应的年、月、日 private void initDate(int diff_weeks) { String nowDate = DateUtil.getNowDate(); thisDate = DateUtil.getAddDate(nowDate, diff_weeks * 7); int thisDay = Integer.valueOf(thisDate.substring(6, 8)); int weekIndex = DateUtil.getWeekIndex(thisDate); int week_count = (int) Math.ceil((thisDay - weekIndex + 0.5) / 7.0); if ((thisDay - weekIndex) % 7 > 0) { week_count++; // 需要计算当天所在周是当月的第几周 } if (thisDay - weekIndex < 0) { week_count++; } first_pos = week_count * 7; mYear = Integer.parseInt(thisDate.substring(0, 4)); mMonth = Integer.parseInt(thisDate.substring(4, 6)); mDay = Integer.parseInt(thisDate.substring(6, 8)); } // 检查当周的七天是否存在特殊节日 private void checkFestival() { int i = 0; for (; i < tranArray.size(); i++) { CalendarTransfer trans = tranArray.get(i); int j = 0; for (; j < Constant.festivalArray.length; j++) { if (trans.day_name.contains(Constant.festivalArray[j])) { // 找到了特殊节日,则发送该节日图片广播 sendFestival(Constant.festivalResArray[j]); break; } } if (j < Constant.festivalArray.length) { break; } } // 未找到特殊节日,则发送日常图片的广播 if (i >= tranArray.size()) { sendFestival(R.drawable.normal_day); } } // 把图片编号通过广播发出去 private void sendFestival(int resid) { // 创建一个广播事件的意图 Intent intent = new Intent(ScheduleActivity.ACTION_SHOW_FESTIVAL); intent.putExtra(ScheduleActivity.EXTRA_FESTIVAL_RES, resid); // 通过本地的广播管理器来发送广播 LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent); } @Override public void onStart() { super.onStart(); // 创建一个周数变更的广播接收器 scrollControlReceiver = new ScrollControlReceiver(); // 注册广播接收器,注册之后才能正常接收广播 LocalBroadcastManager.getInstance(mContext).registerReceiver(scrollControlReceiver, new IntentFilter(ScheduleActivity.ACTION_FRAGMENT_SELECTED)); // 获得数据库帮助器的实例 mArrangeHelper = new ScheduleArrangeHelper(mContext, DbHelper.db_name, null, 1); CalendarTransfer begin_trans = tranArray.get(0); String begin_day = String.format("%s%02d%02d", begin_trans.solar_year, begin_trans.solar_month, begin_trans.solar_day); CalendarTransfer end_trans = tranArray.get(tranArray.size() - 1); String end_day = String.format("%s%02d%02d", end_trans.solar_year, end_trans.solar_month, end_trans.solar_day); // 根据开始日期和结束日期,到数据库中查询这几天的日程安排信息 ArrayList<ScheduleArrange> arrangeList = (ArrayList<ScheduleArrange>) mArrangeHelper.queryInfoByDayRange(begin_day, end_day); // 构建一个当周日程的列表适配器 ScheduleListAdapter listAdapter = new ScheduleListAdapter(mContext, tranArray, arrangeList); // 给lv_shedule设置日程列表适配器 lv_shedule.setAdapter(listAdapter); // 给lv_shedule设置列表项点击监听器 lv_shedule.setOnItemClickListener(listAdapter); } @Override public void onStop() { super.onStop(); // 注销广播接收器,注销之后就不再接收广播 LocalBroadcastManager.getInstance(mContext).unregisterReceiver(scrollControlReceiver); mArrangeHelper.close(); // 关闭数据库连接 } // 声明一个周数变更的广播接收器 private ScrollControlReceiver scrollControlReceiver; // 定义一个广播接收器,用于处理周数变更事件 private class ScrollControlReceiver extends BroadcastReceiver { // 一旦接收到周数变更的广播,马上触发接收器的onReceive方法 public void onReceive(Context context, Intent intent) { if (intent != null) { // 从广播消息中取出最新的周数 int selectedWeek = intent.getIntExtra(ScheduleActivity.EXTRA_SELECTED_WEEK, 1); Log.d(TAG, "onReceive selectedWeek=" + selectedWeek + ", mSelectedWeek=" + mSelectedWeek); // 如果碎片对应的周数正好等于广播的周数,则检查当周是否存在节日 if (mSelectedWeek == selectedWeek) { checkFestival(); } } } } }
package renderer; import java.awt.Color; import java.awt.Graphics; import java.util.ArrayList; import java.util.List; import renderer.sub.FormPolyElement; import renderer.sub.FormQuadElement; import renderer.sub.FormRoundElement; public class FormRenderer implements Renderable { private static List<Renderable> toRender = new ArrayList<>(); public static void oval(int x, int y, int width, int height, Color color, boolean filled) { toRender.add(new FormRoundElement(x, y, width, height, color, filled)); } public static void oval(int x, int y, int radius, Color color, boolean filled) { toRender.add(new FormRoundElement(x, y, radius * 2, radius * 2, color, filled)); } public static void filledOval(int x, int y, int width, int height, Color color) { toRender.add(new FormRoundElement(x, y, width, height, color, true)); } public static void filledOval(int x, int y, int radius, Color color) { toRender.add(new FormRoundElement(x, y, radius * 2, radius * 2, color, true)); } public static void drawOval(int x, int y, int width, int height, Color color) { toRender.add(new FormRoundElement(x, y, width, height, color)); } public static void drawOval(int x, int y, int radius, Color color) { toRender.add(new FormRoundElement(x, y, radius * 2, radius * 2, color)); } public static void drawRect(int x, int y, int width, int height, Color color) { toRender.add(new FormQuadElement(x, y, width, height, color)); } public static void fillRect(int x, int y, int width, int height, Color color) { toRender.add(new FormQuadElement(x, y, width, height, color, true)); } public static void drawPolygon(int[] xPoints, int[] yPoints, Color color) { toRender.add(new FormPolyElement(xPoints, yPoints, color, false)); } public static void fillPolygon(int[] xPoints, int[] yPoints, Color color) { toRender.add(new FormPolyElement(xPoints, yPoints, color, true)); } @Override public void render(Graphics g) { for (Renderable f : toRender) { f.render(g); } toRender.clear(); } }