blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
โŒ€
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
018226dcbca4dbfbd7b6cabe4cadac26d78746d2
6ffc8b7027b5a18d3d367fc6a518c883a3da3d85
/src/weka/classifiers/mmall/Ensemble/logDistributionComputation/W/DBL3LogDistributionComputerW.java
4897098556346b39b8995206c4f00288c08b9228
[]
no_license
icesky0125/DecisionTreeSmoothing
8aa20b96725a669d71ca9483a87dd58ba92e4e77
fdc2c71e31b0dccdf083bfbb5c07040aeb5b2a7b
refs/heads/master
2021-07-16T20:24:12.448519
2020-05-19T05:41:13
2020-05-19T05:41:13
158,150,516
0
0
null
null
null
null
UTF-8
Java
false
false
1,827
java
package weka.classifiers.mmall.Ensemble.logDistributionComputation.W; import weka.classifiers.mmall.DataStructure.DBL.DBLParameters; import weka.classifiers.mmall.Ensemble.logDistributionComputation.LogDistributionComputerDBL; import weka.core.Instance; public class DBL3LogDistributionComputerW extends LogDistributionComputerDBL { public static LogDistributionComputerDBL singleton = null; protected DBL3LogDistributionComputerW() {} public static LogDistributionComputerDBL getComputer() { if(singleton==null){ singleton = new DBL3LogDistributionComputerW(); } return singleton; } @Override public void compute(double[] probs, DBLParameters params,Instance inst) { //double w = (double) params.getNAttributes()/3.0 * 1.0/SUtils.NC3(params.getNAttributes()); double w = 1; for (int c = 0; c < probs.length; c++) { probs[c] = params.getProbAtFullIndex(c) * params.getParameterAtFullIndex(c); double probsClass = 0; for (int att1 = 0; att1 < params.getNAttributes(); att1++) { int att1val = (int) inst.value(att1); long index = params.getAttributeIndex(att1, att1val, c); probs[c] += params.getProbAtFullIndex(index) * params.getParameterAtFullIndex(index); for (int att2 = 0; att2 < att1; att2++) { int att2val = (int) inst.value(att2); index = params.getAttributeIndex(att1, att1val, att2, att2val, c); probsClass += (params.getProbAtFullIndex(index) * params.getParameterAtFullIndex(index)); for (int att3 = 0; att3 < att2; att3++) { int att3val = (int) inst.value(att3); index = params.getAttributeIndex(att1, att1val, att2, att2val, att3, att3val, c); probsClass += (params.getProbAtFullIndex(index) * params.getParameterAtFullIndex(index)); } } } probs[c] += (w * probsClass); } } }
2dfa61a9d4b229fc410422f4c457bf5c1b2fb6c5
3d643e50e304d3ffd3f697905e441556be377cfc
/android/versioned-abis/expoview-abi36_0_0/src/main/java/abi36_0_0/org/unimodules/interfaces/permissions/PermissionsStatus.java
5fc55b168efb1a0d3ef2910d5c844e55a2d8eb9b
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
Qdigital/expo
326c5c1c0167295c173f2388f078a2f1e73835c9
8865a523d754b2332ffb512096da4998c18c9822
refs/heads/master
2023-07-07T18:37:39.814195
2020-02-18T23:28:20
2020-02-18T23:28:20
241,549,344
1
0
MIT
2023-07-06T14:55:15
2020-02-19T06:28:39
null
UTF-8
Java
false
false
314
java
package abi36_0_0.org.unimodules.interfaces.permissions; public enum PermissionsStatus { GRANTED("granted"), UNDETERMINED("undetermined"), DENIED("denied"); private String status; PermissionsStatus(String status) { this.status = status; } public String getStatus() { return status; } }
eb693f23ea68bfbaa6a38a7d6fb663448897151f
075cf1b380d58795e6d27939e6bc7cc8bf9b6946
/src/main/java/org/achtern/AchternEngine/core/scenegraph/entity/debug/AxisDebugger.java
c5680ac1d4cc635bf7679e4596dd09333eeb894b
[ "MIT" ]
permissive
achtern/AchternEngine
f743af52ca8506eaa474000c444062b4d04eeddf
75514c83cdb70b40634c3904ca088f42fcf56906
refs/heads/master
2021-01-13T02:15:22.913991
2015-10-04T15:50:32
2015-10-04T15:50:32
23,397,468
0
0
null
2015-07-27T18:37:57
2014-08-27T16:42:13
Java
UTF-8
Java
false
false
2,944
java
/* * The MIT License (MIT) * * Copyright (c) 2014 Christian Gรคrtner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.achtern.AchternEngine.core.scenegraph.entity.debug; import org.achtern.AchternEngine.core.Transform; import org.achtern.AchternEngine.core.rendering.Color; import org.achtern.AchternEngine.core.rendering.Material; import org.achtern.AchternEngine.core.rendering.generator.ImageGenerator; import org.achtern.AchternEngine.core.rendering.mesh.Arrow; import org.achtern.AchternEngine.core.rendering.mesh.Mesh; import org.achtern.AchternEngine.core.rendering.texture.Texture; import org.achtern.AchternEngine.core.scenegraph.Node; import org.achtern.AchternEngine.core.scenegraph.entity.Figure; public class AxisDebugger extends Node { /** * Create a new AxisDebugger. * * @param name The name of the node/axisdebugger */ public AxisDebugger(String name) { super(name); pushFigure(new Arrow(), Color.RED, "X-Axis"); pushFigure(new Arrow(), Color.GREEN, "Y-Axis"); pushFigure(new Arrow(), Color.BLUE, "Z-Axis"); } /** * Creates an AxisDebugger. */ public AxisDebugger() { this("AxisDebugger"); } private void pushFigure(Mesh mesh, Color color, String name) { Figure f = new Figure("Axis", mesh); Material m = new Material(); m.addTexture("diffuse", new Texture(ImageGenerator.bytesFromColor(color))); f.setMaterial(m); Node n = new Node("AxisDebugger/" + name); n.add(f); add(n); // Rotate, so they are laying on the corresponding axis if (name.equals("Z-Axis")) { n.getTransform().rotate(Transform.Z_AXIS, -90); } // Arrow Mesh is oriented on Y already. else if (name.equals("X-Axis")) { n.getTransform().rotate(Transform.X_AXIS, 90); } } }
d89e4e410284ce7881a7e5d0bdc2f98ca446a7e5
f0d301dfdf9c71e67e2d2d20e002e644aaa6971a
/Java/src/ex8_11_1_polymorphism/Main.java
053a9e56747707fe98f929fd0fda4b8a4cbedbca
[]
no_license
MinjiJo/BaekJoon_Online_Judge
c581ee388110d06be646a4ec60f664dba0328a6f
144b96e1c965fb87ef0f6e2e0619ac147d05a50b
refs/heads/master
2020-07-12T23:28:27.336793
2020-07-03T00:49:01
2020-07-03T00:49:01
204,933,410
0
0
null
null
null
null
UHC
Java
false
false
2,137
java
package ex8_11_1_polymorphism; public class Main { public static void main(String[] args) { EMailSender obj1 = new EMailSender("์ƒ์ผ์„ ์ถ•ํ•˜ํ•ฉ๋‹ˆ๋‹ค", "๊ณ ๊ฐ์„ผํ„ฐ", "[email protected]", "10% ํ• ์ธ์ฟ ํฐ์ด ๋ฐœํ–‰๋˜์—ˆ์Šต๋‹ˆ๋‹ค."); SMSSender obj2 = new SMSSender("์ƒ์ผ์„ ์ถ•ํ•˜ํ•ฉ๋‹ˆ๋‹ค", "๊ณ ๊ฐ์„ผํ„ฐ", "02-333-5555", "10% ํ• ์ธ์ฟ ํฐ์ด ๋ฐœํ–‰๋˜์—ˆ์Šต๋‹ˆ๋‹ค."); //์„œ๋ธŒ ํด๋ž˜์Šค ๊ฐ์ฒด obj1, obj2๋ฅผ ๊ฐ€์ง€๊ณ  ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœ //MessageSender ํด๋ž˜์Šค์—์„œ sendMessage ๋ฉ”์†Œ๋“œ๋ฅผ ์ฃผ์„ ์ฒ˜๋ฆฌํ•  ๊ฒฝ์šฐ //์—๋Ÿฌ ๋ฐœ์ƒ : ์ž๋ฐ” ์ปดํŒŒ์ผ๋Ÿฌ๋Š” ๋ณ€์ˆ˜์˜ ํƒ€์ž…์œผ๋กœ ๊ทธ ๋ฉ”์†Œ๋“œ๊ฐ€ ์žˆ๋Š”์ง€ ์—†๋Š”์ง€ ์ฒดํฌํ•ฉ๋‹ˆ๋‹ค. //MessageSender์— sendMessage() ๋ฉ”์„œ๋“œ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์•„์„œ //The method sendMessage(String) is undefined for the type //์—๋Ÿฌ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. //์ž๋ฐ” ๊ฐ€์ƒ ๊ธฐ๊ณ„(JVM)๋Š” ๊ฐ์ฒด์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ ๋ณ€์ˆ˜์˜ ํƒ€์ž…์— ์ƒ๊ด€์—†์ด //๊ฐ์ฒด๊ฐ€ ์†ํ•˜๋Š” ํด๋ž˜์Šค์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•ฉ๋‹ˆ๋‹ค. send(obj1, "[email protected]"); send(obj1, "[email protected]"); send(obj2, "010-000-0000"); } //MessageSender obj : ์Šˆํผ ํด๋ž˜์Šค ํƒ€์ž…์˜ ํŒŒ๋ผ๋ฏธํ„ฐ static void send(MessageSender obj, String recipient) { //์–ด๋А ํด๋ž˜์Šค์˜ sendMessage ๋ฉ”์†Œ๋“œ๊ฐ€ ํ˜ธ์ถœ๋ ๊นŒ์š”? //EMailSender ๋˜๋Š” SMSSender //์ž๋ฐ” ์ปดํŒŒ์ผ๋Ÿฌ๋Š” ๊ฐ์ฒด๊ฐ€ ์•„๋‹ˆ๋ผ ๋ณ€์ˆ˜์˜ ํƒ€์ž…๋งŒ ๊ฐ€์ง€๊ณ  ๊ทธ ๋ฉ”์†Œ๋“œ๊ฐ€ ์žˆ๋Š”์ง€ ์—†๋Š”์ง€ ์ฒดํฌ //์ถ”์ƒ ๋ฉ”์†Œ๋“œ ์„ ์–ธ์˜ ๋‘ ๋ฒˆ์งธ ๋ชฉ์ : ์Šˆํผํด๋ž˜์Šค์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ์ฒ™ํ•˜๋ฉด์„œ //์ปดํŒŒ์ผ๋Ÿฌ์˜ ์ฒดํฌ๋ฅผ ๋ฌด์‚ฌ ํ†ต๊ณผํ•˜๊ณ  ํ”„๋กœ๊ทธ๋žจ์ด ์‹คํ–‰๋  ๋•Œ๋Š” //์„œ๋ธŒ ํด๋ž˜์Šค์˜ ๋ฉ”์†Œ๋“œ๊ฐ€ ํ˜ธ์ถœ๋˜๋„๋ก ํ•˜๋Š” ๊ฒƒ์ด ์ถ”์ƒ ๋ฉ”์†Œ๋“œ์˜ ๋˜ ๋‹ค๋ฅธ ์‚ฌ์šฉ ๋ชฉ์  //์ถ”์ƒ ๋ฉ”์†Œ๋“œ์˜ ์ฒซ ๋ฒˆ์งธ ๋ชฉ์ : ์„œ๋ธŒํด๋ž˜์Šค์—์„œ ์ด ๋ฉ”์†Œ๋“œ๋ฅผ ๋ฐ˜๋“œ์‹œ ๊ตฌํ˜„ํ•˜๋„๋ก ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด์„œ //๋ถ€๋ชจ ํ•„๋“œ๋ฅผ ๊ฐ€์ ธ์˜ค์ง€๋งŒ ์‹คํ–‰ํ•˜๋ฉด์„œ ์ž์‹์— ์žˆ๋Š”(์˜ค๋ฒ„๋ผ์ด๋”ฉ ๋œ) ๋ฉ”์„œ๋“œ๋ฅผ ์‹คํ–‰ํ•จ //์‹คํ–‰ ์ค‘์— ๋˜๋Š” ๊ฒƒ -> ๋™์  ๋ฐ”์ธ๋”ฉ, ex8_10_์˜ ์‚ฌ๋ก€ -> ์ •์  ๋ฐ”์ธ๋”ฉ obj.sendMessage(recipient); } }
9707ffb6e898833defad537c86599da19bd97b40
0af8b92686a58eb0b64e319b22411432aca7a8f3
/single-large-project/src/main/java/org/gradle/test/performancenull_224/Productionnull_22310.java
3eff617937827330499e2a098279f20c9f8f3bc1
[]
no_license
gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164276
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
2022-09-30T08:04:35
2017-01-26T14:25:33
null
UTF-8
Java
false
false
588
java
package org.gradle.test.performancenull_224; public class Productionnull_22310 { private final String property; public Productionnull_22310(String param) { this.property = param; } public String getProperty() { return property; } private String prop0; public String getProp0() { return prop0; } public void setProp0(String value) { prop0 = value; } private String prop1; public String getProp1() { return prop1; } public void setProp1(String value) { prop1 = value; } }
b07164edc6eb97b829cc03431dd78aad0416cf64
b1d7abf59528ff65e6870e29b4c1f99c9177a592
/src/ArrayStack.java
91883dddd99fd447a5a1807e1e3ce99c373bbd1d
[]
no_license
ReginaClement/code
d895a5e17656309fd537ef8548c4390fb12d684d
22e89ee863e02373614d489a8f6ff9c478357e2f
refs/heads/main
2023-04-02T07:15:01.389750
2021-04-05T17:07:51
2021-04-05T17:07:51
354,891,435
0
0
null
null
null
null
UTF-8
Java
false
false
894
java
import java.util.*; public class ArrayStack { public static void main(String[] args) { Stack stack = new Stack(); System.out.println("push " +stack.push(7)); System.out.println("push " +stack.push(79)); System.out.println("push " +stack.push(70)); System.out.println("pop " +stack.pop()); System.out.println("peek " +stack.peek()); System.out.println("pop " +stack.pop()); System.out.println("peek " +stack.peek()); } static class Stack { int[] array = new int[10]; int data = 0; private int push(int x) { data++; array[data] = x; return x; } private int pop() { int y = array[data--]; return y; } private int peek() { return array[data]; } } }
608e5acdc542a9696804d2fd56b767bdfe35b323
967e3dcf50b1ecc0fe5a965cb4570206b855ef67
/src/org/designpattern/proxy/AnnotationLoader.java
c5c3939cde8d43a8bec994a173f2f25cc37acfbc
[]
no_license
andyzhuangyy/DataStructure
01d2822bebd49947b6fc661deef6815536ef0dbe
d219ec2ccde42a98bfc0bd9f302bef39d935e99b
refs/heads/master
2021-01-13T06:14:57.542230
2014-04-02T13:25:57
2014-04-02T13:25:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,175
java
package org.designpattern.proxy; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class AnnotationLoader { public static <T> T getProxyBean(Class<T> clazz){ T t = (T) newinstance(clazz); Method[] methods = clazz.getMethods(); for(int i=0;i<methods.length;i++){ Annotation pt = methods[i].getAnnotation(Annotation.class); if(pt == null){ continue; } AnnotationProxy pb = (AnnotationProxy) newinstance(pt.proxyClass()); //่ฟ™้‡Œๆ˜ฏ้‡็‚น๏ผŒๅ…ถไธญๅญ˜ๅœจๅฏน่ฑกๅˆ†็บง้“พ๏ผŒ๏ผˆๅœจInvokeHandlerไธญๅผ•็”จไบ†ไธ€ไธชtๅฏน่ฑก๏ผŒๅˆ‡่ฎฐ๏ผ‰็š„ๆƒ…ๅ†ตๅญ˜ๅœจ t = (T) pb.bind(t, methods[i].getName()); } return t; } public static <E> E load(Class cls){ E instance = (E)newinstance(cls); Method[] methods = cls.getMethods(); for(Method m:methods){ Annotation ann = m.getAnnotation(Annotation.class); if(ann==null){ continue; } AnnotationProxy bean = (AnnotationProxy)newinstance(ann.proxyClass()); instance = (E) bean.bind(instance, m.getName()); } return instance; } //public static <T> T newinstance(final Class<T> cls){ public static Object newinstance(final Class cls){ try { Constructor cons = cls.getConstructor(); return cons.newInstance(new Class[]{}); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
86f7c24966d3ee6542d2ec3447db5673d43655f7
3a12b3f82a5a8584e3de9a7765f4d9b7cee393d3
/src/main/java/com/github/thake/avromeasures/MassConverter.java
887f115ac2ea134729efe3b79c846c490b4bc3d1
[]
no_license
thake/avro-measures
e47dce35082831701b3783114521e48630c295c2
dd28fb0438565c07b4a00c1ceed637b8cc461a39
refs/heads/master
2023-02-06T09:42:56.277559
2022-02-23T05:46:57
2022-02-23T05:46:57
241,116,094
0
0
null
2023-01-24T04:02:52
2020-02-17T13:36:50
Java
UTF-8
Java
false
false
1,196
java
package com.github.thake.avromeasures; import org.apache.avro.Conversion; import org.apache.avro.LogicalType; import org.apache.avro.Schema; import tech.units.indriya.quantity.Quantities; import tech.units.indriya.unit.Units; import javax.measure.MetricPrefix; import javax.measure.Quantity; import javax.measure.Unit; import javax.measure.quantity.Length; import javax.measure.quantity.Mass; public class MassConverter extends Conversion<Quantity<Mass>> { private static final Unit<Mass> UNIT = Units.GRAM; private static final MassConverter INSTANCE = new MassConverter(); public static final MassConverter get(){ return INSTANCE; } private MassConverter(){ super(); } public Class<Quantity<Mass>> getConvertedType() { return (Class)Quantity.class; } public String getLogicalTypeName() { return MassLogicalType.MASS_LOGICAL_TYPE_NAME; } @Override public Quantity<Mass> fromLong(Long value, Schema schema, LogicalType type) { return Quantities.getQuantity(value, UNIT); } @Override public Long toLong(Quantity<Mass> value, Schema schema, LogicalType type) { return value.to(UNIT).getValue().longValue(); } }
4bc33ecae8362909da12a65e400314336d1cd69c
2810d434d2ccdcbd2ea1a608571eb4c3799bc592
/app/src/main/java/com/example/examen/peliculas/lstPeliculas/model/LstPeliculasModel.java
4b1bf0cdc7803d6268b5c863f8665d86e411f37a
[]
no_license
aaron0211/ExamenParteAndroid
f60f05c60670d71020ff9d0e055511f257b91fac
23294ff323f2de071e731882f8627eb47d7e51c0
refs/heads/master
2023-02-23T05:00:52.389802
2021-01-23T16:22:33
2021-01-23T16:22:33
329,405,621
0
0
null
null
null
null
UTF-8
Java
false
false
2,127
java
package com.example.examen.peliculas.lstPeliculas.model; import android.os.AsyncTask; import android.widget.AdapterView; import com.example.examen.beans.Pelicula; import com.example.examen.peliculas.lstPeliculas.contract.LstPeliculasContract; import com.example.examen.utils.Post; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class LstPeliculasModel implements LstPeliculasContract.Model{ private ArrayList<Pelicula> lstArrayPeliculas; OnLstPeliculasListener onLstPeliculasListener; @Override public void getPeliculasWS(OnLstPeliculasListener onLstPeliculasListener) { this.onLstPeliculasListener = onLstPeliculasListener; HashMap<String,String> param = new HashMap<>(); param.put("ACTION","PELICULA.FIND_ALL"); DatosAPI dapi = new DatosAPI(param); dapi.execute("http://192.168.18.7:8084/Android/Controller"); } class DatosAPI extends AsyncTask<String, Integer, Boolean>{ private HashMap<String,String> parametros = null; public DatosAPI(HashMap<String, String> parametros){ super(); this.parametros = parametros; } @Override protected Boolean doInBackground(String... strings) { String url_select = strings[0]; try{ Post post = new Post(); JSONArray lstPeliculas = post.getServerDataPost(parametros,url_select); lstArrayPeliculas = Pelicula.getArrayListPeliculaFromJSON(lstPeliculas); }catch (Exception e){ e.printStackTrace(); } return true; } @Override protected void onPostExecute(Boolean respuesta) { if (respuesta){ if (lstArrayPeliculas!=null && lstArrayPeliculas.size()>0){ onLstPeliculasListener.resolve(lstArrayPeliculas); } }else { onLstPeliculasListener.reject("Error al traer los datos del Servidor."); } } } }
831cf7f1d32b69b66e04d7ef4fcbfcb49e42242a
5b0c4ac8bfaf76017ff2ac4fc2152e61100d4c37
/bridge/src/design/patterns/bridge/Rectangle.java
65ee4abba398ee9820b2f15bf661de446e7e6ab2
[ "MIT" ]
permissive
dmpalyvos/design-patterns
c1a363c341211b489183724ce5ed1eef6656a078
550ae1a684a57e04d8b7720f318b3083b49a2b4f
refs/heads/master
2020-04-15T12:44:47.686853
2016-10-21T16:31:00
2016-10-21T16:31:00
61,654,829
0
0
null
null
null
null
UTF-8
Java
false
false
228
java
package design.patterns.bridge; public class Rectangle extends Shape { public Rectangle(final Color color) { super(color); } @Override protected void drawLines() { System.out.println("[*] Drawing a RECTANGLE"); } }
e78442beaadfac6c58871c58303f1615afeb4dfa
6b73046f4005e5a991b0ca2ced86e8be1c9e9ccb
/src/java/org/apache/cassandra/config/.svn/text-base/Config.java.svn-base
cca7745d84f2b3996c2a46f9845a7d9de29d09ce
[ "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
Colex/cassandra-mv
a27c78e3fe927ff84b57e268ac619bcd66a8194f
d6711a79019c2b873ece9144eadcc365260d29fa
refs/heads/master
2021-01-10T19:55:44.301827
2013-12-08T22:34:13
2013-12-08T22:34:13
14,072,437
0
1
Apache-2.0
2023-03-20T11:50:33
2013-11-02T18:45:43
Java
UTF-8
Java
false
false
7,653
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.config; import org.apache.cassandra.cache.SerializingCacheProvider; import org.apache.cassandra.config.EncryptionOptions.ClientEncryptionOptions; import org.apache.cassandra.config.EncryptionOptions.ServerEncryptionOptions; import org.apache.cassandra.io.util.NativeAllocator; import org.apache.cassandra.utils.FBUtilities; /** * A class that contains configuration properties for the cassandra node it runs within. * * Properties declared as volatile can be mutated via JMX. */ public class Config { public String cluster_name = "Test Cluster"; public String authenticator; public String authorizer; public int permissions_validity_in_ms = 2000; /* Hashing strategy Random or OPHF */ public String partitioner; public Boolean auto_bootstrap = true; public volatile Boolean hinted_handoff_enabled = true; public volatile Integer max_hint_window_in_ms = 3600 * 1000; // one hour public SeedProviderDef seed_provider; public DiskAccessMode disk_access_mode = DiskAccessMode.auto; public DiskFailurePolicy disk_failure_policy = DiskFailurePolicy.ignore; /* initial token in the ring */ public String initial_token; public Integer num_tokens = 1; public volatile Long request_timeout_in_ms = new Long(10000); public Long read_request_timeout_in_ms = new Long(10000); public Long range_request_timeout_in_ms = new Long(10000); public Long write_request_timeout_in_ms = new Long(10000); public Long truncate_request_timeout_in_ms = new Long(60000); public Integer streaming_socket_timeout_in_ms = new Integer(0); public boolean cross_node_timeout = false; public volatile Double phi_convict_threshold = 8.0; public Integer concurrent_reads = 8; public Integer concurrent_writes = 32; public Integer concurrent_replicates = 32; public Integer memtable_flush_writers = null; // will get set to the length of data dirs in DatabaseDescriptor public Integer memtable_total_space_in_mb; public Integer storage_port = 7000; public Integer ssl_storage_port = 7001; public String listen_address; public String broadcast_address; public String internode_authenticator; public Boolean start_rpc = true; public String rpc_address; public Integer rpc_port = 9160; public String rpc_server_type = "sync"; public Boolean rpc_keepalive = true; public Integer rpc_min_threads = 16; public Integer rpc_max_threads = Integer.MAX_VALUE; public Integer rpc_send_buff_size_in_bytes; public Integer rpc_recv_buff_size_in_bytes; public Integer internode_send_buff_size_in_bytes; public Integer internode_recv_buff_size_in_bytes; public Boolean start_native_transport = false; public Integer native_transport_port = 9042; public Integer native_transport_min_threads = 16; public Integer native_transport_max_threads = 128; public Integer thrift_max_message_length_in_mb = 16; public Integer thrift_framed_transport_size_in_mb = 15; public Boolean snapshot_before_compaction = false; public Boolean auto_snapshot = true; /* if the size of columns or super-columns are more than this, indexing will kick in */ public Integer column_index_size_in_kb = 64; public Integer in_memory_compaction_limit_in_mb = 64; public Integer concurrent_compactors = FBUtilities.getAvailableProcessors(); public volatile Integer compaction_throughput_mb_per_sec = 16; public Boolean multithreaded_compaction = false; public Integer max_streaming_retries = 3; public volatile Integer stream_throughput_outbound_megabits_per_sec = 200; public String[] data_file_directories; public String saved_caches_directory; // Commit Log public String commitlog_directory; public Integer commitlog_total_space_in_mb; public CommitLogSync commitlog_sync; public Double commitlog_sync_batch_window_in_ms; public Integer commitlog_sync_period_in_ms; public int commitlog_segment_size_in_mb = 32; public String endpoint_snitch; public Boolean dynamic_snitch = true; public Integer dynamic_snitch_update_interval_in_ms = 100; public Integer dynamic_snitch_reset_interval_in_ms = 600000; public Double dynamic_snitch_badness_threshold = 0.1; public String request_scheduler; public RequestSchedulerId request_scheduler_id; public RequestSchedulerOptions request_scheduler_options; public ServerEncryptionOptions server_encryption_options = new ServerEncryptionOptions(); public ClientEncryptionOptions client_encryption_options = new ClientEncryptionOptions(); // this encOptions is for backward compatibility (a warning is logged by DatabaseDescriptor) public ServerEncryptionOptions encryption_options; public InternodeCompression internode_compression = InternodeCompression.none; public int hinted_handoff_throttle_in_kb = 1024; public int max_hints_delivery_threads = 1; public boolean compaction_preheat_key_cache = true; public volatile boolean incremental_backups = false; public int memtable_flush_queue_size = 4; public boolean trickle_fsync = false; public int trickle_fsync_interval_in_kb = 10240; public Long key_cache_size_in_mb = null; public volatile int key_cache_save_period = 14400; public int key_cache_keys_to_save = Integer.MAX_VALUE; public long row_cache_size_in_mb = 0; public volatile int row_cache_save_period = 0; public int row_cache_keys_to_save = Integer.MAX_VALUE; public String row_cache_provider = SerializingCacheProvider.class.getSimpleName(); public String memory_allocator = NativeAllocator.class.getSimpleName(); public boolean populate_io_cache_on_flush = false; public boolean inter_dc_tcp_nodelay = false; private static boolean isClientMode = false; public boolean preheat_kernel_page_cache = false; private static boolean outboundBindAny = false; public static boolean getOutboundBindAny() { return outboundBindAny; } public static void setOutboundBindAny(boolean value) { outboundBindAny = value; } public static boolean isClientMode() { return isClientMode; } public static void setClientMode(boolean clientMode) { isClientMode = clientMode; } public static enum CommitLogSync { periodic, batch } public static enum InternodeCompression { all, none, dc } public static enum DiskAccessMode { auto, mmap, mmap_index_only, standard, } public static enum DiskFailurePolicy { best_effort, stop, ignore, } public static enum RequestSchedulerId { keyspace } }
00ea80c2c3e86a7adf4fecf7bd0f5db3fe1183a8
4e61f371ea912cce64198714152d6668802b1306
/week 4/negative_cycle/NegativeCycle.java
ce396d67f989a9e8a61448b0abf670c1a0702499
[]
no_license
ans-human/algo-on-graphs
cac15421274df296b98027524ff2e4d6f91bf0d9
a55baaac09853a09df07834de762bc7af029d632
refs/heads/master
2022-11-20T16:01:41.572661
2020-06-16T07:12:55
2020-06-24T06:21:50
280,904,252
0
1
null
2020-07-19T16:21:35
2020-07-19T16:21:34
null
UTF-8
Java
false
false
1,509
java
import java.util.ArrayList; import java.util.Scanner; public class NegativeCycle { private static final int inf = Integer.MAX_VALUE; private static int negativeCycle(ArrayList<Integer>[] adj, ArrayList<Integer>[] cost) { // write your code here long[] dist = new long[adj.length]; for (int i = 0;i < adj.length; i++) { dist[i] = inf; } dist[0] = 0; for (int i = 0; i < adj.length; i++) { for(int u = 0; u < adj.length; u++){ for (int v : adj[u]) { int v_index = adj[u].indexOf(v); if (dist[v] > dist[u] + cost[u].get(v_index)) { dist[v] = dist[u] + cost[u].get(v_index); if(i == adj.length - 1) return 1; } } } } return 0; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); ArrayList<Integer>[] adj = (ArrayList<Integer>[])new ArrayList[n]; ArrayList<Integer>[] cost = (ArrayList<Integer>[])new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<Integer>(); cost[i] = new ArrayList<Integer>(); } for (int i = 0; i < m; i++) { int x, y, w; x = scanner.nextInt(); y = scanner.nextInt(); w = scanner.nextInt(); adj[x - 1].add(y - 1); cost[x - 1].add(w); } System.out.println(negativeCycle(adj, cost)); } }
66b23373cbb0baca432593df54cf414ea32a1b59
73e2bcaba4c6f8c07e5855a2ae051d3dfad8e221
/eclipse-workspace/1ยบDAM/T11_ejTeorico_6_Botones_y_BarrasHerramientas/src/boton_y_barraHerramienta/GestorMenu.java
b637099b5d44180d779c7be9b5bf91b5a4fa1dc9
[]
no_license
JoseAntonioVelasco/2DAM_Workspaces
07c59c1a2a726870abf9158f67bd8001a07f8b2d
1e401bbc9cbbe4989f6cedcbdaa339cc27f6d57c
refs/heads/main
2023-03-11T21:27:32.396965
2021-02-26T23:16:57
2021-02-26T23:16:57
301,367,114
0
0
null
null
null
null
UTF-8
Java
false
false
385
java
package boton_y_barraHerramienta; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JLabel; public class GestorMenu implements ActionListener{ private JLabel jl; private String s; public GestorMenu(JLabel jl,String s) { this.jl=jl; this.s=s; } @Override public void actionPerformed(ActionEvent e) { this.jl.setText(s); } }
726a556f76ffcb16ad240866c8401ea4343c23c9
54eb06ccb05adb0df0016e0c3dec08c9d1d5fa5d
/smilecamera/src/androidTest/java/com/tdx/smilecamera/ExampleInstrumentedTest.java
e53f730501627208aa299e48215d0ce0550ab74a
[ "Apache-2.0" ]
permissive
q2209617/SmileCameraLibrary
d85ec9de816ebc6acb695f472529c0f1a1b679c7
8bf548e63c0dda6d5ca521f24430d67e6b706d08
refs/heads/master
2020-05-30T21:20:03.326854
2019-06-11T10:17:24
2019-06-11T10:17:24
189,969,623
0
0
null
null
null
null
UTF-8
Java
false
false
727
java
package com.tdx.smilecamera; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.tdx.smilecamera.test", appContext.getPackageName()); } }
ba5d587d4172581f4212908015a9bc22e6381782
71bf2a61e55833b96b16c95f9efc99857f79eaaf
/SMHT.KingStar.Web/src/main/java/smht/kingstar/entities/tables/UserInfo.java
76f072760ac8a569f191eb419d6e0becb6187312
[]
no_license
onlywhy/Git
b01d4bfccf66bdb3a4361e36762d264c6e0cf646
1eac027a12512104b5d8c61fc97fe36c134dcd2d
refs/heads/master
2016-09-06T10:37:26.687316
2014-11-25T15:09:00
2014-11-25T15:09:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,763
java
/** * This class is generated by jOOQ */ package smht.kingstar.entities.tables; /** * This class is generated by jOOQ. */ @javax.annotation.Generated(value = { "http://www.jooq.org", "3.4.4" }, comments = "This class is generated by jOOQ") @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class UserInfo extends org.jooq.impl.TableImpl<smht.kingstar.entities.tables.records.UserInfoRecord> { private static final long serialVersionUID = -281160289; /** * The singleton instance of <code>smht.user_info</code> */ public static final smht.kingstar.entities.tables.UserInfo USER_INFO = new smht.kingstar.entities.tables.UserInfo(); /** * The class holding records for this type */ @Override public java.lang.Class<smht.kingstar.entities.tables.records.UserInfoRecord> getRecordType() { return smht.kingstar.entities.tables.records.UserInfoRecord.class; } /** * The column <code>smht.user_info.user_id</code>. */ public final org.jooq.TableField<smht.kingstar.entities.tables.records.UserInfoRecord, java.lang.Integer> USER_ID = createField("user_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>smht.user_info.user_nm</code>. */ public final org.jooq.TableField<smht.kingstar.entities.tables.records.UserInfoRecord, java.lang.String> USER_NM = createField("user_nm", org.jooq.impl.SQLDataType.VARCHAR.length(50), this, ""); /** * The column <code>smht.user_info.user_cd</code>. */ public final org.jooq.TableField<smht.kingstar.entities.tables.records.UserInfoRecord, java.lang.String> USER_CD = createField("user_cd", org.jooq.impl.SQLDataType.VARCHAR.length(50), this, ""); /** * The column <code>smht.user_info.user_mm</code>. */ public final org.jooq.TableField<smht.kingstar.entities.tables.records.UserInfoRecord, java.lang.String> USER_MM = createField("user_mm", org.jooq.impl.SQLDataType.VARCHAR.length(50), this, ""); /** * Create a <code>smht.user_info</code> table reference */ public UserInfo() { this("user_info", null); } /** * Create an aliased <code>smht.user_info</code> table reference */ public UserInfo(java.lang.String alias) { this(alias, smht.kingstar.entities.tables.UserInfo.USER_INFO); } private UserInfo(java.lang.String alias, org.jooq.Table<smht.kingstar.entities.tables.records.UserInfoRecord> aliased) { this(alias, aliased, null); } private UserInfo(java.lang.String alias, org.jooq.Table<smht.kingstar.entities.tables.records.UserInfoRecord> aliased, org.jooq.Field<?>[] parameters) { super(alias, smht.kingstar.entities.Smht.SMHT, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public org.jooq.Identity<smht.kingstar.entities.tables.records.UserInfoRecord, java.lang.Integer> getIdentity() { return smht.kingstar.entities.Keys.IDENTITY_USER_INFO; } /** * {@inheritDoc} */ @Override public org.jooq.UniqueKey<smht.kingstar.entities.tables.records.UserInfoRecord> getPrimaryKey() { return smht.kingstar.entities.Keys.KEY_USER_INFO_PRIMARY; } /** * {@inheritDoc} */ @Override public java.util.List<org.jooq.UniqueKey<smht.kingstar.entities.tables.records.UserInfoRecord>> getKeys() { return java.util.Arrays.<org.jooq.UniqueKey<smht.kingstar.entities.tables.records.UserInfoRecord>>asList(smht.kingstar.entities.Keys.KEY_USER_INFO_PRIMARY); } /** * {@inheritDoc} */ @Override public smht.kingstar.entities.tables.UserInfo as(java.lang.String alias) { return new smht.kingstar.entities.tables.UserInfo(alias, this); } /** * Rename this table */ public smht.kingstar.entities.tables.UserInfo rename(java.lang.String name) { return new smht.kingstar.entities.tables.UserInfo(name, null); } }
3385e250b1fd96d02de934c425657b28794ca0a7
3225b0cf9e348993f24c13ea4d0bc8848952bb0f
/src/main/java/nagoya/code4/resas/PatentsLocationsResult.java
b27321a28909aedddbd25fbf0cb55b8510ee0b8b
[]
no_license
code4nagoya/resas-client
fd5f6da6b5dd874d83fd78960bf61a3d61b9607a
07c910ae27f9839f035881fe7dd2aa646f156ab6
refs/heads/master
2021-09-04T18:46:06.101049
2018-01-21T07:40:32
2018-01-21T07:40:32
105,264,737
3
2
null
2018-01-21T07:40:33
2017-09-29T11:24:48
Java
UTF-8
Java
false
false
119
java
package nagoya.code4.resas; public class PatentsLocationsResult extends AbstractListResult<PatentLocationResult> { }
e1b6bf5d5594c1e91b6647e6c4f75007c39ab3af
b091c7718196beaf60a8825c8c0840bb2a88303b
/src/main/java/br/com/guiabolso/transacaoapi/modulos/transacao/service/TransacaoService.java
6018c836db21945c7c9a22eebd14d7d18a9c11f8
[ "MIT" ]
permissive
vhnegrisoli/guia-bolso-transacao-api
97dda1e17aff53a8728b74e4cc5e209925458578
ba61a50d766c7bd889e83c2832f76f0d806f3a6d
refs/heads/master
2023-04-01T03:46:23.031300
2021-04-08T23:12:58
2021-04-08T23:12:58
356,036,267
1
0
null
null
null
null
UTF-8
Java
false
false
4,724
java
package br.com.guiabolso.transacaoapi.modulos.transacao.service; import br.com.guiabolso.transacaoapi.modulos.transacao.model.Transacao; import br.com.guiabolso.transacaoapi.modulos.transacao.repository.TransacaoRepository; import br.com.guiabolso.transacaoapi.modulos.usuario.dto.UsuarioTransacoesResponse; import br.com.guiabolso.transacaoapi.modulos.usuario.model.Usuario; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.time.YearMonth; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import static br.com.guiabolso.transacaoapi.modulos.comum.constantes.Constantes.*; import static br.com.guiabolso.transacaoapi.modulos.comum.utilitarios.GeradorUtil.gerarNumeroAleatorioEntre; import static org.springframework.util.ObjectUtils.isEmpty; @Service public class TransacaoService { @Autowired private TransacaoRepository transacaoRepository; public List<UsuarioTransacoesResponse> buscarTransacoesPorUsuarioEDataReferencia(Usuario usuario, YearMonth dataReferencia) { return tratarTransacoesPorUsuarioEDataReferencia(usuario, dataReferencia) .stream() .map(UsuarioTransacoesResponse::converterDe) .collect(Collectors.toList()); } private List<Transacao> tratarTransacoesPorUsuarioEDataReferencia(Usuario usuario, YearMonth dataReferencia) { if (!transacaoRepository.existsByUsuarioAndDataReferencia(usuario, dataReferencia)) { return gerarTransacoesParaUsuarioComDataDeReferencia(usuario, dataReferencia); } return transacaoRepository.findByUsuarioAndDataReferencia(usuario, dataReferencia); } @Transactional private List<Transacao> gerarTransacoesParaUsuarioComDataDeReferencia(Usuario usuario, YearMonth dataReferencia) { var novasTransacoes = IntStream .rangeClosed(VALOR_MINIMO_NUMERO_TRANSACOES, gerarNumeroAleatorioEntre(VALOR_MINIMO_NUMERO_TRANSACOES, VALOR_MAXIMO_NUMERO_TRANSACOES)) .mapToObj(i -> Transacao.gerarTransacao(usuario, dataReferencia)) .collect(Collectors.toList()); transacaoRepository.saveAll(novasTransacoes); var transacoes = transacaoRepository.findByUsuarioAndDataReferencia(usuario, dataReferencia); validarTransacoesExistentesParaAnoTodo(dataReferencia.getYear()); transacoes.forEach(this::tratarDuplicidade); return transacoes; } private void validarTransacoesExistentesParaAnoTodo(Integer ano) { var mesesDoAno = IntStream .rangeClosed(VALOR_MINIMO_MES, VALOR_MAXIMO_MES) .mapToObj(mes -> YearMonth.of(ano, mes)) .collect(Collectors.toList()); var datasExistentesParaAno = transacaoRepository.findByDataReferenciaIn(mesesDoAno); if (datasExistentesParaAno.size() == VALOR_MAXIMO_MES) { var quantidadeMeses = gerarNumeroAleatorioEntre(VALOR_MINIMO_DUPLICIDADES_MENSAIS, VALOR_MAXIMO_MES); IntStream .rangeClosed(VALOR_MINIMO_MES, quantidadeMeses) .forEach(mes -> gerarDuplicidadeParaMesAno(ano, mes)); } } @Transactional private void gerarDuplicidadeParaMesAno(Integer ano, Integer mes) { var dataReferencia = YearMonth.of(ano, mes); transacaoRepository.findTop1ByDataReferencia(dataReferencia) .ifPresent(transacaoExistente -> { var transacaoComDuplicidade = new Transacao(); BeanUtils.copyProperties(transacaoExistente, transacaoComDuplicidade); transacaoComDuplicidade.setarDuplicacaoParaNovaTransacao(); transacaoRepository.save(transacaoComDuplicidade); }); } private void tratarDuplicidade(Transacao transacao) { var transacoesExistentes = transacaoRepository .findByDescricaoAndDataReferenciaAndValor( transacao.getDescricao(), transacao.getDataReferencia(), transacao.getValor()); if (!isEmpty(transacoesExistentes) && transacoesExistentes.size() > VALOR_MINIMO_NUMERO_TRANSACOES) { transacao.setDuplicated(true); transacoesExistentes.get(PRIMEIRA_TRANSACAO).setDuplicated(false); transacoesExistentes .stream() .skip(PRIMEIRA_TRANSACAO) .forEach(transacaoExistente -> transacaoExistente.setDuplicated(true)); transacaoRepository.saveAll(transacoesExistentes); } } }
45b9bacae6a5dc7b9d08958fded5e651a9be720c
83a4e2fc957f9812dbc574eb0fe4ff6ba2f5b1b3
/logistics/src/main/java/com/cl/logistics/dao/ICustomerBillClearDao.java
68ce8f92246f3e814db8a9d42a363ab0966437a6
[]
no_license
TANGWO/code
8c82eaa55712d904f25caf4bdd92f0cedf0071f5
2dccc788e5e1b5a9ca4e1432d299bad2b91b3441
refs/heads/master
2020-04-15T02:29:27.086977
2019-01-04T09:33:16
2019-01-04T09:33:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
302
java
package com.cl.logistics.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.cl.logistics.bean.CustomerBillClear; public interface ICustomerBillClearDao extends JpaRepository<CustomerBillClear, Long> { public CustomerBillClear findByGoodsBillCode(String billCode); }
9f668730dd2a9bfd640ff25581f6788e2089d687
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_206f1be8d80316cd0a72456d5959fef23863eb32/InternalDbHelper/2_206f1be8d80316cd0a72456d5959fef23863eb32_InternalDbHelper_t.java
30bfdaed5a81e4b95f1f39a0348e406837ad7825
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
11,397
java
package yuku.alkitab.base.storage; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import yuku.afw.App; import yuku.alkitab.base.model.Ari; import yuku.alkitab.base.storage.Db.Bookmark2; public class InternalDbHelper extends SQLiteOpenHelper { public static final String TAG = InternalDbHelper.class.getSimpleName(); public InternalDbHelper(Context context) { super(context, "AlkitabDb", null, App.getVersionCode()); //$NON-NLS-1$ } @Override public void onOpen(SQLiteDatabase db) { // db.execSQL("PRAGMA synchronous=OFF"); } @Override public void onCreate(SQLiteDatabase db) { Log.d(TAG, "onCreate dipanggil"); //$NON-NLS-1$ createTableBukmak2(db); createIndexBukmak2(db); createTableRenungan(db); createIndexRenungan(db); createTableEdisi(db); createIndexEdisi(db); createTableLabel(db); createIndexLabel(db); createTableBukmak2_Label(db); createIndexBukmak2_Label(db); createTableProgressMark(db); insertDefaultProgressMarks(db); } private void createTableBukmak2(SQLiteDatabase db) { db.execSQL(String.format("create table if not exists %s (" + //$NON-NLS-1$ "_id integer primary key autoincrement, " + //$NON-NLS-1$ "%s integer, " + // ari //$NON-NLS-1$ "%s integer, " + // jenis //$NON-NLS-1$ "%s text, " + // tulisan //$NON-NLS-1$ "%s integer, " + // waktuTambah //$NON-NLS-1$ "%s integer)", // waktuUbah //$NON-NLS-1$ Db.TABLE_Bookmark2, Db.Bookmark2.ari, Db.Bookmark2.kind, Db.Bookmark2.caption, Db.Bookmark2.addTime, Db.Bookmark2.modifyTime)); } private void createIndexBukmak2(SQLiteDatabase db) { // index Bukmak2(ari) db.execSQL(String.format("create index if not exists index_201 on %s (%s)", Db.TABLE_Bookmark2, Db.Bookmark2.ari)); //$NON-NLS-1$ // index Bukmak2(jenis,ari) db.execSQL(String.format("create index if not exists index_202 on %s (%s, %s)", Db.TABLE_Bookmark2, Db.Bookmark2.kind, Db.Bookmark2.ari)); //$NON-NLS-1$ // index Bukmak2(jenis,waktuUbah) db.execSQL(String.format("create index if not exists index_203 on %s (%s, %s)", Db.TABLE_Bookmark2, Db.Bookmark2.kind, Db.Bookmark2.modifyTime)); //$NON-NLS-1$ // index Bukmak2(jenis,waktuTambah) db.execSQL(String.format("create index if not exists index_204 on %s (%s, %s)", Db.TABLE_Bookmark2, Db.Bookmark2.kind, Db.Bookmark2.addTime)); //$NON-NLS-1$ // index Bukmak2(jenis,tulisan) db.execSQL(String.format("create index if not exists index_205 on %s (%s, %s collate NOCASE)", Db.TABLE_Bookmark2, Db.Bookmark2.kind, Db.Bookmark2.caption)); //$NON-NLS-1$ } private void createTableRenungan(SQLiteDatabase db) { db.execSQL(String.format("create table if not exists %s (" + //$NON-NLS-1$ "_id integer primary key autoincrement, " + //$NON-NLS-1$ "%s text, " + // nama //$NON-NLS-1$ "%s text, " + // tgl (yyyymmdd) //$NON-NLS-1$ "%s text, " + // header //$NON-NLS-1$ "%s text, " + // judul //$NON-NLS-1$ "%s text, " + // isi //$NON-NLS-1$ "%s integer," + // siap pakai //$NON-NLS-1$ "%s integer)", // waktuSentuh //$NON-NLS-1$ Db.TABLE_Devotion, Db.Devotion.name, Db.Devotion.date, Db.Devotion.header, Db.Devotion.title, Db.Devotion.body, Db.Devotion.readyToUse, Db.Devotion.touchTime)); } private void createIndexRenungan(SQLiteDatabase db) { // index Renungan(nama) db.execSQL(String.format("create index if not exists index_101 on %s (%s)", Db.TABLE_Devotion, Db.Devotion.name)); //$NON-NLS-1$ // index Renungan(nama,tgl) db.execSQL(String.format("create index if not exists index_102 on %s (%s, %s)", Db.TABLE_Devotion, Db.Devotion.name, Db.Devotion.date)); //$NON-NLS-1$ // index Renungan(tgl) db.execSQL(String.format("create index if not exists index_103 on %s (%s)", Db.TABLE_Devotion, Db.Devotion.date)); //$NON-NLS-1$ // index Renungan(waktuSentuh) db.execSQL(String.format("create index if not exists index_104 on %s (%s)", Db.TABLE_Devotion, Db.Devotion.touchTime)); //$NON-NLS-1$ } private void createTableEdisi(SQLiteDatabase db) { db.execSQL("create table if not exists " + Db.TABLE_Version + " (" + //$NON-NLS-1$ //$NON-NLS-2$ "_id integer primary key autoincrement, " + //$NON-NLS-1$ Db.Version.shortName + " text, " + //$NON-NLS-1$ Db.Version.title + " text, " + // judul (keliatan sama user) //$NON-NLS-1$ Db.Version.kind + " text, " + // jenis (yes) //$NON-NLS-1$ Db.Version.description + " text, " + // keterangan tambahan, mungkin bisa diedit user kalo perlu //$NON-NLS-1$ Db.Version.filename + " text, " + // nama file di sd card (full path) //$NON-NLS-1$ Db.Version.filename_originalpdb + " text, " + // nama file kalau bekas dikonvert dari pdb (nama doang) //$NON-NLS-1$ Db.Version.active + " integer, " + // tampilkan di daftar edisi? //$NON-NLS-1$ Db.Version.ordering + " integer)"); //$NON-NLS-1$ } private void createIndexEdisi(SQLiteDatabase db) { // index Edisi(urutan) db.execSQL(String.format("create index if not exists index_301 on %s (%s)", Db.TABLE_Version, Db.Version.ordering)); //$NON-NLS-1$ // index Edisi(shortName) db.execSQL(String.format("create index if not exists index_302 on %s (%s)", Db.TABLE_Version, Db.Version.shortName)); //$NON-NLS-1$ // index Edisi(judul) db.execSQL(String.format("create index if not exists index_303 on %s (%s)", Db.TABLE_Version, Db.Version.title)); //$NON-NLS-1$ } private void createTableLabel(SQLiteDatabase db) { db.execSQL("create table if not exists " + Db.TABLE_Label + " (" + //$NON-NLS-1$ //$NON-NLS-2$ "_id integer primary key autoincrement, " + //$NON-NLS-1$ Db.Label.title + " text, " + //$NON-NLS-1$ Db.Label.ordering + " integer, " + //$NON-NLS-1$ Db.Label.backgroundColor + " text)"); //$NON-NLS-1$ } private void createIndexLabel(SQLiteDatabase db) { // index Label(urutan) db.execSQL(String.format("create index if not exists index_401 on %s (%s)", Db.TABLE_Label, Db.Label.ordering)); //$NON-NLS-1$ } private void createTableBukmak2_Label(SQLiteDatabase db) { db.execSQL("create table if not exists " + Db.TABLE_Bookmark2_Label + " (" + //$NON-NLS-1$ //$NON-NLS-2$ "_id integer primary key autoincrement, " + //$NON-NLS-1$ Db.Bookmark2_Label.bookmark2_id + " integer, " + //$NON-NLS-1$ Db.Bookmark2_Label.label_id + " integer)"); //$NON-NLS-1$ } private void createIndexBukmak2_Label(SQLiteDatabase db) { // index Bukmak2_Label(bukmak2_id) db.execSQL(String.format("create index if not exists index_501 on %s (%s)", Db.TABLE_Bookmark2_Label, Db.Bookmark2_Label.bookmark2_id)); //$NON-NLS-1$ // index Bukmak2_Label(label_id) db.execSQL(String.format("create index if not exists index_502 on %s (%s)", Db.TABLE_Bookmark2_Label, Db.Bookmark2_Label.label_id)); //$NON-NLS-1$ // unique index Bukmak2_Label(bukmak2_id, label_id) db.execSQL(String.format("create unique index if not exists index_503 on %s (%s, %s)", Db.TABLE_Bookmark2_Label, Db.Bookmark2_Label.bookmark2_id, Db.Bookmark2_Label.label_id)); //$NON-NLS-1$ } private void createTableProgressMark(SQLiteDatabase db) { db.execSQL("create table if not exists " + Db.TABLE_ProgressMark + " (" + "_id integer primary key autoincrement, " + Db.ProgressMark.caption + " text, " + Db.ProgressMark.ari + " integer, " + Db.ProgressMark.modifyTime + " integer)"); } private void insertDefaultProgressMarks(SQLiteDatabase db) { ContentValues cv = new ContentValues(); cv.put(Db.ProgressMark.ari, 0); for (int i = 0; i < 5; i++) { db.insert(Db.TABLE_ProgressMark, null, cv); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG, "onUpgrade dipanggil, oldVersion=" + oldVersion + " newVersion=" + newVersion); //$NON-NLS-1$ //$NON-NLS-2$ if (oldVersion <= 23) { // konvert dari Bukmak ke Bukmak2 convertFromBookmarkToBookmark2(db); } if (oldVersion <= 50) { // tambah tabel Edisi createTableEdisi(db); createIndexEdisi(db); } if (oldVersion <= 69) { // 70: 2.0.0 // tambah tabel Label dan Bukmak2_Label createTableLabel(db); createIndexLabel(db); createTableBukmak2_Label(db); createIndexBukmak2_Label(db); } if (oldVersion <= 70) { // 71: 2.0.0 juga // tambah index di Bukmak2 createIndexBukmak2(db); } if (oldVersion <= 71) { // 72: 2.0.0 juga // tambah index di Renungan createIndexRenungan(db); } if (oldVersion <= 102) { // 103: 2.7.1 addShortNameColumnAndIndexToEdisi(db); } if (oldVersion <= 126) { // 127: 3.2.0 createTableProgressMark(db); insertDefaultProgressMarks(db); } } private void addShortNameColumnAndIndexToEdisi(SQLiteDatabase db) { db.execSQL("alter table " + Db.TABLE_Version + " add column " + Db.Version.shortName + " text"); // index Edisi(shortName) db.execSQL(String.format("create index if not exists index_302 on %s (%s)", Db.TABLE_Version, Db.Version.shortName)); //$NON-NLS-1$ // index Edisi(judul) db.execSQL(String.format("create index if not exists index_303 on %s (%s)", Db.TABLE_Version, Db.Version.title)); //$NON-NLS-1$ } private void convertFromBookmarkToBookmark2(SQLiteDatabase db) { String TABEL_Bukmak = "Bukmak"; //$NON-NLS-1$ class Bukmak { public static final String alamat = "alamat"; //$NON-NLS-1$ public static final String waktuTambah = "waktuTambah"; //$NON-NLS-1$ public static final String kitab = "kitab"; //$NON-NLS-1$ public static final String pasal = "pasal"; //$NON-NLS-1$ public static final String ayat = "ayat"; //$NON-NLS-1$ } createTableBukmak2(db); createIndexBukmak2(db); // pindahin data dari Bukmak ke Bukmak2 db.beginTransaction(); try { Cursor cursor = db.query(TABEL_Bukmak, new String[] {Bukmak.alamat, Bukmak.kitab, Bukmak.pasal, Bukmak.ayat, Bukmak.waktuTambah}, null, null, null, null, null); int kolom_alamat = cursor.getColumnIndex(Bukmak.alamat); int kolom_kitab = cursor.getColumnIndex(Bukmak.kitab); int kolom_pasal = cursor.getColumnIndex(Bukmak.pasal); int kolom_ayat = cursor.getColumnIndex(Bukmak.ayat); int kolom_waktuTambah = cursor.getColumnIndex(Bukmak.waktuTambah); ContentValues cv = new ContentValues(); // default cv.put(Bookmark2.kind, Bookmark2.kind_bookmark); while (true) { boolean more = cursor.moveToNext(); if (!more) { break; } cv.put(Bookmark2.caption, cursor.getString(kolom_alamat)); int kitab = cursor.getInt(kolom_kitab); int pasal = cursor.getInt(kolom_pasal); int ayat = cursor.getInt(kolom_ayat); int ari = Ari.encode(kitab, pasal, ayat); cv.put(Bookmark2.ari, ari); Integer waktu = Integer.valueOf(cursor.getString(kolom_waktuTambah)); cv.put(Bookmark2.addTime, waktu); cv.put(Bookmark2.modifyTime, waktu); db.insertOrThrow(Db.TABLE_Bookmark2, null, cv); } cursor.close(); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } }
0b54752f13aff9ad3d0eedce7e2140d130509f24
2b72ba860b81c54a61cc4abcb1a927c138d5800f
/service-router-zuul/src/main/java/com/easy/ms/router/filter/post/RestApiResponseFilter.java
be1f0af79e30459e360d9f13fcab8ad66e07e114
[]
no_license
todoo/spring-cloud-demo
602a0854a2c6c05de6fadaaf037f94e327f2a6a4
022ab3bf88084e37352fb65ba5c799cb31033954
refs/heads/master
2021-05-03T20:26:20.962629
2018-04-26T08:49:59
2018-04-26T08:49:59
120,429,114
0
0
null
null
null
null
UTF-8
Java
false
false
3,954
java
package com.easy.ms.router.filter.post; import java.io.IOException; import java.nio.charset.Charset; import java.util.Date; import java.util.Map; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; import org.springframework.cloud.netflix.zuul.filters.support.ResettableServletInputStreamWrapper; import org.springframework.stereotype.Component; import org.springframework.util.StreamUtils; import com.easy.ms.router.service.AppService; import com.easy.ms.service.base.constants.SignTypeEnum; import com.easy.ms.service.base.utils.DateUtils; import com.easy.ms.service.base.utils.RSAUtils; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import lombok.extern.slf4j.Slf4j; /** * ๅฏน่ฟ”ๅ›ž็ป“ๆžœ่ฟ›่กŒ็ญพๅ * @author tkx * */ @Slf4j @Component public class RestApiResponseFilter extends ZuulFilter { @Autowired private AppService appService; @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); HttpServletResponse response = ctx.getResponse(); String appId = request.getHeader("appId"); String signType = SignTypeEnum.RSA.getCode(); String timestamp = DateUtils.formatDateTime(new Date()); response.setHeader("appId", appId); response.setHeader("signType", signType); response.setHeader("timestamp", timestamp); Map<String, String> signParamMap = new TreeMap<>(); signParamMap.put("appId", appId); signParamMap.put("signType", signType); signParamMap.put("timestamp", timestamp); String body = null; if ((body = this.getResponseBody(ctx)) != null) { signParamMap.put("body", body); } // ๆŒ‰ๅญ—ๆฎตๅญ—ๅ…ธๆŽ’ๅบ็”Ÿๆˆๅพ…็ญพๅๅญ—็ฌฆไธฒ String signString = ""; for (String key : signParamMap.keySet()) { signString = signString + "&" + key + "=" + signParamMap.get(key); } signString = signString.replaceFirst("&", ""); response.setHeader("sign", this.sign(appId, signString, signType)); return null; } @Override public String filterType() { return FilterConstants.POST_TYPE; } @Override public int filterOrder() { return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 2; } private String sign(String appId, String signStr, String signType) { if (SignTypeEnum.RSA.getCode().equalsIgnoreCase(signType)) { // ๅŠ ๅฏ†็ง้’ฅ String privateKey = appService.getServerRsaPrivateKey(appId); try { RSAUtils.sign(signStr.getBytes("UTF-8"), privateKey); } catch (Exception e) { log.error("rsa sign error:", e); return null; } } return null; } private String getResponseBody(RequestContext ctx) { if (ctx.getResponseBody() != null) { return ctx.getResponseBody(); } try { ResettableServletInputStreamWrapper resettableServletInputStreamWrapper = new ResettableServletInputStreamWrapper( StreamUtils.copyToByteArray(ctx.getResponseDataStream())); ctx.setResponseDataStream(resettableServletInputStreamWrapper); String response = StreamUtils.copyToString(resettableServletInputStreamWrapper, Charset.forName("UTF-8")); resettableServletInputStreamWrapper.reset(); return response; } catch (IOException e) { log.error("get response error:", e); } return null; } }
8c276a66ec1ce5908ca1452ca53793d844452924
0e6b8e068990e01831fcc1c88dc5ac8569482db9
/app/src/test/java/com/example/wheatherforecast/ExampleUnitTest.java
ef737b0357923e5949e607f4eb66fdc6dee7d3cc
[]
no_license
srl88/WeatherApp
48814fba2a3cd3a35bc8bfed45182a34609341a1
4b64da009d8c1234e602b826ab6f906d0be26fa6
refs/heads/master
2020-05-14T21:29:21.994809
2019-04-17T20:34:25
2019-04-17T20:34:25
181,964,035
0
0
null
null
null
null
UTF-8
Java
false
false
389
java
package com.example.wheatherforecast; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
96eafa8e79fb5755b63e082044089e17b392ee7b
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/28/28_a9cd8e1278a05bd112fea305faa5c8e9c0a4771a/UserImpl/28_a9cd8e1278a05bd112fea305faa5c8e9c0a4771a_UserImpl_s.java
368a19b8ef7ad19978a1e96b2baf0e3529ea7b21
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
1,925
java
/* * JBoss, a division of Red Hat * Copyright 2012, Red Hat Middleware, LLC, and individual * contributors as indicated by the @authors tag. See the * copyright.txt in the distribution for a full listing of * individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.services.organization.idm; /** * TODO: This is temporary implementation, which should be removed after https://issues.jboss.org/browse/EXOJCR-1780 will be fixed * and available in GateIn. * * @author <a href="mailto:[email protected]">Marek Posolda</a> */ public class UserImpl extends org.exoplatform.services.organization.impl.UserImpl { private String displayName; public UserImpl() { super(); } public UserImpl(String username) { super(username); } @Override public String getFullName() { return displayName != null ? displayName : getFirstName() + " " + getLastName(); } @Override public void setFullName(String fullName) { this.displayName = fullName; } public String getDisplayName() { return this.displayName; } }
1d411d664f94e582e4e87f9e2227a562f2ed214c
b3fb8289104bc09f7d2f98c792b4bfbc6373d343
/app/us/sosia/magnet/service/ConverterServiceConstants.java
38d5c8cacbf3e7dc1fd448b1423aaed8fd58f996
[ "Apache-2.0" ]
permissive
He-Pin/magnetService
629fbb5e87b385d097bbb875284d27cb5b3e963e
296d9341ceb2debf43857b4288f81f6b1299c715
refs/heads/master
2022-05-17T16:09:48.860811
2013-12-04T09:22:00
2013-12-04T09:22:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
212
java
package us.sosia.magnet.service; /** * Author: kerr * Mail: [email protected] */ public class ConverterServiceConstants { public static boolean CacheEnable = true; public static int CacheTimeOut = 10; }
328e8ccbc88e2f6f3e647a609684847db271b27f
e3d0a1d8de479440ac24892675ef943e0d55c68a
/src/GUI/FrmAddNanny1.java
cb6a332518407ccc7a92454ce9e48e47dc6e7748
[]
no_license
duynguyen591990/child-care
fd2f33c6303e3c7596736486c1efa8c98be4de4f
fcef9d30e1ab184713643f1bb8f8b18b8f913955
refs/heads/master
2021-01-22T23:58:41.967140
2012-01-21T17:53:28
2012-01-21T17:53:28
32,220,881
0
0
null
null
null
null
UTF-8
Java
false
false
22,004
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * FrmAddNanny1.java * * Created on Nov 27, 2011, 10:13:18 PM */ package GUI; import DAO.Connect; import DatabaseAccess.quanLyBaoMau; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import javax.swing.JOptionPane; /** * * @author Dell */ public class FrmAddNanny1 extends javax.swing.JFrame { Connect connect = new Connect(); Connection conn; ResultSet rs; PreparedStatement pstmt; quanLyBaoMau nhap = new quanLyBaoMau(); /** Creates new form FrmAddNanny1 */ public FrmAddNanny1() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); btnSave = new javax.swing.JButton(); btnReset = new javax.swing.JButton(); btnClose = new javax.swing.JButton(); txtContactNumber = new javax.swing.JTextField(); txtCharge = new javax.swing.JTextField(); txtWorkingHours = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); txtNannyID = new javax.swing.JTextField(); lblNannyID = new javax.swing.JLabel(); lblName = new javax.swing.JLabel(); txtName = new javax.swing.JTextField(); lblBirthDay = new javax.swing.JLabel(); txtAddress = new javax.swing.JTextField(); lblAddress = new javax.swing.JLabel(); txtBirthday = new com.toedter.calendar.JDateChooser(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Add Nanny"); jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); btnSave.setFont(new java.awt.Font("Tahoma", 0, 12)); btnSave.setForeground(new java.awt.Color(0, 0, 204)); btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/save1.png"))); // NOI18N btnSave.setText("Save"); btnSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSaveActionPerformed(evt); } }); btnReset.setFont(new java.awt.Font("Tahoma", 0, 12)); btnReset.setForeground(new java.awt.Color(0, 0, 204)); btnReset.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/reset.png"))); // NOI18N btnReset.setText("Reset"); btnReset.setPreferredSize(new java.awt.Dimension(87, 31)); btnReset.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnResetActionPerformed(evt); } }); btnClose.setFont(new java.awt.Font("Tahoma", 0, 12)); btnClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/close2.png"))); // NOI18N btnClose.setText("Close"); btnClose.setPreferredSize(new java.awt.Dimension(87, 31)); btnClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCloseActionPerformed(evt); } }); txtContactNumber.setForeground(new java.awt.Color(0, 0, 204)); txtCharge.setForeground(new java.awt.Color(0, 0, 204)); txtCharge.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtChargeActionPerformed(evt); } }); txtWorkingHours.setForeground(new java.awt.Color(0, 0, 204)); txtWorkingHours.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtWorkingHoursActionPerformed(evt); } }); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12)); jLabel7.setForeground(new java.awt.Color(0, 0, 204)); jLabel7.setText("Contact Number"); jLabel9.setFont(new java.awt.Font("Tahoma", 0, 12)); jLabel9.setForeground(new java.awt.Color(0, 0, 204)); jLabel9.setText("Charge"); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 12)); jLabel10.setForeground(new java.awt.Color(0, 0, 204)); jLabel10.setText("WorkingHours"); jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); txtNannyID.setForeground(new java.awt.Color(0, 0, 204)); lblNannyID.setFont(new java.awt.Font("Tahoma", 0, 12)); lblNannyID.setForeground(new java.awt.Color(0, 0, 204)); lblNannyID.setText("NannyID"); lblName.setFont(new java.awt.Font("Tahoma", 0, 12)); lblName.setForeground(new java.awt.Color(0, 0, 204)); lblName.setText("Name"); txtName.setForeground(new java.awt.Color(0, 0, 204)); lblBirthDay.setFont(new java.awt.Font("Tahoma", 0, 12)); lblBirthDay.setForeground(new java.awt.Color(0, 0, 204)); lblBirthDay.setText("Birthday"); txtAddress.setForeground(new java.awt.Color(0, 0, 204)); lblAddress.setFont(new java.awt.Font("Tahoma", 0, 12)); lblAddress.setForeground(new java.awt.Color(0, 0, 204)); lblAddress.setText("Address"); txtBirthday.setForeground(new java.awt.Color(0, 0, 204)); txtBirthday.setDateFormatString("MMMM/dd/yyyy"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblName) .addComponent(lblAddress) .addComponent(lblNannyID) .addComponent(lblBirthDay)) .addGap(37, 37, 37) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtBirthday, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(txtName, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtNannyID, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE) .addComponent(txtAddress, javax.swing.GroupLayout.Alignment.LEADING)) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblNannyID) .addComponent(txtNannyID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblName) .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtBirthday, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblBirthDay)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblAddress) .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(26, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(16, 16, 16) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel10) .addGap(51, 51, 51) .addComponent(txtWorkingHours, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel7) .addGap(37, 37, 37) .addComponent(txtContactNumber, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel9) .addGap(89, 89, 89) .addComponent(txtCharge, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(127, Short.MAX_VALUE) .addComponent(btnSave) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnClose, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(118, 118, 118)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(75, 75, 75) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(txtContactNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(txtCharge, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(txtWorkingHours, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(60, 60, 60) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSave) .addComponent(btnReset, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnClose, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(32, Short.MAX_VALUE)) ); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 36)); jLabel1.setForeground(new java.awt.Color(204, 0, 0)); jLabel1.setText("Add Nanny"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(178, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(180, 180, 180)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(32, Short.MAX_VALUE)) ); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-573)/2, (screenSize.height-420)/2, 573, 420); }// </editor-fold>//GEN-END:initComponents private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed if (txtNannyID.getText().equals("")) { JOptionPane.showMessageDialog(this, "Please,Enter NannyNo"); txtNannyID.requestFocus(); return; } if (txtName.getText().equals("")) { JOptionPane.showMessageDialog(this, "Please,Enter FullName"); txtName.requestFocus(); return; } if (txtAddress.getText().equals("")) { JOptionPane.showMessageDialog(this, "Please,Enter Address"); txtAddress.requestFocus(); return; } if (txtContactNumber.getText().equals("")) { JOptionPane.showMessageDialog(this, "Please,Enter Contact Number"); txtContactNumber.requestFocus(); return; } if (txtCharge.getText().equals("")) { JOptionPane.showMessageDialog(this, "Please,Enter Charge"); txtCharge.requestFocus(); return; } if (txtWorkingHours.getText().equals("")) { JOptionPane.showMessageDialog(this, "Please,Enter WorkingHours"); txtWorkingHours.requestFocus(); return; } Date d = new Date(); if (txtBirthday.getDate() != null) { if (txtBirthday.getCalendar().getTime().after(d)) { JOptionPane.showMessageDialog(this, "Birthday Date < today"); txtBirthday.setDate(null); txtBirthday.requestFocus(); return; } } try { conn=connect.getConnection(); String strsql = "insert tblNanny values (?,?,?,?,?,?,?)"; pstmt = conn.prepareStatement(strsql); pstmt.setString(1, txtNannyID.getText()); pstmt.setString(2, txtName.getText()); if (txtBirthday.getDate() == null) { JOptionPane.showMessageDialog(this, "Please,Enter Birthday"); } else { pstmt.setString(3, txtBirthday.getCalendar().getTime().toLocaleString()); } pstmt.setString(4, txtAddress.getText()); pstmt.setString(5, txtContactNumber.getText()); pstmt.setFloat(6,Float.parseFloat(txtCharge.getText())); pstmt.setInt(7, Integer.parseInt(txtWorkingHours.getText())); pstmt.executeUpdate(); JOptionPane.showMessageDialog(this, "Insert successfully!"); this.dispose(); conn.close(); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Error:" + ex.getMessage()+ex.getLocalizedMessage()); return; } }//GEN-LAST:event_btnSaveActionPerformed private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed this.dispose(); }//GEN-LAST:event_btnCloseActionPerformed private void txtChargeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtChargeActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtChargeActionPerformed private void txtWorkingHoursActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtWorkingHoursActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtWorkingHoursActionPerformed private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed // TODO add your handling code here: txtNannyID.setText(""); txtName.setText(""); txtBirthday.setDate(null); txtContactNumber.setText(""); txtCharge.setText(""); txtWorkingHours.setText(""); txtAddress.setText(""); }//GEN-LAST:event_btnResetActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FrmAddNanny1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FrmAddNanny1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FrmAddNanny1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FrmAddNanny1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FrmAddNanny1().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnClose; private javax.swing.JButton btnReset; private javax.swing.JButton btnSave; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JLabel lblAddress; private javax.swing.JLabel lblBirthDay; private javax.swing.JLabel lblName; private javax.swing.JLabel lblNannyID; private javax.swing.JTextField txtAddress; private com.toedter.calendar.JDateChooser txtBirthday; private javax.swing.JTextField txtCharge; private javax.swing.JTextField txtContactNumber; private javax.swing.JTextField txtName; private javax.swing.JTextField txtNannyID; private javax.swing.JTextField txtWorkingHours; // End of variables declaration//GEN-END:variables }
[ "[email protected]@7b50d76b-702c-47d2-0f96-b0069ba6ed1b" ]
[email protected]@7b50d76b-702c-47d2-0f96-b0069ba6ed1b
c6a1afbafef87ac69f7fe0591069b51e43822018
7444ddae69b9b3d96bbaddc94aef083014669fb3
/testng-test/src/main/java/com/jennifer/asserttest/AssertTest2.java
697e9d6d42c16a65c88d083d5d9ad54560b85f3d
[]
no_license
jenniferhuang/jennifer-common-test
e73d2506aa27930cac0cb9e6b23f16376bd64ce5
cd48e1230a68729ed7dd202cf127a7ebef822e35
refs/heads/master
2022-12-05T10:09:00.835219
2019-01-15T11:44:14
2019-01-15T11:44:14
92,487,982
0
0
null
2022-11-16T09:35:23
2017-05-26T08:13:13
Java
UTF-8
Java
false
false
1,275
java
package com.jennifer.asserttest; import org.testng.Assert; import org.testng.TestException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Created by IntelliJ IDEA. * User: com.jennifer.huang * Date: 5/5/2017 */ public class AssertTest2 { @BeforeMethod public void befreMethod(){ System.out.println("before Mehtod"); } @Test public void testOriginalAssert(){ System.out.println("before assert test--Original"); Assert.assertEquals(1, 2); System.out.println("after assert test"); } @Test public void testSoftAssert(){ System.out.println("before assert test--Soft, catch"); softAssert(1, 2); System.out.println("after assert test --No tag as fail"); } private static Boolean softAssert(Object actual, Object expected){ try{ Assert.assertEquals(actual,expected); return true; }catch(Error e){ System.out.println("test fail expected: "+ expected + " Actual: "+actual); return false; } } @AfterMethod public void afterMethod(){ System.out.println("after Mehtod"); } }
a1523d666f19defce90e6ddbc3d7e91cf5adb562
d912456588401fb0b904dff2fff6023c5034562e
/src/main/java/cn/eli486/dto/PageInfo.java
b03806a94b584da83cb5d9b29dbea7af54487a61
[]
no_license
eli719/Crawler-Update
acf923e4f80bd77377809d9c154eb124e9ea8da8
73f950aeaf4e02254578b77d5c4c4c8baf5ef1f0
refs/heads/master
2022-06-22T15:11:55.263837
2020-04-06T05:46:27
2020-04-06T05:46:27
253,387,563
0
0
null
2022-06-17T03:04:01
2020-04-06T03:42:46
Java
UTF-8
Java
false
false
2,341
java
package cn.eli486.dto; import cn.eli486.entity.Customer; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.springframework.core.io.ClassPathResource; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author eli */ public class PageInfo { private static Map<String, Customer> map; private static Map<String, Customer> verifyMap; public static void instance () { map = init ("customer.json"); verifyMap = init ("verifyCustomer.json"); } static Map<String, Customer> init (String filename) { ClassPathResource resource = new ClassPathResource (filename); StringBuilder builder = new StringBuilder (); BufferedReader bufferedReader = null; String s = null; try { InputStreamReader inputStreamReader = new InputStreamReader (resource.getInputStream (), "utf-8"); bufferedReader = new BufferedReader (inputStreamReader); while ((s = bufferedReader.readLine ()) != null) { builder.append (s); } } catch (Exception e) { e.printStackTrace (); } finally { try { if (bufferedReader != null) { bufferedReader.close (); } } catch (IOException e) { e.printStackTrace (); } } JSONObject parse = JSON.parseObject (builder.toString ()); JSONArray customers = parse.getJSONArray ("customers"); String customersStr = customers.toJSONString (); List<Customer> customersList = JSON.parseArray (customersStr, Customer.class); Map<String, Customer> map = new HashMap<> (); for (Customer customer : customersList ) { map.put (customer.getOrgcode (), customer); } return map; } public static Collection<Customer> getMap () { return map.values (); } public static Collection<Customer> getVerifyMap () { return verifyMap.values (); } public static Customer getOne (String orgCode) { return map.get (orgCode); } }
953ee65de73d22432634c59317cfe32d892cddfd
0e8eb8c7a8a93b99f5fd8151573026f2a7d5f2d0
/src/main/java/cn/wsyjlly/mavlink/common/v2/enums/MavMode.java
456cd22e105442dafd3fef22970a51ed17df5fcb
[]
no_license
wsyjlly/mavlink
5c1d98e0abd4ba45df08b4928a25f52e3d5553ea
02f239fb0fcb55fe0795b7db0489294c81510e35
refs/heads/master
2023-01-24T00:43:44.377942
2020-11-26T07:39:03
2020-11-26T07:39:03
310,179,590
5
0
null
null
null
null
UTF-8
Java
false
false
3,299
java
package cn.wsyjlly.mavlink.common.v2.enums; import cn.wsyjlly.mavlink.annotation.MavlinkEnum; import cn.wsyjlly.mavlink.annotation.MavlinkEnumEntry; /********************************** * Author YSW * Description * Date 2020.11.26 - 02:46 * **********************************/ @MavlinkEnum(name = "MAV_MODE") public enum MavMode { /** * System is not ready to fly, booting, calibrating, etc. No flag is set. */ @MavlinkEnumEntry(value = 0,description = "System is not ready to fly, booting, calibrating, etc. No flag is set.") MAV_MODE_PREFLIGHT(), /** * System is allowed to be active, under assisted RC control. */ @MavlinkEnumEntry(value = 80,description = "System is allowed to be active, under assisted RC control.") MAV_MODE_STABILIZE_DISARMED(), /** * System is allowed to be active, under assisted RC control. */ @MavlinkEnumEntry(value = 208,description = "System is allowed to be active, under assisted RC control.") MAV_MODE_STABILIZE_ARMED(), /** * System is allowed to be active, under manual (RC) control, no stabilization */ @MavlinkEnumEntry(value = 64,description = "System is allowed to be active, under manual (RC) control, no stabilization") MAV_MODE_MANUAL_DISARMED(), /** * System is allowed to be active, under manual (RC) control, no stabilization */ @MavlinkEnumEntry(value = 192,description = "System is allowed to be active, under manual (RC) control, no stabilization") MAV_MODE_MANUAL_ARMED(), /** * System is allowed to be active, under autonomous control, manual setpoint */ @MavlinkEnumEntry(value = 88,description = "System is allowed to be active, under autonomous control, manual setpoint") MAV_MODE_GUIDED_DISARMED(), /** * System is allowed to be active, under autonomous control, manual setpoint */ @MavlinkEnumEntry(value = 216,description = "System is allowed to be active, under autonomous control, manual setpoint") MAV_MODE_GUIDED_ARMED(), /** * System is allowed to be active, under autonomous control and navigation (the trajectory is decided onboard and not pre-programmed by waypoints) */ @MavlinkEnumEntry(value = 92,description = "System is allowed to be active, under autonomous control and navigation (the trajectory is decided onboard and not pre-programmed by waypoints)") MAV_MODE_AUTO_DISARMED(), /** * System is allowed to be active, under autonomous control and navigation (the trajectory is decided onboard and not pre-programmed by waypoints) */ @MavlinkEnumEntry(value = 220,description = "System is allowed to be active, under autonomous control and navigation (the trajectory is decided onboard and not pre-programmed by waypoints)") MAV_MODE_AUTO_ARMED(), /** * UNDEFINED mode. This solely depends on the autopilot - use with caution, intended for developers only. */ @MavlinkEnumEntry(value = 66,description = "UNDEFINED mode. This solely depends on the autopilot - use with caution, intended for developers only.") MAV_MODE_TEST_DISARMED(), /** * UNDEFINED mode. This solely depends on the autopilot - use with caution, intended for developers only. */ @MavlinkEnumEntry(value = 194,description = "UNDEFINED mode. This solely depends on the autopilot - use with caution, intended for developers only.") MAV_MODE_TEST_ARMED(), }
88967bf323bb0fd0d7b7f6823353911cff37d7c2
fd83a6e2fc15cf855123187ed718ac66d384dfcb
/src/main/java/Util/orders.java
78df8dec75342536c29196d2552d7f17c92e64c8
[]
no_license
Dzyzy/shoppingMall
83db6409c1984aab7f194083832e5526ac913476
24fd3f92ac6844ccf251b33c8cfb7977d3c57620
refs/heads/master
2023-02-10T00:00:55.441304
2021-01-01T01:41:36
2021-01-01T01:41:36
325,900,902
0
0
null
null
null
null
UTF-8
Java
false
false
1,104
java
package Util; public class orders { private int orders_id; private int orders_total_amount; private int user_id; private int orders_statu; public orders(int orders_id, int orders_total_amount, int user_id, int orders_statu) { this.orders_id = orders_id; this.orders_total_amount = orders_total_amount; this.user_id = user_id; this.orders_statu = orders_statu; } public int getOrders_id() { return orders_id; } public void setOrders_id(int orders_id) { this.orders_id = orders_id; } public int getOrders_total_amount() { return orders_total_amount; } public void setOrders_total_amount(int orders_total_amount) { this.orders_total_amount = orders_total_amount; } public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public int getOrders_statu() { return orders_statu; } public void setOrders_statu(int orders_statu) { this.orders_statu = orders_statu; } }
373a36f682308c7592eca72d1adf186f099e6df4
48e27e86a11db27d2677c1252907858605fa5f1e
/OKWX-android/app/src/main/java/com/okwx/xiao/util/http/Format.java
70906b7222cdf9db1a0f0a0f72efeff84b8018fd
[]
no_license
jangocheng/MonitorWx
f3aa0c2af530996be09af8e361b36613bd29c4e9
52d5573b24ac3cedc78e7ccac04c1f732bda81c4
refs/heads/master
2020-08-23T08:58:19.500213
2019-10-18T01:51:48
2019-10-18T01:51:48
216,582,000
1
0
null
2019-10-21T13:58:38
2019-10-21T13:58:38
null
UTF-8
Java
false
false
942
java
package com.okwx.xiao.util.http; import java.util.List; /*** * json ่งฃๆž็ฑป */ public class Format { private String msg; private Integer code; private List data; public Format(String msg, Integer code, List data) { this.msg = msg; this.code = code; this.data = data; } public Format() { } public String getMsg() { return msg; } public Integer getCode() { return code; } public List getData() { return data; } public void setMsg(String msg) { this.msg = msg; } public void setCode(Integer code) { this.code = code; } public void setData(List data) { this.data = data; } @Override public String toString() { return "Format{" + "msg='" + msg + '\'' + ", code=" + code + ", data=" + data + '}'; } }
2755ba2ca0341bfaf0c18995666f80b301c57d2d
ae1456a6605716a67604bf8866a1caee54105fa2
/modeldesigner/winery.repository.ext/src/main/java/de/ustutt/iaas/bpmn2bpel/planwriter/ManagementTaskTemplateWrapper.java
7fa0ecb81cdd4b8a901665e928e3a9f7d91af7d4
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LicenseRef-scancode-public-domain", "CC-BY-4.0" ]
permissive
open-o/common-tosca-model-designer
aef7630c8a0dbfeb40bbe6651b044e08590cf763
b4fdca321ec4016d6846f3ad2c79c4948a9b2374
refs/heads/master
2021-01-19T11:31:47.383406
2017-04-11T07:43:17
2017-04-11T07:43:17
87,973,145
0
0
null
null
null
null
UTF-8
Java
false
false
4,476
java
/** * Copyright 2016 ZTE Corporation. * * 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 de.ustutt.iaas.bpmn2bpel.planwriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.xml.namespace.QName; import de.ustutt.iaas.bpmn2bpel.model.ManagementTask; import de.ustutt.iaas.bpmn2bpel.model.param.Parameter; import de.ustutt.iaas.bpmn2bpel.model.param.TopologyParameter; /** * Copyright 2015 IAAS University of Stuttgart <br> * <br> * * Add convenience methods to the {@link ManagementTask} that can be used * in the Velocity template. * * @author Sebastian Wagner * */ public class ManagementTaskTemplateWrapper extends ManagementTask { public ManagementTaskTemplateWrapper(ManagementTask task) { super(); setId(task.getId()); setName(task.getName()); setInterfaceName(task.getInterfaceName()); setNodeTemplateId(task.getNodeTemplateId()); setNodeOperation(task.getNodeOperation()); setInputParameters(task.getInputParameters()); setOutputParameters(task.getOutputParameters()); //add by qinlihan setTaskTypeDetail(task.getTaskTypeDetail()); } public List<QName> getInputNodeTemplateIds() { // Velocity does just support java lists in templates but not sets; return new ArrayList<QName>(getNodeTemplateIds(getInputParameters())); } // public List<String> getInputNodeTemplateIdsAsLocalNames() { // // Velocity does just support java lists in templates but not sets; // List<String> localNames = new ArrayList<String>(); // Iterator<QName> iter = getNodeTemplateIds(getInputParameters()).iterator(); // // while (iter.hasNext()) { // localNames.add(iter.next().getLocalPart()); // } // return localNames; // } public List<QName> getOutputNodeTemplateIds() { // Velocity does just support java lists in templates but not sets; return new ArrayList<QName>(getNodeTemplateIds(getOutputParameters())); } // public List<String> getOutputNodeTemplateIdsAsLocalNames() { // // Velocity does just support java lists in templates but not sets; // List<String> localNames = new ArrayList<String>(); // Iterator<QName> iter = getNodeTemplateIds(getOutputParameters()).iterator(); // // while (iter.hasNext()) { // localNames.add(iter.next().getLocalPart()); // } // return localNames; // } // public List<String> getAllNodeTemplateIdsAsQNames() { // List<String> qnamesAsString = new ArrayList<String>(); // Iterator<QName> iter = getAllNodeTemplateIds().iterator(); // // while (iter.hasNext()) { // qnamesAsString.add(iter.next().toString()); // } // return qnamesAsString; // // } // public List<String> getAllNodeTemplateIdsAsLocalNames() { // List<String> localNames = new ArrayList<String>(); // Iterator<QName> iter = getAllNodeTemplateIds().iterator(); // // while (iter.hasNext()) { // localNames.add(iter.next().getLocalPart()); // } // return localNames; // // } /** * @return The set union of all ids of node templates used by the task. */ public List<QName> getAllNodeTemplateIds() { Set<QName> allNodeTemplates = getNodeTemplateIds(getInputParameters()); allNodeTemplates.addAll(getNodeTemplateIds(getOutputParameters())); return new ArrayList<QName>(allNodeTemplates); } /** * Helper that returns a set of ids of the node templates used by the parameters. * @param parameters * @return Set of node template ids as QNames */ private Set<QName> getNodeTemplateIds(List<Parameter> parameters) { Set<QName> nodeTemplateIds = new HashSet<QName>(); Iterator<Parameter> iter = parameters.iterator(); while (iter.hasNext()) { Parameter parameter = (Parameter) iter.next(); /* Just topology parameter refer to node templates */ if (parameter instanceof TopologyParameter) { nodeTemplateIds.add(((TopologyParameter) parameter).getNodeTemplateId()); } } return nodeTemplateIds; } }
f87ae1233c3c07833be9691bd69a0651024a96c6
52571bbc269a804c7df8f7b27ae3c41ee84f84f2
/cache/src/main/java/codexe/han/cache/masterslave/jedis/exceptions/JedisMovedDataException.java
a9b525d908e924b847c08874b527947fb94dd7b9
[]
no_license
codexehan/java-related
8b684b18b2402983cfd0ab6e44a860b8c014f0e7
a023a4f3e87a6558925af49f35de2f39bb0c1194
refs/heads/master
2020-05-07T06:02:43.118869
2019-12-30T10:40:55
2019-12-30T10:40:55
180,296,971
0
0
null
null
null
null
UTF-8
Java
false
false
713
java
package codexe.han.cache.masterslave.jedis.exceptions; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.exceptions.JedisRedirectionException; public class JedisMovedDataException extends JedisRedirectionException { private static final long serialVersionUID = 3878126572474819403L; public JedisMovedDataException(String message, HostAndPort targetNode, int slot) { super(message, targetNode, slot); } public JedisMovedDataException(Throwable cause, HostAndPort targetNode, int slot) { super(cause, targetNode, slot); } public JedisMovedDataException(String message, Throwable cause, HostAndPort targetNode, int slot) { super(message, cause, targetNode, slot); } }
6574ee8e60507a3ace7fc8ae3244d477f6dfd51b
893bdc59bb8ff233ad4567182a04ff23a4ee13ae
/maven/mybatis1/src/main/java/com/rueggerllc/dao/BaseDao.java
d865165fcab8bc22c87eb16a50b3a3395ed61ed9
[]
no_license
rueggerc/rueggerllc-public
33f5396f04a423a62f6c7e7124fa02c8f455c2c8
a86950de18c1d5ec23aaf1051268f297b4bc4f78
refs/heads/master
2021-01-13T14:38:17.480642
2017-10-10T22:14:30
2017-10-10T22:14:30
76,731,748
0
0
null
null
null
null
UTF-8
Java
false
false
426
java
package com.rueggerllc.dao; import java.util.List; import com.rueggerllc.mappers.Mapper; public interface BaseDao<M extends Mapper<D>, D> { public List<D> selectAll() throws Exception; public D selectById(long id) throws Exception; public void insert(D domainObject) throws Exception; public void update(D domainObject) throws Exception; public void delete(long id) throws Exception; }
2d9a7273f66620163c693df29b2927004b518c4c
c503c822725e5752935bd942ec702470585c821d
/src/com/zhima/traffic/ui/epd/EpdDriverUi.java
45da13658def8519b6610b9a8330c1b92b12b3b0
[]
no_license
3356317015/traffic
73d17d8ec8d02c86d78a36c959c34cf708bf2d80
2bf2d7182fb202e2dc3ed28d818365c9a1bbf05e
refs/heads/master
2020-03-28T03:23:59.790720
2018-09-06T14:00:41
2018-09-06T14:00:41
147,642,313
0
0
null
null
null
null
UTF-8
Java
false
false
10,118
java
/** ******************************************************************************* * * (c) Copyright 2012 ้‡ๅบ†ๅธ‚ๅฟ—็Ž›ไฟกๆฏๆŠ€ๆœฏๆœ‰้™ๅ…ฌๅธ * * ็ณป็ปŸๅ็งฐ๏ผšframeWork * ๆ–‡ ไปถ ๅ ๏ผšSamModuleUi.java * ๆจกๅ—ๅ็งฐ๏ผš(่ฏทๆ›ดๆ”นๆˆ่ฏฅๆจกๅ—ๅ็งฐ) * ๅˆ› ๅปบ ไบบ ๏ผš้ฒๆ‰ฟๆฏ… * ๅˆ›ๅปบๆ—ฅๆœŸ๏ผš2013-3-2 ไธ‹ๅˆ10:36:15 * ไฟฎ ๆ”น ไบบ ๏ผš(ไฟฎๆ”นไบ†่ฏฅๆ–‡ไปถ๏ผŒ่ฏทๅกซไธŠไฟฎๆ”นไบบ็š„ๅๅญ—) * ไฟฎๆ”นๆ—ฅๆœŸ๏ผš(่ฏทๅกซไธŠไฟฎๆ”น่ฏฅๆ–‡ไปถๆ—ถ็š„ๆ—ฅๆœŸ) * ็‰ˆ ๆœฌ ๏ผš V1.0.0 ******************************************************************************* */ package com.zhima.traffic.ui.epd; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Composite; import com.zhima.basic.CallMethod; import com.zhima.basic.CommFinal; import com.zhima.basic.exception.UserBusinessException; import com.zhima.frame.model.SamModuleRight; import com.zhima.frame.model.SamParameter; import com.zhima.traffic.action.epd.IEpdDriver; import com.zhima.traffic.action.epd.IEpdDriverinfo; import com.zhima.traffic.action.epd.impl.ImpEpdDriver; import com.zhima.traffic.action.epd.impl.ImpEpdDriverinfo; import com.zhima.traffic.comm.TraffFinal; import com.zhima.traffic.comm.TraffParam; import com.zhima.traffic.model.EpdDriver; import com.zhima.traffic.model.EpdDriverinfo; import com.zhima.util.DateUtils; import com.zhima.util.SWTResourceManager; import com.zhima.util.log4j.LogUtil; import com.zhima.widget.BasicPanel; import com.zhima.widget.MsgBox; import com.zhima.widget.ThreadWaiting; import com.zhima.widget.grid.GridColumn; import com.zhima.widget.grid.GridConfig; import com.zhima.widget.grid.GridView; /** * EpdCarUiๆฆ‚่ฆ่ฏดๆ˜Ž๏ผš้ฉพ้ฉถๅ‘˜่ฎพ็ฝฎ * @author lcy */ public class EpdDriverUi extends Composite { private Object obj; private BasicPanel panel; //ๅŠŸ่ƒฝๆƒ้™ private List<SamModuleRight> rights; //ๆƒ้™ private GridView gridView; //ๆŸฅ่ฏข็›ธๅ…ณ private String fIdNumber = ""; private String fDriver = ""; private String fCompany = ""; private String fStatus = ""; /** * * ๆž„้€ ๅ‡ฝๆ•ฐ: ้ฉพ้ฉถๅ‘˜ๆกฃๆกˆ * @param parent * @param style * @param list ๅŠŸ่ƒฝๆŒ‰้’ฎๆƒ้™ */ @SuppressWarnings({ "rawtypes", "unchecked" }) public EpdDriverUi(Composite parent, int style, List list) { super(parent, style); this.setLayout(new FormLayout()); this.obj = this; this.rights=list; panel = new BasicPanel(this, SWT.BORDER); panel.setInput(false); panel.createPanel(); FormData data = new FormData(); data.top = new FormAttachment(0); data.left = new FormAttachment(0); data.right = new FormAttachment(100); data.bottom = new FormAttachment(100); panel.setLayoutData(data); createToolbar(); createDetail(); } /** * createToolbarๆ–นๆณ•ๆ่ฟฐ๏ผšๆž„ๅปบๅทฅๅ…ท้ขๆฟๆŒ‰้’ฎ * ๅˆ› ๅปบ ไบบ ๏ผš้ฒๆ‰ฟๆฏ… * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2013-6-22 ไธŠๅˆ08:37:54 * ไฟฎ ๆ”น ไบบ ๏ผš(ไฟฎๆ”นไบ†่ฏฅๆ–นๆณ•๏ผŒ่ฏทๅกซไธŠไฟฎๆ”นไบบ็š„ๅง“ๅ) * ไฟฎๆ”นๆ—ถ้—ด๏ผš(่ฏทๅกซไธŠไฟฎๆ”นๆ—ถ้—ด) void */ private void createToolbar(){ panel.toolbar.setLayout(new RowLayout()); CallMethod callMethod = new CallMethod(); callMethod.createBtnRight(obj, panel.toolbar, rights); } /** * createDetailๆ–นๆณ•ๆ่ฟฐ๏ผšๆž„ๅปบ็ป†้ƒจ้ขๆฟ่กจๆ ผ * ๅˆ› ๅปบ ไบบ ๏ผš้ฒๆ‰ฟๆฏ… * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2013-6-22 ไธŠๅˆ08:38:25 * ไฟฎ ๆ”น ไบบ ๏ผš(ไฟฎๆ”นไบ†่ฏฅๆ–นๆณ•๏ผŒ่ฏทๅกซไธŠไฟฎๆ”นไบบ็š„ๅง“ๅ) * ไฟฎๆ”นๆ—ถ้—ด๏ผš(่ฏทๅกซไธŠไฟฎๆ”นๆ—ถ้—ด) void */ private void createDetail(){ panel.detail.setLayout(new FormLayout()); List<GridColumn> columns=new ArrayList<GridColumn>(); columns.add(new GridColumn("้ฉพ้ฉถๅ‘˜ๅง“ๅ","driverName",100)); columns.add(new GridColumn("ๆ€งๅˆซ","sex",TraffFinal.ARR_SEX,80)); columns.add(new GridColumn("่บซไปฝ่ฏ","idNumber",200)); columns.add(new GridColumn("้ฉพ็…ง็ฑปๅž‹","drivingType",100)); columns.add(new GridColumn("้ฉพ็…งๆœ‰ๆ•ˆๆœŸ","drivingValid",100)); columns.add(new GridColumn("ไปŽไธš่ต„ๆ ผ่ฏ","permitNumber",200)); columns.add(new GridColumn("่ต„ๆ ผ่ฏๆœ‰ๆ•ˆๆœŸ","permitValid",120)); columns.add(new GridColumn("่”็ณป็”ต่ฏ","telephone",120)); columns.add(new GridColumn("ๅ…ฌๅธๅ็งฐ","driverCompanyname",300)); columns.add(new GridColumn("็Šถๆ€","driverStatus",TraffFinal.ARR_DRIVER_STATUS,100)); columns.add(new GridColumn("ๅค‡ๆณจ","remark",300)); GridConfig gridConfig = new GridConfig(); gridConfig.setCheck(false); gridConfig.setColumns(columns); gridConfig.setRightBos(rights); gridConfig.setObj(obj); gridView = new GridView(panel.detail, SWT.NONE); gridView.CreateTabel(gridConfig); gridView.bindMouseDoubleClick(obj,rights,"updateMethod"); gridView.bindRefresh(obj, "queryDriver"); FormData data = new FormData(); data.top = new FormAttachment(0); data.left = new FormAttachment(0); data.bottom = new FormAttachment(100); data.right = new FormAttachment(100); gridView.setLayoutData(data); } /** * queryMethodๆ–นๆณ•ๆ่ฟฐ๏ผšๆŸฅ่ฏขๆ–นๆณ• * ๅˆ› ๅปบ ไบบ ๏ผš้ฒๆ‰ฟๆฏ… * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2013-6-22 ไธŠๅˆ08:38:47 * ไฟฎ ๆ”น ไบบ ๏ผš(ไฟฎๆ”นไบ†่ฏฅๆ–นๆณ•๏ผŒ่ฏทๅกซไธŠไฟฎๆ”นไบบ็š„ๅง“ๅ) * ไฟฎๆ”นๆ—ถ้—ด๏ผš(่ฏทๅกซไธŠไฟฎๆ”นๆ—ถ้—ด) void */ public void queryMethod(){ EpdDriverFindUi findUi = new EpdDriverFindUi(this.getShell()); findUi.setfIdNumber(fIdNumber); findUi.setfDriver(fDriver); findUi.setfCompany(fCompany); findUi.setfStatus(fStatus); findUi.open(); if (findUi.getBtnId()==1){ fIdNumber = findUi.getfIdNumber(); fDriver = findUi.getfDriver(); fCompany = findUi.getfCompany(); fStatus = findUi.getfStatus(); ThreadWaiting waiting = new ThreadWaiting(this,"queryDriver",new Class[]{},new String[]{}); waiting.task(); } } public void queryDriver(){ try { for (int i = 0; i < rights.size(); i++) { if (rights.get(i).getRightMethod().equals("queryMethod")){ int start = gridView.getStart(); int limit = gridView.getLimit(); IEpdDriver iEpdDriver = new ImpEpdDriver(); int count = iEpdDriver.queryCountByCustom(CommFinal.organize.getOrganizeSeq(), fIdNumber,fDriver, fCompany, fStatus); if (count>0){ gridView.removeAll(); List<EpdDriver> epdDrivers = iEpdDriver.queryPageByCustom(CommFinal.organize.getOrganizeSeq(), fIdNumber,fDriver, fCompany, fStatus, start, limit); gridView.setDataList(epdDrivers); IEpdDriverinfo iEpdDriverinfo = new ImpEpdDriverinfo(); SamParameter parameter = CommFinal.getParamValue(TraffParam.WarningDriverDays); String currDate = DateUtils.getNow(DateUtils.FORMAT_SHORT); for (int j = 0; j < epdDrivers.size(); j++) { if (DateUtils.nDaysBetweenTwoDate(currDate,epdDrivers.get(j).getDrivingValid())<0){ gridView.setRowFontColor(j, SWTResourceManager.getColor(SWT.COLOR_RED)); continue; }else if(DateUtils.nDaysBetweenTwoDate(currDate,epdDrivers.get(j).getDrivingValid()) <=Integer.valueOf(parameter.getParameterValue())){ gridView.setRowFontColor(j, SWTResourceManager.getColor(SWT.COLOR_BLUE)); } if (DateUtils.nDaysBetweenTwoDate(currDate,epdDrivers.get(j).getPermitValid())<0){ gridView.setRowFontColor(j, SWTResourceManager.getColor(SWT.COLOR_RED)); continue; }else if(DateUtils.nDaysBetweenTwoDate(currDate,epdDrivers.get(j).getPermitValid()) <=Integer.valueOf(parameter.getParameterValue())){ gridView.setRowFontColor(j, SWTResourceManager.getColor(SWT.COLOR_BLUE)); } List<EpdDriverinfo> driverinfos = iEpdDriverinfo.queryByDriverSeq(epdDrivers.get(j).getDriverSeq()); if(null != driverinfos && driverinfos.size()>0){ for (int k = 0; k < driverinfos.size(); k++) { if (DateUtils.nDaysBetweenTwoDate(currDate,driverinfos.get(k).getEndDate())<0){ gridView.setRowFontColor(j, SWTResourceManager.getColor(SWT.COLOR_RED)); break; }else if(DateUtils.nDaysBetweenTwoDate(currDate,driverinfos.get(k).getEndDate()) <=Integer.valueOf(parameter.getParameterValue())){ gridView.setRowFontColor(j, SWTResourceManager.getColor(SWT.COLOR_BLUE)); } } } } }else{ gridView.removeAll(); } gridView.setTotalCount(count); } } } catch (UserBusinessException e) { LogUtil.operLog(e,"E",true,true); } catch (Exception e) { LogUtil.operLog(e,"E",true,true); } } public void addMethod(){ EpdDriverEditUi editUi = new EpdDriverEditUi(this.getShell(),gridView,CommFinal.OPER_TYPE_ADD); editUi.open(); } public void updateMethod(){ String thisMethodName = new Exception().getStackTrace()[0].getMethodName();// ่Žทๅพ—ๅฝ“ๅ‰็š„ๆ–นๆณ•ๅ for (int i = 0; i < rights.size(); i++) { if (thisMethodName.equals(rights.get(i).getRightMethod())){ if(null!=gridView.getSelection()){ EpdDriverEditUi editUi = new EpdDriverEditUi(this.getShell(), gridView, CommFinal.OPER_TYPE_UPDATE); editUi.open(); }else{ MsgBox.warning(getShell(), "่ฏท้€‰ๆ‹ฉไฟฎๆ”น็š„้กนใ€‚"); } break; } } } @SuppressWarnings("unchecked") public void deleteMethod(){ try { int checkIndex[] = gridView.getSelectionIndexs(); if (checkIndex.length>0){ int isdel = MsgBox.confirm(getShell(),"็กฎๅฎš่ฆๅˆ ้™ค้€‰ไธญ่กŒๆ•ฐๆฎๅ—๏ผŸ"); if(isdel == SWT.YES){ IEpdDriver iEpdDriver = new ImpEpdDriver(); iEpdDriver.delete((List<EpdDriver>) gridView.getSelections(),CommFinal.initConfig()); gridView.deleteRow(checkIndex); } } }catch (Exception e) { LogUtil.operLog(e,"E",true,true); } } public void outputMethod() throws UserBusinessException{ gridView.exportExcel(); } }
4028c442a3060c94cc26c46f7e81d05edb0e5f87
f48a51e7c72db5de1a2a0ac61ebbc6e95caf9a7c
/app/src/main/java/com/example/sofra/ui/generalViewModel/CityViewModel.java
f0f02471ac488f47555768a01c66cae89c058df2
[ "MIT" ]
permissive
traviraj90/Sofra
077f0666ac67f3749a3d1aa7d1822e5630f565ea
996eb6021542bfdecff817869f77a3026140042d
refs/heads/master
2023-02-06T17:50:38.965959
2020-12-22T02:00:54
2020-12-22T02:00:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,290
java
package com.example.sofra.ui.generalViewModel; import androidx.annotation.NonNull; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.example.sofra.data.pojo.general.city.City; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static com.example.sofra.data.api.RetrofitClient.getClient; public class CityViewModel extends ViewModel { private static final String TAG = CityViewModel.class.getName(); public MutableLiveData<City> cityMutableLiveData = new MutableLiveData<>(); public void getCity() { getClient().getCity().enqueue(new Callback<City>() { @Override public void onResponse(@NonNull Call<City> call, @NonNull Response<City> response) { try { assert response.body() != null; if (response.body().getStatus() == 1) { cityMutableLiveData.setValue(response.body()); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(@NonNull Call<City> call, @NonNull Throwable t) { t.printStackTrace(); } }); } }
f049ed74d5d890152eaef3791bfe635f29c9566a
0a02f2a262d517ff4e10005a13bbd5a852a45cc9
/app/src/main/java/com/mxx/myimmatationdemo/di/module/MainPagerFragmentModule.java
7b5a2282c4545434a53664af6c633ccdedaeca91
[]
no_license
MxxGitHub666/MyImmatationDemo
5301d0ca8af09f1d6c22c9f22db07f76d9992ebf
1cf5be43562dd12c5f30cd713efa07b7ce422d80
refs/heads/master
2020-07-06T00:09:53.672391
2019-11-02T10:12:54
2019-11-02T10:13:12
202,700,884
0
0
null
null
null
null
UTF-8
Java
false
false
117
java
package com.mxx.myimmatationdemo.di.module; import dagger.Module; @Module public class MainPagerFragmentModule { }
4a444d1b18a8cc73c1b5c1209a1f5c6478593a51
db37e81aedf8d13af2af10ef315f1acb65ad15a4
/src/com/nari/slsd/gglck/entity/AisLocation.java
a0a9a1a771f486b9f84d6a2c2924312526533d7a
[]
no_license
acyh58976142/ShipLockTest
c4bf1c05c100b650921401b35a10c7cd4c9f999a
4f75602d80f2e47bbaa41e7d4725727bc5e699cf
refs/heads/master
2020-04-29T15:44:12.373759
2019-03-18T08:53:11
2019-03-18T08:53:11
176,238,262
0
0
null
null
null
null
UTF-8
Java
false
false
1,307
java
package com.nari.slsd.gglck.entity; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * ais ่ˆน่ˆถไฝ็ฝฎ * @author zsq */ public class AisLocation { private String mmsi; //mmsi private String vesselName; //่ˆนๅ private String longitude; //็ปๅบฆ private String latitude; //็บฌๅบฆ private String aistime; //ๆŠฅๆ–‡้‡Œ็š„ๆ—ถ้—ด private String inRange; //ๆ˜ฏไธๆ˜ฏๅœจๆœ‰ๆ•ˆๅŒบๅŸŸๅ†…(0-ไธๅœจ,1-ๅœจ,2-ไธ่ƒฝๅŒบๅˆ†) public AisLocation() { super(); } public String getMmsi() { return mmsi; } public void setMmsi(String mmsi) { this.mmsi = mmsi; } public String getVesselName() { return vesselName; } public void setVesselName(String vesselName) { this.vesselName = vesselName; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getAistime() { return aistime; } public void setAistime(String aistime) { this.aistime = aistime; } public String getInRange() { return inRange; } public void setInRange(String inRange) { this.inRange = inRange; } }
05b6a6c8ae8bba77d203343d17bf492783ada1e1
c36327d3d117eb154388104b555ca4570430c546
/src/net/sf/openrocket/example/PowerLawWindConfigurator.java
05b86ddab0ec972f513ab88d98c9acac34d82968
[ "MIT" ]
permissive
wasa-rockoon/PowerLawWind
be6ae54f36333aab5b39ab7b2abc5382c148db5f
418077af8fc1fac4f4feb63c5f2d1d4539be1bef
refs/heads/master
2023-06-28T23:55:54.914247
2021-07-27T14:55:27
2021-07-27T14:55:27
390,009,566
1
0
null
null
null
null
UTF-8
Java
false
false
2,362
java
package net.sf.openrocket.example; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import net.sf.openrocket.document.Simulation; import net.sf.openrocket.gui.SpinnerEditor; import net.sf.openrocket.gui.adaptors.DoubleModel; import net.sf.openrocket.gui.components.BasicSlider; import net.sf.openrocket.gui.components.UnitSelector; import net.sf.openrocket.plugin.Plugin; import net.sf.openrocket.simulation.extension.AbstractSwingSimulationExtensionConfigurator; import net.sf.openrocket.unit.UnitGroup; /** * The Swing configuration dialog for the extension. * * The abstract implementation provides a ready JPanel using MigLayout * to which you can build the dialog. */ @Plugin public class PowerLawWindConfigurator extends AbstractSwingSimulationExtensionConfigurator<PowerLawWind> { public PowerLawWindConfigurator() { super(PowerLawWind.class); } @Override protected JComponent getConfigurationComponent(PowerLawWind extension, Simulation simulation, JPanel panel) { // Reference altitude panel.add(new JLabel("Reference altitude:")); DoubleModel refAltModel = new DoubleModel(extension, "RefAlt", UnitGroup.UNITS_DISTANCE, 1.0); JSpinner refAltSpin = new JSpinner(refAltModel.getSpinnerModel()); refAltSpin.setEditor(new SpinnerEditor(refAltSpin)); panel.add(refAltSpin, "w 75lp!"); UnitSelector refAltUnit = new UnitSelector(refAltModel); panel.add(refAltUnit, "w 25"); BasicSlider refAltSlider = new BasicSlider(refAltModel.getSliderModel(0.1, 10.0)); panel.add(refAltSlider, "w 75lp, wrap"); // Surface coefficient panel.add(new JLabel("Surface coefficient:")); DoubleModel surfaceCModel = new DoubleModel(extension, "SurfaceC", UnitGroup.UNITS_COEFFICIENT, 1.0); JSpinner surfaceCSpin = new JSpinner(surfaceCModel.getSpinnerModel()); surfaceCSpin.setEditor(new SpinnerEditor(surfaceCSpin)); panel.add(surfaceCSpin, "w 75lp!"); BasicSlider surfaceCSlider = new BasicSlider(surfaceCModel.getSliderModel(0.1, 10.0)); panel.add(surfaceCSlider, "w 75lp, wrap"); return panel; } }
1125e886418e2547bb9012376bfee3b5796f9828
16f896534b6d1a0c195d44c656f0655df99e56c7
/src/test/java/com/localgrower/ArchTest.java
27af2db7075540af8b90ed3aa13b149e66cd4fba
[]
no_license
alexvoinea05/Licenta2k21
ab3e1bcfba77bc21da73037701ccb73de4f21967
bdfb4fb08df7bd66049ee65927e64f0fcb0291c5
refs/heads/main
2023-06-05T03:40:13.496166
2021-06-29T18:05:37
2021-06-29T18:05:37
374,117,180
0
0
null
null
null
null
UTF-8
Java
false
false
1,012
java
package com.localgrower; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.importer.ClassFileImporter; import com.tngtech.archunit.core.importer.ImportOption; import org.junit.jupiter.api.Test; class ArchTest { @Test void servicesAndRepositoriesShouldNotDependOnWebLayer() { JavaClasses importedClasses = new ClassFileImporter() .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS) .importPackages("com.localgrower"); noClasses() .that() .resideInAnyPackage("com.localgrower.service..") .or() .resideInAnyPackage("com.localgrower.repository..") .should() .dependOnClassesThat() .resideInAnyPackage("..com.localgrower.web..") .because("Services and repositories should not depend on web layer") .check(importedClasses); } }
1865e6ef5d43c4cfe45c9c901557c8c1f257abc2
72a1cc17f54cb88320778f02da4c5632445edaa3
/006_Dynamic_Proxy_Spring_AOP/src/Proxy/src/com/bjsxt/proxy/test/UserMgr.java
2358496ab99d7789eecbf0224c2939c3d1ea2c20
[]
no_license
XiongJobs/Jworkbench
10d42f7ce26e7bdd6fdfb5095e94a22727c8d345
ed0aac32fec5673078c0ac60901d3323993a7459
refs/heads/master
2021-07-19T01:06:50.926131
2018-07-09T01:15:00
2018-07-09T01:15:00
135,654,158
0
0
null
null
null
null
UTF-8
Java
false
false
77
java
package com.bjsxt.proxy.test; public interface UserMgr { void addUser(); }
d4367d8fb1313336f1220df80b4b73585acf4a7a
63f0e5f7870d9914c1ed85af8e4889696b458700
/QuestionAnswerAPI/src/main/java/com/example/QuestionAnswerAPI/QuestionAnswerAPI/entity/CommentList.java
0b0a33002752269a692075d6c9ed8fb97444aa3e
[]
no_license
ravitripathi/internalQuora
073b32b32618679e52c9eb1f55de98d35dea03c1
c99e8de94a862e9314b27533b4a16144142ed799
refs/heads/master
2021-03-19T06:26:58.706696
2018-02-08T09:03:33
2018-02-08T09:03:33
120,611,178
1
0
null
null
null
null
UTF-8
Java
false
false
1,088
java
package com.example.QuestionAnswerAPI.QuestionAnswerAPI.entity; import com.example.QuestionAnswerAPI.QuestionAnswerAPI.dto.CommentDTO; import com.example.QuestionAnswerAPI.QuestionAnswerAPI.dto.CommentListDTO; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.util.List; @Document(collection = CommentList.COLLECTION_NAME) public class CommentList { public static final String COLLECTION_NAME = "comment"; @Id private String commentListId; //id will be same as answer id private List<CommentDTO> commentDTOList; public static String getCollectionName() { return COLLECTION_NAME; } public String getCommentListId() { return commentListId; } public void setCommentListId(String commentListId) { this.commentListId = commentListId; } public List<CommentDTO> getCommentDTOList() { return commentDTOList; } public void setCommentDTOList(List<CommentDTO> commentDTOList) { this.commentDTOList = commentDTOList; } }
7146ff22910128d0289fd84e5d57ef245fef9ff4
ef93b64a6b27e30ff7536d10d4ba7123f94595c0
/src/test/java/com/googlecode/hibernate/memcached/integration/ContactIntegrationTest.java
92195f8ab601b269ccec62924ed695a42516cb6d
[ "Apache-2.0" ]
permissive
ddlatham/hibernate-memcached
c64b6a7554682e6ebfda83572c745cc3a7ccee44
4847a7d87f5bee43535f9b8d0235a3e1a6cb4d5d
refs/heads/master
2021-01-16T13:34:34.810968
2010-02-26T21:34:17
2010-02-26T21:34:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,474
java
package com.googlecode.hibernate.memcached.integration; import org.hibernate.Criteria; import static org.hibernate.criterion.Restrictions.eq; import java.util.Calendar; import java.util.Date; import java.util.Properties; public class ContactIntegrationTest extends AbstractHibernateTestCase { Contact ray; @Override protected void setupInTransaction() { ray = new Contact(); ray.setFirstName("Ray"); ray.setLastName("Krueger"); ray.setBirthday(new Date()); session.saveOrUpdate(ray); session.flush(); session.clear(); } @Override protected Properties getConfigProperties() { Properties props = new Properties(); props.setProperty("hibernate.cache.use_query_cache", "true"); return props; } public void test() { Contact fromDB = (Contact) session.get(Contact.class, ray.getId()); assertNotNull(fromDB); } public void test_query_cache() { Criteria criteria = session.createCriteria(Contact.class) .add(eq("firstName", "Ray")) .add(eq("lastName", "Krueger")) .setCacheable(true) .setCacheRegion("contact.findByFirstNameAndLastName"); assertNotNull(criteria.uniqueResult()); criteria.uniqueResult(); criteria.uniqueResult(); criteria.uniqueResult(); criteria.uniqueResult(); assertEquals(criteria.uniqueResult(), criteria.uniqueResult()); } public void test_query_cache_with_date() throws Exception { Thread.sleep(100); Calendar birthday = Calendar.getInstance(); birthday.set(Calendar.HOUR_OF_DAY, 0); birthday.set(Calendar.MINUTE, 0); birthday.set(Calendar.SECOND, 0); birthday.set(Calendar.MILLISECOND, 0); Criteria criteria = session.createCriteria(Contact.class) .add(eq("firstName", "Ray")) .add(eq("lastName", "Krueger")) .add(eq("birthday", birthday.getTime())) .setCacheable(true) .setCacheRegion("contact.findByFirstNameAndLastNameAndBirthday"); assertNotNull(criteria.uniqueResult()); criteria.uniqueResult(); criteria.uniqueResult(); criteria.uniqueResult(); assertEquals(criteria.uniqueResult(), criteria.uniqueResult()); } }
a32d758080adcc8bc1c3f78a9f517d5001601ea2
d5e0ec705a0c4d0b70eacf3b3d747b9267e11f3e
/src/main/java/DesignPatterns/Creational/Animal.java
b684251a69bcafd6ad9dfd4d60cef764d2bec774
[]
no_license
Karinagiselle/Fundamentals
e146f5ed4b3528386a02b60c1871877ac86f5a2e
c93c9f4ea72ef1942937dbd73d8920c304f5b76f
refs/heads/master
2021-08-30T03:19:54.055921
2017-12-15T21:17:00
2017-12-15T21:17:00
110,279,737
0
0
null
null
null
null
UTF-8
Java
false
false
307
java
package DesignPatterns.Creational; public enum Animal { DOG("Dog", new Dog()), CAT("Cat", new Cat()); private String name; private Pet pet; Animal(String name, Pet pet) { this.name = name; this.pet = pet; } public Pet getPet() { return pet; } }
19798c27e75fa5cdfe3ddfc046a03d488e154d91
8dfde33cb2a30e4d4d4c98f560a9fe856d245e06
/NotableCommonsLib/notable-commons-lib/src/main/java/nlusersi324201edwinvanrooij/fhict/httpathena/libraryproject/adapteritems/AdapterItemFeedback.java
367a2cd9d872e5e38360ab37a0a37937934b1040
[]
no_license
EdwinVanRooij/notable
be43e4869915c65116baaf2d99bb8da9a4e12e46
009f446740ded1eaa7af7af320ceb99a510f37bb
refs/heads/master
2021-03-27T18:54:30.680057
2016-06-12T00:07:07
2016-06-12T00:07:07
56,100,269
0
0
null
null
null
null
UTF-8
Java
false
false
2,241
java
package nlusersi324201edwinvanrooij.fhict.httpathena.libraryproject.adapteritems; //import nlusersi324201edwinvanrooij.fhict.httpathena.libraryproject.R; // //import com.mikepenz.fastadapter.items.AbstractItem; /** * Created by Edwin on 11/16/2015. */ public class AdapterItemFeedback { // public class AdapterItemFeedback extends AbstractItem<AdapterItemFeedback, AdapterItemFeedback.ViewHolder> { // private FeedbackItem item; // private Context c; // // public AdapterItemFeedback(FeedbackItem item, Context c) { // this.item = item; // this.c = c; // } // // public FeedbackItem getAccount(){ // return item; // } // // //The unique ID for this type of item // @Override // public int getType() { // return R.id.item_feedback_root_id; // } // // //The layout to be used for this type of item // @Override // public int getLayoutRes() { // return R.layout.item_feedback; // } // // //The logic to bind your data to the view // @Override // public void bindView(RecyclerView.ViewHolder holder) { // Context ctx = holder.itemView.getContext(); // //get our viewHolder // ViewHolder viewHolder = (ViewHolder) holder; // // //set the text for the name // viewHolder.tvUsername.setText(item.getAccountId()); // viewHolder.tvDescription.setText(item.getDescription()); // viewHolder.tvFeedbackType.setText(item.getType().toString()); // viewHolder.tvDate.setText("dummy"); // } // // /** // * our ViewHolder // */ // protected static class ViewHolder extends RecyclerView.ViewHolder { // protected View view; // TextView tvUsername; // TextView tvDescription; // TextView tvFeedbackType; // TextView tvDate; // // public ViewHolder(View view) { // super(view); // this.view = view; // // tvUsername = (TextView) view.findViewById(R.id.tvUsername); // tvDescription = (TextView) view.findViewById(R.id.tvDescription); // tvFeedbackType = (TextView) view.findViewById(R.id.tvFeedbackType); // tvDate = (TextView) view.findViewById(R.id.tvDate); // } // } }
89c2f2818cfa554498364e1cc7a250dfbc6aa6b2
ac4412c5666664670c36fccc95c2323499a4ab6c
/appEmprestimoFacil/src/main/java/br/edu/infnet/emprestimo/service/ParcelaService.java
bdd7a52172de33befed4c111ee00fd9a1762e8c1
[ "Apache-2.0" ]
permissive
pauloricmarinho/infnet-05-java-injecao-dependencia-persistencia-projeto
35ad355163d28079db70284145de7b137fe3c3f0
67fc3231fb92549439ef57334c2519d35438dd52
refs/heads/master
2022-11-21T02:11:03.321551
2020-07-26T23:16:30
2020-07-26T23:16:30
275,684,691
0
0
Apache-2.0
2020-07-26T23:16:32
2020-06-28T23:16:08
Java
UTF-8
Java
false
false
2,647
java
package br.edu.infnet.emprestimo.service; import java.util.Calendar; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.edu.infnet.emprestimo.model.Cliente; import br.edu.infnet.emprestimo.model.Investidor; import br.edu.infnet.emprestimo.model.Parcela; import br.edu.infnet.emprestimo.repository.ClienteRepository; import br.edu.infnet.emprestimo.repository.InvestidorRepository; import br.edu.infnet.emprestimo.repository.ParcelaRepository; @Service public class ParcelaService { private @Autowired ParcelaRepository repo; private @Autowired ClienteRepository repositoryCliente; private @Autowired InvestidorRepository respositoryInvestidor; public void salvar(List<Parcela> parcelas) { for (Parcela parcela : parcelas) { repo.save(parcela); } } public Parcela salvar(Parcela parcela) { return repo.save(parcela); } public Parcela buscar(Long id) { return repo.findById(id).get(); } public Parcela cancelar(Long id) { Parcela parcela = buscar(id); parcela.cancelar(); parcela.setQuitacao(null); // Atualizar Saldo Cliente Cliente c = repositoryCliente.findById(parcela.getEmprestimo().getCliente().getId()).get(); Double saldo = c.getSaldo() + parcela.getValor(); c.setSaldo(saldo); repositoryCliente.save(c); // Atualizar Saldo Investidor Investidor inv = respositoryInvestidor.findById(parcela.getEmprestimo().getInvestidor().getId()).get(); Double saldoInvs = inv.getSaldo() - parcela.getValor(); inv.setSaldo(saldoInvs); respositoryInvestidor.save(inv); return salvar(parcela); } public Parcela pagar(Long id) { Parcela parcela = buscar(id); parcela.pagar(); parcela.setQuitacao(getDate()); // Atualizar Saldo Cliente Cliente c = repositoryCliente.findById(parcela.getEmprestimo().getCliente().getId()).get(); Double saldo = c.getSaldo() - parcela.getValor(); c.setSaldo(saldo); repositoryCliente.save(c); // Atualizar Saldo Investidor Investidor inv = respositoryInvestidor.findById(parcela.getEmprestimo().getInvestidor().getId()).get(); Double saldoInvs = inv.getSaldo() + parcela.getValor(); inv.setSaldo(saldoInvs); respositoryInvestidor.save(inv); return salvar(parcela); } public Date getDate() { Calendar calendar = Calendar.getInstance(); return calendar.getTime(); } public List<Parcela> buscarParcelaBalanco(Boolean pago) { return repo.findByPagoOrderByVencimentoAsc(pago); } }
5ac9424adadd33d240a5c73d893175ddc930d3a0
1d145870f72cb678248b399eb8aea04b03d86a75
/app/src/main/java/com/coolweather/android/util/HttpUtil.java
f92023cfc4f0373e80e2328ca4c3ae0f176a18ec
[ "Apache-2.0" ]
permissive
531621028/coolweather
268e64a21da6dc2ab629d168a92faf44b225fc3f
3dd1eb657def8ff5b855573fd2d60f87c2999168
refs/heads/master
2021-01-23T01:40:51.108973
2017-03-24T03:25:59
2017-03-24T03:25:59
85,925,249
0
0
null
null
null
null
UTF-8
Java
false
false
423
java
package com.coolweather.android.util; import okhttp3.OkHttpClient; import okhttp3.Request; /** * Created by kang on 2017/3/23. */ public class HttpUtil { public static void sendOkHttpRequest(String adress, okhttp3.Callback callback) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(adress).build(); client.newCall(request).enqueue(callback); } }
2f3eb856c04c9f17ccad32d3f97c76b21e304e75
5be10a20029e9601f6ae4efa1711e998e3374f3a
/Numeros.java
b995ac0de37d2a33ae529c26e6204ca16fe2303f
[]
no_license
chechubui/Poo
a1788c9ac5b6b45bf7590f8352aa22be7a57896f
5e256e70fd3500e3170733d5f1a5aaf905b62312
refs/heads/master
2016-08-05T09:07:05.059799
2014-11-05T11:45:54
2014-11-05T11:45:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
412
java
public class Numeros { //atributo valor private int valor; //getter public int getValor(){ return this.valor; } //setter public void setValor(int valor){ System.out.println("usando metodo setValor(int valor) "); this.valor=valor; } public void setValor(double valor){ System.out.println("usando metodo setValor(double valor) "); this.valor=(int)valor; return; } }
8d5136cf781f13ea092cf43b03af4b315f047639
373d384494895b0b5ddd75df936657060605a5fa
/RFacade/rftest/TstRFacade.java
0d2525bba1dbaa064168eff0faf3d7ee374e57a7
[]
no_license
baloghe/Kaggle
ddf565bf451361fd142a9777712099ccd2b76249
a6de5d3dec99947e10dbe1ed81ba0c24847af3eb
refs/heads/master
2021-01-18T21:29:27.385925
2016-05-06T20:48:45
2016-05-06T20:48:45
28,754,225
0
0
null
null
null
null
UTF-8
Java
false
false
2,710
java
package rftest; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import rfacade.REngineInstance; import rfacade.RFacade; /** * Test cases for RFacade */ public class TstRFacade { private static RFacade r; @BeforeClass public static void setUpClass() { r = new RFacade( (new REngineInstance()) ); } @AfterClass public static void tearDownClass() { r.off(); } @Before public void cleanAllVars(){ r.eval("rm(list=ls())"); } @Test public void testAddition(){ double d=12+13; Assert.assertEquals(d, r.calcDouble("12+13"), 0.001); } @Test public void testMultiplication(){ double d=4*5; Assert.assertEquals(d, r.calcDouble("4*5"), 0.001); } @Test public void testDivision(){ double d=5.0/35.0; Assert.assertEquals(d, r.calcDouble("5/35"), 0.001); } @Test public void testPower(){ double d=Math.pow(2, 3); Assert.assertEquals(d, r.calcDouble("2^3"), 0.001); } @Test public void testSqrt(){ double d=Math.sqrt(20); Assert.assertEquals(d, r.calcDouble("sqrt(20)"), 0.0); } @Test public void testPunktStrich(){ double d=10*3+1; Assert.assertEquals(d, r.calcDouble("10*3+1"), 0.0); } @Test public void testExp(){ double d=Math.exp(2.0); Assert.assertEquals(d, r.calcDouble("exp(2)"), 0.0); } @Test public void testTrigo(){ double d=Math.sin(15.0); Assert.assertEquals(d, r.calcDouble("sin(15)"), 0.0); } @Test public void testDblVec(){ double[] d = new double[]{-0.1, 1.1, 2.3, Double.MIN_VALUE, Double.MAX_VALUE}; r.addDoubleVector("d", d); double[] dback=r.getDoubleVector("d"); Assert.assertArrayEquals(d, dback, 0.0); } @Test public void testMatrix(){ //double[][] d = { { 1.0D, 2.0D }, { 3.0D, 4.0D } }; double[][] d = { { 2.0D, 4.0D, 3.0D }, { 1.0D, 5.0D, 7.0D }, { 5.0D, 6.0D, 7.0D } }; double dsum = 0.0; for(int i=0; i<d.length; i++){ for(int j=0; j<d[i].length; j++){ dsum += d[i][j]; } } r.addMatrix("mmm", d); double rdsum = r.calcDouble("msum <- sum(mmm)"); Assert.assertEquals(dsum, rdsum, 0.0); } @Test public void testDataFrame(){ double[][] d = { { 2.0D, 4.0D, 3.0D }, { 1.0D, 5.0D, 7.0D }, { 5.0D, 6.0D, 7.0D } }; double dsum = 0.0; for(int i=0; i<d.length; i++){ for(int j=0; j<d[i].length; j++){ dsum += d[i][j]; } } r.addDataFrame("df", null, new String[]{"alma", "bela", "cili"}, d); double rdsum = r.calcDouble("msum <- sum(df)"); Assert.assertEquals(dsum, rdsum, 0.0); } }
d0c72f60dae7446d79d377a6f92508bedb9592b1
7041ac021206b707e904c4ea3c176f0c8b2f91ff
/ToDoProject/src/main/java/com/bridgelabz/User/SocialLogin/FaceBookConnection.java
1fe7c67ae23c7fd72ea914cef92bb140c850d588
[]
no_license
ashwinipatil321/ToDoApp
b87d751ed37e4e6749bafb02e015cbbd99a2abaf
ae30ba16f67b64f2721e4ceb26c28e6cfb456634
refs/heads/master
2021-09-05T08:05:11.535672
2018-01-25T11:37:00
2018-01-25T11:37:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,247
java
package com.bridgelabz.User.SocialLogin; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Form; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @Component public class FaceBookConnection { private static final String faceBookClientId="1347872695339978"; private static final String faceBookSecretId="1f1b14eca45bf9dfb71dc3408ea8cd8b"; public static final String Redirect_URI = "http://localhost:8080/ToDoProject/connectFaceBook"; public String getFaceBookURL(String unid) { String facebookLoginURL = ""; try { facebookLoginURL = "http://www.facebook.com/dialog/oauth?" + "client_id=" + faceBookClientId + "&redirect_uri=" + URLEncoder.encode(Redirect_URI, "UTF-8") + "&state=" + unid + "&response_type=code" + "&scope=public_profile,email"; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return facebookLoginURL; } public String getAccessToken(String authCode) throws UnsupportedEncodingException { String fbaccessTokenURL = "https://graph.facebook.com/v2.9/oauth/access_token?" + "client_id=" + faceBookClientId + "&redirect_uri=" + URLEncoder.encode(Redirect_URI, "UTF-8") + "&client_secret=" + faceBookSecretId + "&code=" + authCode; ResteasyClient restCall = new ResteasyClientBuilder().build(); ResteasyWebTarget target = restCall.target(fbaccessTokenURL); Form form = new Form(); form.param("client_id", faceBookClientId); form.param("client_secret", faceBookSecretId); form.param("redirect_uri", Redirect_URI); form.param("code", authCode); form.param("grant_type", "authorization_code"); Response response = target.request().accept(MediaType.APPLICATION_JSON).post(Entity.form(form)); String facebookAccessToken = response.readEntity(String.class); ObjectMapper mapper=new ObjectMapper(); String acc_token = null; try { acc_token = mapper.readTree(facebookAccessToken).get("access_token").asText(); } catch (IOException e) { e.printStackTrace(); } return acc_token; } public JsonNode getUserProfile(String fbaccessToken) { String fbgetUserURL = "https://graph.facebook.com/v2.9/me?access_token=" + fbaccessToken + "&fields=id,name,email,first_name,last_name,picture"; ResteasyClient restCall = new ResteasyClientBuilder().build(); ResteasyWebTarget target = restCall.target(fbgetUserURL); String headerAuth = "Bearer " + fbaccessToken; Response response = target.request() .header("Authorization", headerAuth) .accept(MediaType.APPLICATION_JSON) .get(); String profile = response.readEntity(String.class); ObjectMapper mapper=new ObjectMapper(); JsonNode FBprofile = null; try { FBprofile = mapper.readTree(profile); } catch (IOException e) { e.printStackTrace(); } restCall.close(); return FBprofile; } }
d1887ff70a270493c88356366d34217b7617aa35
6bebad6a3683b580232aaadbb46106aecd4c05a1
/src/codeupBasic100/OutputConversion/n1034.java
b166ed1f94f7b92cf26805f6229b9f8a92aef82d
[]
no_license
jeeyani/CodingTest
cb87ff9db22eeb3ec477688de0452eda9f4ff483
11dcbed6ca71586cffc73796b097168869bb357d
refs/heads/master
2023-09-05T02:58:47.521216
2021-10-18T14:55:55
2021-10-18T14:55:55
329,774,656
1
0
null
null
null
null
UTF-8
Java
false
false
326
java
package codeupBasic100.OutputConversion; import java.util.*; public class n1034 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String a = sc.next(); int b = Integer.valueOf(a,8); //8์ง„์ˆ˜์˜ intํƒ€์ž…์œผ๋กœ ๋ณ€ํ™˜ System.out.print(String.format("%d", b)); } }
ef7b02ed7a68da171242fb0156ba820dc4356b3a
f6f101626183101024ffa965deee4202fab1d00f
/seikabutsu/study_java/src/Tel3.java
fb7ce8b7b6d9979fda562a05f173b56e74d2f429
[]
no_license
sonshi/About_Me
bce6d8cd5c70fdeb71892b80774f10605d433963
3be6df914a2c4c1adb1f71303646b3d47dc3f8f9
refs/heads/master
2020-03-18T14:47:01.459604
2019-02-21T12:04:52
2019-02-21T12:04:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
221
java
package study_java; public class Tel3 { private String tel, name; Tel3(String tel, String name){ this.tel = tel; this.name = name; } String getName() { return name; } String getTel() { return tel; } }
144f48f1e2f8baa2848f02a144e62d5e3a07ff99
963a35552210a78620b7054334cbb3721df4a283
/ACERPSYSTEM/src/java/Utilites/UserService.java
248a47fee2e2aa2d70caf87b0803588f518d05ac
[]
no_license
dipskakadiya/ACERP
720a9e053d4b929856216ad6c44a6c9bb2c7c089
fb23c464503e190c7de6dee8e0519f0e5ef84254
refs/heads/master
2016-09-06T17:09:46.032459
2013-11-12T14:37:23
2013-11-12T14:37:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,877
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Utilites; import java.util.List; import javax.sql.DataSource; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.jdbc.core.JdbcTemplate; import java.net.*; import java.io.InputStreamReader; /** * * @author sai */ public class UserService { private JdbcTemplate jdbcTemplate = new JdbcTemplate(); public UserService(String file,String id) { Resource res = new FileSystemResource(file); XmlBeanFactory xbf = new XmlBeanFactory(res); DataSource ds = (DataSource) xbf.getBean(id, DataSource.class); this.jdbcTemplate = new JdbcTemplate(ds); } public void persist(String query) throws Exception { jdbcTemplate.execute(query); } public Integer get_int(String query) throws Exception { return jdbcTemplate.queryForInt(query); } public void update(String query) throws Exception { jdbcTemplate.update(query); } public List getLists(String query) { try { return jdbcTemplate.queryForList(query); } catch (Exception ex) { System.out.println(ex); return jdbcTemplate.queryForList(query); } } public void sendsms(Object phone, String msg) throws Exception { URL url = new URL("http://www.ubaid.tk/sms/sms.aspx?uid=8460838411&pwd=dips1992&msg="+msg+"&phone="+phone+"&provider=way2sms"); URLConnection conn = url.openConnection(); conn.connect(); InputStreamReader content = new InputStreamReader(conn.getInputStream()); for (int i = 0; i != -1; i = content.read()) { System.out.print((char) i); } } }
62f879ab545b0915ae3c0fa76a007aedb7c869c4
a66e5e936f17ed63f39cfdd6ef8bb15f17c201d5
/GoodsMarket/src/com/market/bean/SkuBean.java
3fcfd6d4ddac6273738b450c89ede4bbeafea152
[ "Apache-2.0" ]
permissive
ansonn/usbcamera
2bdb538ba195c384cfc2001149d7637e375edda3
0d9180e3a7126bae9f797af62d59122f1ceb1370
refs/heads/master
2021-08-28T14:03:09.682313
2017-12-12T11:55:34
2017-12-12T11:55:34
113,933,355
1
0
null
null
null
null
UTF-8
Java
false
false
4,256
java
package com.market.bean; import java.io.Serializable; public class SkuBean implements Serializable{ /** * serialVersionUID */ private static final long serialVersionUID = 1L; private Spec[] specbean; private String spec_key; private Double weight; private Double cost_price; private String image; private Long store_id; private Long category_id; private Long prom_id; private Integer number; private Integer store_num; private String url; private String pro_no; private Double amount; private Double real_price; private String title; private Double sell_price; private Double market_price; private Long goods_id; private Integer warning_line; private Long sku_id; private String thumb; private String prom_name; private Boolean isPurchased = true; public String getSpec_key() { return spec_key; } public void setSpec_key(String spec_key) { this.spec_key = spec_key; } public Double getWeight() { return weight; } public void setWeight(Double weight) { this.weight = weight; } public Double getCost_price() { return cost_price; } public void setCost_price(Double cost_price) { this.cost_price = cost_price; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public Long getStore_id() { return store_id; } public void setStore_id(Long store_id) { this.store_id = store_id; } public Long getCategory_id() { return category_id; } public void setCategory_id(Long category_id) { this.category_id = category_id; } public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } public Integer getStore_num() { return store_num; } public void setStore_num(Integer store_num) { this.store_num = store_num; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getPro_no() { return pro_no; } public void setPro_no(String pro_no) { this.pro_no = pro_no; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } public Double getReal_price() { return real_price; } public void setReal_price(Double real_price) { this.real_price = real_price; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Double getSell_price() { return sell_price; } public void setSell_price(Double sell_price) { this.sell_price = sell_price; } public Double getMarket_price() { return market_price; } public void setMarket_price(Double market_price) { this.market_price = market_price; } public Long getGoods_id() { return goods_id; } public void setGoods_id(Long goods_id) { this.goods_id = goods_id; } public Integer getWarning_line() { return warning_line; } public void setWarning_line(Integer warning_line) { this.warning_line = warning_line; } public Long getSku_id() { return sku_id; } public void setSku_id(Long sku_id) { this.sku_id = sku_id; } public String getThumb() { return thumb; } public void setThumb(String thumb) { this.thumb = thumb; } public Boolean getIsPurchased() { return isPurchased; } public void setIsPurchased(Boolean isPurchased) { this.isPurchased = isPurchased; } @Override public String toString() { return "spec_key "+spec_key+" weight "+weight +"cost_price "+cost_price+" image "+image +"store_id "+store_id+" category_id "+category_id +" number "+number+" store_num "+store_num +" url "+url+" pro_no "+pro_no +" amount "+amount+" real_price "+real_price +" title "+title+" sell_price "+sell_price +" market_price "+market_price+" goods_id "+goods_id +" warning_line "+warning_line+" sku_id "+sku_id +" thumb "+thumb; } public Long getProm_id() { return prom_id; } public void setProm_id(Long prom_id) { this.prom_id = prom_id; } public Spec[] getSpecbean() { return specbean; } public void setSpecbean(Spec[] specbean) { this.specbean = specbean; } public String getProm_name() { return prom_name; } public void setProm_name(String prom_name) { this.prom_name = prom_name; } }
707bc6c25f599b87486b3dc37db4f0249e3b973a
c3777b7772de71de2c125e6ed16c1d1256a73c7a
/Assn2/src/cse360assign2/SimpleList.java
c8ca0f39b8148ec823def65b430a3de8305888a9
[]
no_license
jviera1/SimpleList
6a57e897df5193edc8187097cfae3123b32a9806
46d58c6abffd4c12d6883be63770b70f63864fea
refs/heads/master
2021-01-26T11:43:48.084134
2020-02-28T06:17:03
2020-02-28T06:17:03
243,426,108
0
0
null
null
null
null
UTF-8
Java
false
false
6,349
java
/*Author: Joshua E. Viera *Class ID: 373 *Assignment: 2 * * * Description: * This program creates an array of 10 integers. It contains 6 methods that will manipulate the array in different ways. The add() method will add * elements to the array while increasing the size of the array once it is full. The remove() method will accept an integer as an input and remove all the instances * of that integer from the array, and shift all the values to the left of the array. If the array is more than 25% empty, then it will reduce the size of the array. * The toString() method converts the integer array into a single string.The count() method is used to keep track of the total elements in the array. The search() * method searched for an element in the array and returns the index where that value is stored. The last() method returns the last element in the array. The first() * method returns the first element of the array. The size() method returns the size of the array. The append() method appends an integer to the end of the array. */ package cse360assign2; public class SimpleList { private int count; private boolean track; // use this to keep track of the first time you input more than 10 integers to the list private int list[]; private int list2[]; public int size; public int num; public SimpleList() { // Define variables in the constructor count = 0; list = new int [10]; track = false; size = 0; num = 0; } public void add(int n) { // If the list is already full, increase its size by 50% // This will only account for the first time the list is full if(count >= 10) { track = true; if(count == list.length) { // Set the size of arrayList list2 = new int[list.length + list.length/2]; // Traverse through list, add everything to list2 for(int i = 0; i<list.length; i++) { list2[i] = list[i]; } } // Now add something into the new array. for(int i = list2.length-2; i >= 0; i--) { list2[i+1] = list2[i]; } list2[0] = n; // Pass the reference of the bigger array back to the initial reference "list" list = list2; } // This will handle the first ten inputs of the list only else { // If the list is empty, add it in the first index if(list[0] == 0 && count == 0) { list[0] = n; } // If the list is not empty, shift all the elements to the left and // place the input in the first index of that array. else { for(int i = list.length-2; i >= 0; i--) { list[i+1] = list[i]; } list[0] = n; } } // Keep track every time an element is added to the array. count++; } public void remove (int n) { int spaces = 0; // if the number is at the front of the list if(list[0] == n) { list[0]=0; } // look for the occurrences throughout the array else { num = 0; // Keep track of how many occurrences of that integer there are in the array for(int i = 0; i<list.length-1; i++) { if(list[i] == n) { count-=1; //decrease the count for every item removed num++; list[i] = 0; } } // if the number to be removed is not in the array if(num == 0) { System.out.println("Number does not exist in array"); } } // Fix the spacing in the array for(int i = 0; i < list.length-2; i++) { if(list[i] == 0) { list[i] = list[i+1]; list[i+1]=0; } } // for(int i = 0; i<list.length-1; i++) { if(list[i] == 0) { spaces++; } } if(100*((double)spaces / (double)count) >= 25) { // decrease the size of the array list2 = new int[list.length-1]; // Traverse through list, add everything to list2 for(int i = 0; i<list2.length; i++) { list2[i] = list[i]; } // Pass the reference of the bigger array back to the initial reference "list" list = list2; } } // Manage the inputs in the array public int count() { // If add() is used consecutively more than 10 times, count shouldn't exceed 10 /*if(count>=10) { count = 10; }*/ // If remove() is used consecutively more that 10 times, count shouldn't be less that 0 if (count<=0) { count = 0; } return count; } // Convert the array into a string public String toString() { String lastString = null; StringBuffer sbuff = new StringBuffer(); String arr[] = new String[9]; // Move the elements into a string array for (int i = 0; i < list.length-1; i++) { arr[i] = Integer.toString(list[i]); } // Create a string buffer and move the elements of the array into it for(int i = 0; i<arr.length-1; i++) { sbuff.append(arr[i]); } //store the buffer into a string lastString = sbuff.toString(); return lastString; } // Search for an element in the array, return the index of its location public int search(int n) { // traverse through the array for(int i = 0; i < list.length; i++) { // return the index if it is found if(list[i] == n) { return i; } } // return -1 if the element is not in the array return -1; } // display the array as it is right now (not used in Junit testing public void display() { System.out.println("Here is the array now: "); for(int i = 0; i<list.length; i++) { System.out.print(list[i]); } System.out.println("\n"); } // append user input to the very end of the array public void append(int app) { if(list[0]==0) { list[0] = app; } else { list[list.length-1] = app; } } // return the first index of the array public int first() { if(list[0] != 0) { return list[0]; } return -1; } // return the last index of the array public int last() { if(list[0]!=0) { return list[list.length-1]; } return -1; } public int size() { return list.length; } }
0210e86f9e17ca3ead403639e5a21f6f9dc82ed5
cbd99571c213ffbd70b2858b666e3f0882497f2e
/src/main/java/org/onebusaway/gtfs_realtime/exporter/AbstractGtfsRealtimeFileWriter.java
bacb89e41bba9580f0f75a5cd80254f751eb9dab
[ "Apache-2.0" ]
permissive
camsys/onebusaway-hamilton-connector
091cbf4b3aafbf15ad7a1ea720a6fb124e9680e0
4b05b2b2e11fca425b3d9cbdcc9d0ea98d7f540f
refs/heads/master
2020-05-05T03:03:17.559646
2014-10-04T16:17:48
2014-10-04T16:17:48
24,143,625
0
0
null
null
null
null
UTF-8
Java
false
false
2,681
java
/** * Copyright (C) 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onebusaway.gtfs_realtime.exporter; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.protobuf.Message; public abstract class AbstractGtfsRealtimeFileWriter { private static final Logger _log = LoggerFactory.getLogger(AbstractGtfsRealtimeFileWriter.class); protected GtfsRealtimeProvider _provider; private ScheduledExecutorService _executor; private File _path; private int _period = 5; private ScheduledFuture<?> _task; @Inject public void setProvider(GtfsRealtimeProvider provider) { _provider = provider; } @Inject public void setExecutor( @Named(GtfsRealtimeExporterModule.NAME_EXECUTOR) ScheduledExecutorService executor) { _executor = executor; } public void setPath(File path) { _path = path; } public void setPeriod(int timeInSeconds) { _period = timeInSeconds; } @PostConstruct public void start() { _task = _executor.scheduleAtFixedRate(new TaskEntryPoint(), 0, _period, TimeUnit.SECONDS); } @PreDestroy public void stop() { if (_task != null) { _task.cancel(false); _task = null; } } protected abstract Message getMessage(); protected void writeMessageToFile() throws IOException { Message message = getMessage(); OutputStream out = new BufferedOutputStream(new FileOutputStream(_path)); message.writeTo(out); out.close(); } private class TaskEntryPoint implements Runnable { public void run() { try { writeMessageToFile(); } catch (IOException ex) { _log.error("Error writing message to output file: " + _path, ex); } } } }
97848176e2ad3e5e4456da3f463cf8fcf203a4c7
426454ce2e5f4310bfcf29f61e9f34cf0ad23874
/kodilla-patterns/src/main/java/com/kodilla/patterns/factory/task/PaintingTask.java
eab4b27efd82e6df06405d2fdec881987274bd4b
[]
no_license
KatarzynaSzykiewicz/Kalkulator
61cf24f7fdc7c8090d9a9d572bda7004440a516f
6f0d357e31cfcac86117fa0b2f0195341d2c5136
refs/heads/master
2021-09-12T12:05:50.714217
2018-04-11T18:57:11
2018-04-11T18:57:11
115,419,510
0
0
null
2018-04-16T14:54:26
2017-12-26T12:16:06
Java
UTF-8
Java
false
false
934
java
package com.kodilla.patterns.factory.task; public final class PaintingTask implements Task { final String taskName; final String color; final String whatToPaint; final boolean completed; public PaintingTask(final String taskName, final String color, final String whatToPaint, final boolean completed) { this.taskName = taskName; this.color = color; this.whatToPaint = whatToPaint; this.completed = completed; } @Override public String executeTask() { return "A task is to paint " + whatToPaint + " " + color; } @Override public String getTaskName() { return taskName; } @Override public boolean isTaskExecuted() { if (completed) { System.out.println("Painting task is completed."); } else { System.out.println("Painting task is not completed."); } return true; } }
[ "szykiewicz_katarzyn [email protected]" ]
szykiewicz_katarzyn [email protected]
43238dbcfe1a9b28ab46e468a4229934a9a158bc
c461673ce82a8d63bbbbecbc0558c95f13859f2a
/src/main/java/org/jenkins_ci/plugins/flexible_publish/ConditionalMatrixAggregator.java
69aef0b991143c381bccca1b6ad7c9e0b4b521b7
[]
no_license
KostyaSha/flexible-publish-plugin
5bb1f7869d3044bb79823786e44f53c3a02b2331
f6c09dff1c72492481ebe47cd290807ecdd929c7
refs/heads/master
2021-01-17T23:41:03.379988
2015-02-12T18:53:59
2015-02-20T18:34:16
30,714,735
0
0
null
2015-02-12T17:38:50
2015-02-12T17:38:49
null
UTF-8
Java
false
false
2,985
java
/* * The MIT License * * Copyright (c) 2013 IKEDA Yasuyuki * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkins_ci.plugins.flexible_publish; import java.io.IOException; import hudson.Launcher; import hudson.matrix.MatrixAggregator; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixRun; import hudson.model.BuildListener; import hudson.tasks.Publisher; /** * Wraps {@link MatrixAggregator} for the wrapped {@link Publisher}. * Evaluates the condition, and call wrapped {@link MatrixAggregator} if satisfied. */ public class ConditionalMatrixAggregator extends MatrixAggregator { private ConditionalPublisher conditionalPublisher; private MatrixAggregator baseAggregator; protected ConditionalMatrixAggregator(MatrixBuild build, Launcher launcher, BuildListener listener, ConditionalPublisher conditionalPublisher, MatrixAggregator baseAggregator) { super(build, launcher, listener); this.conditionalPublisher = conditionalPublisher; this.baseAggregator = baseAggregator; } @Override public boolean startBuild() throws InterruptedException, IOException { return baseAggregator.startBuild(); } @Override public boolean endRun(MatrixRun run) throws InterruptedException, IOException { MarkPerformedBuilder mpb = new MarkPerformedBuilder(); boolean isSuccess = conditionalPublisher.getRunner().perform( conditionalPublisher.getCondition(), mpb, run, // watch out! not parent build. launcher, listener ); if(!isSuccess || !mpb.isPerformed()) { return true; } return baseAggregator.endRun(run); } @Override public boolean endBuild() throws InterruptedException, IOException { return baseAggregator.endBuild(); } }
04b2c7af144d0e3816d5dd277b7643d8a59e7e78
ed83f1964c39f34e5b59f82814bd27bd138ff4c9
/chapter_001/src/main/java/ru/simple/array/Turn.java
73feabb6f92cf43068ca39f1fe103a6ddb20dd21
[ "Apache-2.0" ]
permissive
simple1161/simple
891146a337766d01dd17859c8500f3f7e71bb6e6
bc0387fa57f0096b4619cb29ea62b9000371d25e
refs/heads/master
2021-04-12T03:32:24.409771
2018-09-28T16:53:02
2018-09-28T16:53:02
125,759,674
0
0
null
null
null
null
UTF-8
Java
false
false
407
java
package ru.simple.array; public class Turn { public int[] turn(int[] array) { for (int i = 0; i < array.length; i++) { int index = array.length - i - 1; int value = index - i; int val1 = array[i]; array[i] = array[index]; array[index] = val1; if (value <= 2) break; } return array; } }
0064ebf79eaf7452d97044d4e9812ef7238e7477
77b8fedb9ec8e989042ac58af9fab3b007b3f036
/mate-core/mate-starter-web/src/main/java/vip/mate/core/web/tree/ForestNodeMerger.java
c07c29738bfc50c7d39a168dfe825b7d0624d0cb
[ "Apache-2.0" ]
permissive
my1313677/matecloud
d920365f314115ef7c8c5cf93d67699a19cb6ec4
1d6c471474ea7aef346dadf50134e0c9dc012600
refs/heads/master
2023-05-11T02:16:26.481905
2021-05-28T07:41:08
2021-05-28T07:41:08
278,293,691
0
0
Apache-2.0
2020-11-25T10:22:21
2020-07-09T07:25:01
Java
UTF-8
Java
false
false
1,048
java
package vip.mate.core.web.tree; import java.util.List; /** * ่Š‚็‚นๅฝ’ๅนถ็ฑป * @author pangu * @link https://blog.csdn.net/u014424628/article/details/51765394?utm_source=blogxgwz2 */ public class ForestNodeMerger { /** * ๅฐ†่Š‚็‚นๆ•ฐ็ป„ๅฝ’ๅนถไธบไธ€ไธชๆฃฎๆž—๏ผˆๅคšๆฃตๆ ‘๏ผ‰๏ผˆๅกซๅ……่Š‚็‚น็š„childrenๅŸŸ๏ผ‰ * ๆ—ถ้—ดๅคๆ‚ๅบฆไธบO(n^2) * * @param items ่Š‚็‚นๅŸŸ * @return ๅคšๆฃตๆ ‘็š„ๆ น่Š‚็‚น้›†ๅˆ */ public static <T extends INode> List<T> merge(List<T> items) { ForestNodeManager<T> forestNodeManager = new ForestNodeManager<>(items); items.forEach(forestNode -> { if (forestNode.getParentId() != 0) { INode node = forestNodeManager.getTreeNodeAT(forestNode.getParentId()); if (node != null) { node.getChildren().add(forestNode); } else { forestNodeManager.addParentId(forestNode.getId()); } } }); return forestNodeManager.getRoot(); } }
069688bf94e67e1aabe871aa59ac145e2ef454ea
804ae7c538088ee47610e2e3d21a90a508e23b03
/src/PeriodicHeartBeatRunnable.java
aa0d6fa54d64fbc4ea05646ac4d402aeef7471ea
[ "Apache-2.0" ]
permissive
JamJamJames98/Networking-Final_Assignment
bf8c8545c0058ca8607d7c8f84a2078a65df8d90
eee4d7551f5c0ac10037c07707fff27ffe2907e0
refs/heads/master
2020-04-02T16:36:19.326928
2018-10-25T06:25:09
2018-10-25T06:25:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,825
java
import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map.Entry; public class PeriodicHeartBeatRunnable implements Runnable { private HashMap<ServerInfo, Date> serverStatus; private int sequenceNumber; private int localPort; public PeriodicHeartBeatRunnable(HashMap<ServerInfo, Date> serverStatus, int localPort) { this.serverStatus = serverStatus; this.sequenceNumber = 0; this.localPort = localPort; } @Override public void run() { while(true) { //broadcast HeartBeat message to all peers from week 9 tute ArrayList<Thread> threadArrayList = new ArrayList<>(); for (ServerInfo server_list : serverStatus.keySet()) { Thread thread = new Thread(new HeartBeatClientRunnable(server_list, "hb|" + localPort + "|" + sequenceNumber)); threadArrayList.add(thread); thread.start(); } for (Thread thread : threadArrayList) { try { thread.join(); } catch (InterruptedException e) { } } // increment the sequenceNumber //System.out.print(sequenceNumber); sequenceNumber += 1; // sleep for two seconds try { Thread.sleep(2000); } catch (InterruptedException e) { } for (Entry<ServerInfo, Date> entry: serverStatus.entrySet()) { Date temp_date = new Date(); Date entry_date = entry.getValue(); //remove if no response for 4 seconds if (temp_date.getTime() - entry_date.getTime() > 4000) { serverStatus.remove(entry); } } } } }
ee831cfa17a2042622dec5f25d29d980ca6923cc
3f95326dfca54c095f8cf99d369296f8334d4702
/src/main/java/example/logger/RecoveryLoggerProducer.java
eafc559cdc869e6d34bd0eceee372f88eeaac9e3
[ "CC0-1.0" ]
permissive
kawasima/goodbye-sleepless-nights
23a1af3cee8f467b7768947644042ce59871b174
198fb357cd64f386d7f5697f333dae9b784ed847
refs/heads/master
2021-01-10T08:48:21.306271
2015-11-18T02:09:19
2015-11-18T02:09:19
46,388,623
1
0
null
null
null
null
UTF-8
Java
false
false
465
java
package example.logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.Dependent; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.InjectionPoint; import javax.inject.Named; /** * @author kawasima */ @Named @Dependent public class RecoveryLoggerProducer { @Produces public RecoveryLogger getProgressLogger(InjectionPoint ip) { return new RecoveryLogger(LoggerFactory.getLogger("RECOVERY")); } }
a148ede7f48ca5111e1b8a99b694c31fd620fab1
7799944a97dc77487163cb7e3d691518519232eb
/rxmvvm-sample/src/main/java/vn/tale/rxmvvm_sample/adapter/UsersAdapter.java
0e31998b5b0dfee3492fc67374fee1029bfeb9c8
[ "Apache-2.0" ]
permissive
talenguyen/RxMvvm
599663a7acb7218969d1d206dd61f2e32971507b
775b095f371ec3d8f9452b4e6092e0e07ced1df9
refs/heads/dev/1.0.0
2020-12-24T01:01:23.980434
2016-06-13T10:15:34
2016-06-13T10:15:34
60,931,875
1
1
null
2016-06-13T09:59:34
2016-06-11T23:16:43
Java
UTF-8
Java
false
false
1,115
java
package vn.tale.rxmvvm_sample.adapter; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import vn.tale.rxmvvm_sample.model.User; import vn.tale.rxmvvm_sample.viewholder.UserViewHolder; /** * Created by Giang Nguyen at Tiki on 6/8/16. */ public class UsersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private List<User> users; public UsersAdapter() { this.users = new ArrayList<>(); } public void setUsers(List<User> users) { this.users = users; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return UserViewHolder.create(parent); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { final User user = users.get(position); final UserViewHolder userViewHolder = UserViewHolder.class.cast(holder); userViewHolder.bind(user); } @Override public int getItemCount() { return users == null ? 0 : users.size(); } }
a83588c70e1c009c117922792941ffac814cabba
89964de2c32a60a3c5996a50aa4e87a67f56e005
/javaSolutions/ThreeSumClosest.java
63273abc2d97ab8b258d041383d1620d26281fed
[]
no_license
liujiankd/leetcodes
08a069ab00f45c20a221495968f35b9e0cd91298
7f4bd404982c0244315cddaf1cf8d70ff29f529a
refs/heads/master
2020-04-10T06:47:22.180870
2014-09-24T14:01:48
2014-09-24T14:01:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,179
java
/* Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). */ public class ThreeSumClosest { // This solution uses O(n^3) time complexity public int threeSumClosest1(int[] num, int target) { final int length = num.length; int result = Integer.MAX_VALUE; int diff = Integer.MAX_VALUE; for(int i = 0; i < length - 2; i++) { for(int j = i + 1; j < length - 1; j++) { int s1 = num[i] + num[j]; for(int k = j + 1; k < length; k++) { if(Math.abs(s1 + num[k] - target) < diff) { result = s1 + num[k]; diff = Math.abs(s1 + num[k] - target); if(diff == 0) { return target; } } } } } return result; } }
0b78110af5111ebf068adf4d75446aad3a33d760
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/alibaba--druid/ad6f6a593c6e72fe6e5252230851acfc69c6517f/before/MySqlWallTest.java
009d9ee2ead3d53f5c4b753ae5b23e45225efc99
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
2,861
java
/* * Copyright 1999-2011 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.bvt.filter.wall; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.druid.wall.WallUtils; public class MySqlWallTest extends TestCase { public void testWall() throws Exception { Assert.assertFalse(WallUtils.isValidateMySql("SELECT * FROM X where id=1 and 1!=1 union select 14,13,12,11,10,@@version_compile_os,8,7,6,5,4,3,2,1 FROM X")); Assert.assertTrue(WallUtils.isValidateMySql("select '@@version_compile_os' FROM X")); Assert.assertFalse(WallUtils.isValidateMySql("SELECT * FROM X where id=1 and 1!=1 union select hex(load_file(0x633A2F77696E646F77732F7265706169722F73616D))")); Assert.assertTrue(WallUtils.isValidateMySql("select hex(load_file(0x633A2F77696E646F77732F7265706169722F73616D))")); Assert.assertTrue(WallUtils.isValidateMySql("select 'hex(load_file(0x633A2F77696E646F77732F7265706169722F73616D))'")); Assert.assertFalse(WallUtils.isValidateMySql("select * from t where fid = 1 union select 15,version() FROM X")); Assert.assertTrue(WallUtils.isValidateMySql("select 15,version() FROM X")); Assert.assertTrue(WallUtils.isValidateMySql("select 15,'version'")); Assert.assertFalse(WallUtils.isValidateMySql("SELECT *FROM T UNION select 1 from information_schema.columns")); Assert.assertTrue(WallUtils.isValidateMySql("select 'information_schema.columns'")); Assert.assertFalse(WallUtils.isValidateMySql("SELECT *FROM T UNION select 1 from mysql.user")); Assert.assertTrue(WallUtils.isValidateMySql("select 'mysql.user'")); Assert.assertFalse(WallUtils.isValidateMySql("select * FROM T WHERE id = 1 AND select 0x3C3F706870206576616C28245F504F53545B2763275D293F3E into outfile '\\www\\edu\\1.php'")); Assert.assertTrue(WallUtils.isValidateMySql("select 'outfile'")); Assert.assertFalse(WallUtils.isValidateMySql("select f1, f2 from t union select 1, 2")); Assert.assertTrue(WallUtils.isValidateMySql("select c1 from t where 1=1 or id =1")); Assert.assertFalse(WallUtils.isValidateMySql("select c1 from t where id =1 or 1=1")); Assert.assertFalse(WallUtils.isValidateMySql("select c1 from t where id =1 || 1=1")); } }
b53277651bbe3eb2e1284d08cbf77f28fb043d46
9a501f792940ad0113ff5fc3f96e97ce0897090e
/jooby/src/test/java/org/jooby/ResultTest.java
71d5e3d9fb45691b92ca9619f89c5363848f6c43
[ "Apache-2.0" ]
permissive
JStumpp/jooby
651885fd8677a8a18748c60e0ca491bed4c46606
9390a580e9d2966b65bd5a6f6ffb1bf5c520f70b
refs/heads/master
2020-08-01T10:03:56.921913
2016-11-12T21:33:42
2016-11-12T21:33:42
73,577,727
1
0
null
2016-11-12T20:50:43
2016-11-12T20:50:43
null
UTF-8
Java
false
false
5,859
java
package org.jooby; import static org.junit.Assert.assertEquals; import java.util.Date; import java.util.Optional; import org.junit.Test; import com.google.common.collect.Lists; public class ResultTest { @Test public void sillyJacocoWithStaticMethods() { new Results(); } @Test public void entityAndStatus() { Result result = Results.with("x", 200); assertEquals("x", result.ifGet().get()); assertEquals(Optional.empty(), result.type()); assertEquals(Status.OK, result.status().get()); } @Test public void json() { Result result = Results.json("{}"); assertEquals("{}", result.ifGet().get()); assertEquals(MediaType.json, result.type().get()); assertEquals(Status.OK, result.status().get()); } @Test public void xml() { Result result = Results.xml("{}"); assertEquals("{}", result.ifGet().get()); assertEquals(MediaType.xml, result.type().get()); assertEquals(Status.OK, result.status().get()); } @Test public void accepted() { Result result = Results.accepted(); assertEquals(Optional.empty(), result.ifGet()); assertEquals(Optional.empty(), result.type()); assertEquals(Status.ACCEPTED, result.status().get()); } @Test public void acceptedWithConent() { Result result = Results.accepted("s"); assertEquals(Optional.empty(), result.type()); assertEquals("s", result.ifGet().get()); assertEquals(Status.ACCEPTED, result.status().get()); } @Test public void ok() { Result result = Results.ok(); assertEquals(Optional.empty(), result.ifGet()); assertEquals((Object) null, result.get()); assertEquals(Optional.empty(), result.type()); assertEquals(Status.OK, result.status().get()); } @Test public void okWithConent() { Result result = Results.ok("s"); assertEquals(Optional.empty(), result.type()); assertEquals("s", result.ifGet().get()); assertEquals(Status.OK, result.status().get()); } @Test public void withStatusCode() { Result result = Results.with(200); assertEquals(Optional.empty(), result.ifGet()); assertEquals(Optional.empty(), result.type()); assertEquals(Status.OK, result.status().get()); } @Test public void chainStatusCode() { Result result = Results.with("b").status(200); assertEquals(Optional.empty(), result.type()); assertEquals("b", result.ifGet().get()); assertEquals(Status.OK, result.status().get()); } @Test public void type() { Result result = Results.with("b").type("json"); assertEquals(MediaType.json, result.type().get()); assertEquals("b", result.ifGet().get()); assertEquals(Optional.empty(), result.status()); } @Test public void header() { Date date = new Date(); Result result = Results.ok().header("char", 'c') .header("byte", (byte) 3) .header("short", (short) 4) .header("int", 5) .header("long", 6l) .header("float", 7f) .header("double", 8d) .header("date", date) .header("list", 1, 2, 3); assertEquals('c', result.headers().get("char")); assertEquals((byte) 3, result.headers().get("byte")); assertEquals((short) 4, result.headers().get("short")); assertEquals(5, result.headers().get("int")); assertEquals((long) 6, result.headers().get("long")); assertEquals(7.0f, result.headers().get("float")); assertEquals(8.0d, result.headers().get("double")); assertEquals(date, result.headers().get("date")); assertEquals(Lists.newArrayList(1, 2, 3), result.headers().get("list")); } @Test public void chainStatus() { Result result = Results.with("b").status(Status.OK); assertEquals(Optional.empty(), result.type()); assertEquals("b", result.ifGet().get()); assertEquals(Status.OK, result.status().get()); } @Test public void noContent() { Result result = Results.noContent(); assertEquals(Optional.empty(), result.ifGet()); assertEquals(Optional.empty(), result.type()); assertEquals(Status.NO_CONTENT, result.status().get()); } @Test public void withStatus() { Result result = Results.with(Status.CREATED); assertEquals(Optional.empty(), result.ifGet()); assertEquals(Optional.empty(), result.type()); assertEquals(Status.CREATED, result.status().get()); } @Test public void resultWithConent() { Result result = Results.with("s"); assertEquals(Optional.empty(), result.type()); assertEquals(Optional.empty(), result.status()); assertEquals("s", result.ifGet().get()); } @Test public void moved() { Result result = Results.moved("/location"); assertEquals(Optional.empty(), result.ifGet()); assertEquals(Optional.empty(), result.type()); assertEquals(Status.MOVED_PERMANENTLY, result.status().get()); assertEquals("/location", result.headers().get("location")); } @Test public void redirect() { Result result = Results.redirect("/location"); assertEquals(Optional.empty(), result.ifGet()); assertEquals(Optional.empty(), result.type()); assertEquals(Status.FOUND, result.status().get()); assertEquals("/location", result.headers().get("location")); } @Test public void seeOther() { Result result = Results.seeOther("/location"); assertEquals(Optional.empty(), result.ifGet()); assertEquals(Optional.empty(), result.type()); assertEquals(Status.SEE_OTHER, result.status().get()); assertEquals("/location", result.headers().get("location")); } @Test public void temporaryRedirect() { Result result = Results.tempRedirect("/location"); assertEquals(Optional.empty(), result.ifGet()); assertEquals(Optional.empty(), result.type()); assertEquals(Status.TEMPORARY_REDIRECT, result.status().get()); assertEquals("/location", result.headers().get("location")); } }
87261cf221e38702f737a512b9e342e80198a92a
01df68ce108ef20ced22beaa992346b048653145
/gravitee-apim-rest-api/gravitee-apim-rest-api-model/src/test/java/io/gravitee/rest/api/model/v4/api/NewApiEntityTest.java
f569d5b63581c9aeee737f3fbcb84826a59efaeb
[ "Apache-2.0" ]
permissive
anniyanvr/gravitee-gateway
022436afe23c0768da0c65461d7ea5433f9e7d21
d4c84ecdeddbd568342b23bb2a30ede91e32d230
refs/heads/master
2023-04-13T07:32:54.111141
2023-03-30T15:34:21
2023-03-30T15:52:40
83,608,024
0
0
Apache-2.0
2023-03-31T19:30:00
2017-03-01T22:26:04
Java
UTF-8
Java
false
false
1,517
java
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.rest.api.model.v4.api; import static org.junit.Assert.*; import org.junit.Test; public class NewApiEntityTest { @Test public void setNameShouldSanitizeInput() { NewApiEntity newApiEntity = new NewApiEntity(); newApiEntity.setName("A Test API"); assertEquals("A Test API", newApiEntity.getName()); newApiEntity.setName("A <img src=\"../../../image.png\">Test API"); assertEquals("A Test API", newApiEntity.getName()); newApiEntity.setName("A Test <script>alert()</script>API"); assertEquals("A Test API", newApiEntity.getName()); newApiEntity.setName("<h1>A Test</h1> API"); assertEquals("A Test API", newApiEntity.getName()); newApiEntity.setName("A <a href=\"https://www.gravitee.io\">Test</a> API"); assertEquals("A Test API", newApiEntity.getName()); } }
3dd94f035f1be4c2a7f1adedf4cbee2a85c078b6
a8a7cc6bae2a202941e504aea4356e2a959e5e95
/eclipse/org.activiti.designer.gui/src/main/java/org/activiti/designer/features/AddStartEventFeature.java
8b8b8a0a9095fe769272d770e75df812dddd9305
[]
no_license
jenkinsci/jenkow-plugin
aed5d5db786ad260c16cebecf5c6bbbcbf498be5
228748890476b2f17f80b618c8d474a4acf2af8b
refs/heads/master
2023-08-19T23:43:15.544100
2013-05-14T00:49:56
2013-05-14T00:49:56
4,395,961
2
4
null
2022-12-20T22:37:41
2012-05-21T16:58:26
Java
UTF-8
Java
false
false
240
java
package org.activiti.designer.features; import org.eclipse.graphiti.features.IFeatureProvider; public class AddStartEventFeature extends AddEventFeature { public AddStartEventFeature(IFeatureProvider fp) { super(fp); } }
e0132f578360b4b8c3fe3ba56384bacc7e3a7c3c
3f7028cc89a79582266a19acbde0d6b066a568de
/mobile/library/java/org/chromium/net/impl/AtomicCombinatoryState.java
4f46472c0c3a9d7db4f77a32325ad8d68b567eb7
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
envoyproxy/envoy
882d3c7f316bf755889fb628bee514bb2f6f66f0
72f129d273fa32f49581db3abbaf4b62e3e3703c
refs/heads/main
2023-08-31T09:20:01.278000
2023-08-31T08:58:36
2023-08-31T08:58:36
65,214,191
21,404
4,756
Apache-2.0
2023-09-14T21:56:37
2016-08-08T15:07:24
C++
UTF-8
Java
false
false
1,227
java
package org.chromium.net.impl; import java.util.concurrent.atomic.AtomicInteger; /** * "Compare And Swap" logic based class providing a mean to ensure that the last awaited * "stateEvent" will be identified as so. Typically a "stateEvent" is a single bit flip. * * <p>This class is Thread Safe. */ final class AtomicCombinatoryState { private final int mFinalState; private final AtomicInteger mState = new AtomicInteger(0); /** * finalState must be a power of two minus one: 1, 3, 7, 15, ... */ AtomicCombinatoryState(int finalState) { assert finalState > 0 && ((finalState + 1) & finalState) == 0; this.mFinalState = finalState; } /** * Returns true if the state reaches, for the first time, the final state. The provided stateEvent * is atmomically ORed with the current state - the outcome is saved as the new state. */ boolean hasReachedFinalState(int stateEvent) { assert stateEvent <= mFinalState; while (true) { int originalState = mState.get(); int updatedState = originalState | stateEvent; if (mState.compareAndSet(originalState, updatedState)) { return originalState != mFinalState && updatedState == mFinalState; } } } }
214829e70e47757c7fe3c500a7bf6d9a57ba0308
d81e3d8e99d56a4d6d87438c14ed91cd2b281a49
/src/main/java/bookstore/controller/InitController.java
0460c369fbf06a49ef48ed76488bdc3aa700f48b
[]
no_license
COJ123/Bookstore
7f0c562da2fd7ee19c977909ce2ed1ad38a2cba2
9a43afb1cdb46eef79a51637c524ee013becd783
refs/heads/master
2020-03-21T20:56:58.792110
2018-06-28T11:23:38
2018-06-28T11:23:38
137,520,572
0
0
null
null
null
null
UTF-8
Java
false
false
266
java
package bookstore.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class InitController { @GetMapping("/") public String showHome(){ return "index"; } }
4bdac6999630e0678330671ba8b8664dcfea9e08
984a565528c6f6b5849e2bab99ef7b354b96bacc
/src/main/java/ro/ghid/java/service/package-info.java
32ea6e3c959efb15dd46b26d057552ccc03a1e31
[]
no_license
niculaflorin/RoGhid
7e56ce308e8da3b4516fc40dcf72ff7f33636d8d
636848663a1556824b34ad0cd93cf3b228298667
refs/heads/master
2021-04-28T13:14:20.346563
2018-01-02T18:27:55
2018-01-02T18:27:55
122,099,105
0
1
null
2020-09-18T10:41:38
2018-02-19T17:49:27
Java
UTF-8
Java
false
false
62
java
/** * Service layer beans. */ package ro.ghid.java.service;
fd4b2fa3b464e51788cbcf4812d490cdccf95a62
9a6f2b9b73bcf8fd22ddf04366477b1dc3b6439d
/src/main/java/com/douglei/orm/sessionfactory/sessions/session/sqlquery/impl/ExecutableQuerySql.java
51026cddc2e5f242b286988d76e791969dd6c0d5
[]
no_license
DougLei/jdb-orm
c02e0dbf9c54b426dc4944eded7a784d2b0291ce
c0ded6fb9e29df8de93c049ba6d7d4d1992e1591
refs/heads/master
2022-07-12T11:03:54.096755
2021-06-01T08:03:35
2021-06-01T08:03:35
183,609,797
0
0
null
2022-06-21T01:06:50
2019-04-26T10:33:08
Java
UTF-8
Java
false
false
4,242
java
package com.douglei.orm.sessionfactory.sessions.session.sqlquery.impl; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import com.douglei.orm.sessionfactory.sessions.session.IExecutableSql; import com.douglei.orm.sessionfactory.sessions.session.sql.impl.ExecutableSql; import com.douglei.orm.sql.query.QuerySqlStatement; /** * * @author DougLei */ public class ExecutableQuerySql implements IExecutableSql{ private QuerySqlStatement querySql; private List<Object> parameterValues; private HashSet<String> conditionSQLMark; // ็ป„่ฃ…ๆกไปถsqlๆ—ถ, ่ฎฐๅฝ•ๆฏไธชๆกไปถ็š„ๅ‚ๆ•ฐๅ(ๅŽป้‡), ็”จๆฅๅœจๆœ€ๅŽ้ชŒ่ฏๆ˜ฏๅฆๆฒกๆœ‰ไผ ๅ…ฅๅฟ…่ฆ็š„ๅ‚ๆ•ฐ private StringBuilder conditionSQL; // ๆกไปถsql private StringBuilder resultSQL; // (ๆŸฅ่ฏข)็ป“ๆžœsql private StringBuilder orderbySQL; // ๆŽ’ๅบsql ExecutableQuerySql(ExecutableSql executableSql) { this.querySql = new QuerySqlStatement(executableSql.getSql(), false); this.parameterValues = executableSql.getParameterValues(); } // ่Žทๅ–ๆกไปถsql private StringBuilder getConditionSQL() { if(conditionSQLMark == null) { conditionSQLMark = new HashSet<String>(); conditionSQL = new StringBuilder(300); conditionSQL.append(" WHERE "); if(parameterValues == null) parameterValues = new ArrayList<Object>(); } return conditionSQL; } /** * ่ฟฝๅŠ ๆกไปถSQL * @param sql * @param name * @param values */ public void appendConditionSQL(String sql, String name, Object... values) { getConditionSQL().append(sql); // ่ฟฝๅŠ sql conditionSQLMark.add(name); // ่ฎฐๅฝ•ๅ‚ๆ•ฐ if(values.length > 0) { // ่ฎฐๅฝ•ๅ‚ๆ•ฐๅ€ผ for (Object value : values) { if(value != null) parameterValues.add(value); } } } /** * ่ฟฝๅŠ ๆกไปถSQL็š„ๅทฆๆ‹ฌๅท */ public void appendConditionSQLLeftParenthesis() { getConditionSQL().append('('); } /** * ่ฟฝๅŠ ๆกไปถSQL็š„ๅณๆ‹ฌๅท */ public void appendConditionSQLRightParenthesis() { conditionSQL.append(')'); } /** * ่ฟฝๅŠ ๆกไปถSQL็š„้€ป่พ‘่ฟ็ฎ—็ฌฆ * @param next */ public void appendConditionSQLNext(LogicalOperator next) { conditionSQL.append(' ').append(next.name()).append(' '); } /** * ๆกไปถsqlไธญ, ๆ˜ฏๅฆๅญ˜ๅœจๆŒ‡ๅฎšname็š„ๅ‚ๆ•ฐ * @param name * @return */ public boolean existsInConditionSQL(String name) { if(conditionSQLMark == null) return false; return conditionSQLMark.contains(name); } /** * ่ฟฝๅŠ (ๆŸฅ่ฏข)็ป“ๆžœSQL * @param name * @param alias */ public void appendResultSQL(String name, String alias) { if(resultSQL == null) { resultSQL = new StringBuilder(100); resultSQL.append("SELECT "); }else { resultSQL.append(','); } resultSQL.append(name); if(alias != null) resultSQL.append(' ').append(alias); } /** * ่ฟฝๅŠ ๆŽ’ๅบSQL * @param name * @param order */ public void appendOrderbySQL(String name, String order) { if(orderbySQL == null) { orderbySQL = new StringBuilder(100); orderbySQL.append(" ORDER BY "); }else { orderbySQL.append(','); } orderbySQL.append(name); if(order != null) orderbySQL.append(' ').append(order); } @Override public String getCurrentSql() { StringBuilder sql = new StringBuilder(querySql.getTotalLength() + 500); // append withๅญๅฅ if(querySql.getWithClause() != null) sql.append(querySql.getWithClause()).append(' '); // append(ๆŸฅ่ฏข)็ป“ๆžœsql if(resultSQL == null) { sql.append("SELECT * FROM ("); }else { sql.append(resultSQL).append(" FROM ("); } // appendๅŽŸsql sql.append(querySql.getSql()).append(") _SUB_SQ_"); // appendๆกไปถsql if(conditionSQL != null) sql.append(conditionSQL); // appendๆŽ’ๅบsql if(orderbySQL != null) sql.append(orderbySQL); return sql.toString(); } @Override public List<Object> getCurrentParameterValues() { return parameterValues; } @Override public String toString() { return "\nquerySql=" + querySql + "\nconditionSQL=" + conditionSQL + "\norderbySQL=" + orderbySQL + "\nparameterValues=" + parameterValues; } }
54641829777a2a8fe9b5975efe49bb8dc204a1b4
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/k9mail--k-9/eac65df806031417d5ad752300a0fc317519d135/after/MessageCompose.java
8cc78b61e958ebcd6a34a83c60ebe6e3fefc9f73
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
126,400
java
package com.fsck.k9.activity; import java.text.DateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.LoaderManager; import android.app.PendingIntent; import android.content.ClipData; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender.SendIntentException; import android.content.Loader; import android.content.pm.ActivityInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.support.annotation.Nullable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.util.TypedValue; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.view.Window; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.fsck.k9.Account; import com.fsck.k9.Account.MessageFormat; import com.fsck.k9.Account.QuoteStyle; import com.fsck.k9.FontSizes; import com.fsck.k9.Identity; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.activity.compose.ComposeCryptoStatus; import com.fsck.k9.activity.compose.CryptoSettingsDialog.OnCryptoModeChangedListener; import com.fsck.k9.activity.compose.RecipientMvpView; import com.fsck.k9.activity.compose.RecipientPresenter; import com.fsck.k9.activity.compose.RecipientPresenter.CryptoMode; import com.fsck.k9.activity.loader.AttachmentContentLoader; import com.fsck.k9.activity.loader.AttachmentInfoLoader; import com.fsck.k9.activity.misc.Attachment; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.controller.MessagingListener; import com.fsck.k9.fragment.ProgressDialogFragment; import com.fsck.k9.fragment.ProgressDialogFragment.CancelListener; import com.fsck.k9.helper.Contacts; import com.fsck.k9.helper.HtmlConverter; import com.fsck.k9.helper.IdentityHelper; import com.fsck.k9.helper.MailTo; import com.fsck.k9.helper.SimpleTextWatcher; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Multipart; import com.fsck.k9.mail.Part; import com.fsck.k9.mail.internet.MessageExtractor; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mailstore.LocalBodyPart; import com.fsck.k9.mailstore.LocalMessage; import com.fsck.k9.message.IdentityField; import com.fsck.k9.message.IdentityHeaderParser; import com.fsck.k9.message.InsertableHtmlContent; import com.fsck.k9.message.MessageBuilder; import com.fsck.k9.message.PgpMessageBuilder; import com.fsck.k9.message.QuotedTextMode; import com.fsck.k9.message.SimpleMessageBuilder; import com.fsck.k9.message.SimpleMessageFormat; import com.fsck.k9.provider.AttachmentProvider; import com.fsck.k9.ui.EolConvertingEditText; import com.fsck.k9.view.MessageWebView; import org.htmlcleaner.CleanerProperties; import org.htmlcleaner.HtmlCleaner; import org.htmlcleaner.SimpleHtmlSerializer; import org.htmlcleaner.TagNode; import org.openintents.openpgp.IOpenPgpService2; import org.openintents.openpgp.util.OpenPgpApi; import org.openintents.openpgp.util.OpenPgpServiceConnection; import org.openintents.openpgp.util.OpenPgpServiceConnection.OnBound; @SuppressWarnings("deprecation") public class MessageCompose extends K9Activity implements OnClickListener, CancelListener, OnFocusChangeListener, OnCryptoModeChangedListener, MessageBuilder.Callback { private static final int DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE = 1; private static final int DIALOG_CONFIRM_DISCARD_ON_BACK = 2; private static final int DIALOG_CHOOSE_IDENTITY = 3; private static final int DIALOG_CONFIRM_DISCARD = 4; private static final long INVALID_DRAFT_ID = MessagingController.INVALID_MESSAGE_ID; private static final String ACTION_COMPOSE = "com.fsck.k9.intent.action.COMPOSE"; private static final String ACTION_REPLY = "com.fsck.k9.intent.action.REPLY"; private static final String ACTION_REPLY_ALL = "com.fsck.k9.intent.action.REPLY_ALL"; private static final String ACTION_FORWARD = "com.fsck.k9.intent.action.FORWARD"; private static final String ACTION_EDIT_DRAFT = "com.fsck.k9.intent.action.EDIT_DRAFT"; private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_MESSAGE_BODY = "messageBody"; private static final String EXTRA_MESSAGE_REFERENCE = "message_reference"; private static final String STATE_KEY_ATTACHMENTS = "com.fsck.k9.activity.MessageCompose.attachments"; private static final String STATE_KEY_QUOTED_TEXT_MODE = "com.fsck.k9.activity.MessageCompose.QuotedTextShown"; private static final String STATE_KEY_SOURCE_MESSAGE_PROCED = "com.fsck.k9.activity.MessageCompose.stateKeySourceMessageProced"; private static final String STATE_KEY_DRAFT_ID = "com.fsck.k9.activity.MessageCompose.draftId"; private static final String STATE_KEY_HTML_QUOTE = "com.fsck.k9.activity.MessageCompose.HTMLQuote"; private static final String STATE_IDENTITY_CHANGED = "com.fsck.k9.activity.MessageCompose.identityChanged"; private static final String STATE_IDENTITY = "com.fsck.k9.activity.MessageCompose.identity"; private static final String STATE_IN_REPLY_TO = "com.fsck.k9.activity.MessageCompose.inReplyTo"; private static final String STATE_REFERENCES = "com.fsck.k9.activity.MessageCompose.references"; private static final String STATE_KEY_READ_RECEIPT = "com.fsck.k9.activity.MessageCompose.messageReadReceipt"; private static final String STATE_KEY_DRAFT_NEEDS_SAVING = "com.fsck.k9.activity.MessageCompose.draftNeedsSaving"; private static final String STATE_KEY_FORCE_PLAIN_TEXT = "com.fsck.k9.activity.MessageCompose.forcePlainText"; private static final String STATE_KEY_QUOTED_TEXT_FORMAT = "com.fsck.k9.activity.MessageCompose.quotedTextFormat"; private static final String STATE_KEY_NUM_ATTACHMENTS_LOADING = "numAttachmentsLoading"; private static final String STATE_KEY_WAITING_FOR_ATTACHMENTS = "waitingForAttachments"; private static final String LOADER_ARG_ATTACHMENT = "attachment"; private static final String FRAGMENT_WAITING_FOR_ATTACHMENT = "waitingForAttachment"; private static final int MSG_PROGRESS_ON = 1; private static final int MSG_PROGRESS_OFF = 2; private static final int MSG_SKIPPED_ATTACHMENTS = 3; private static final int MSG_SAVED_DRAFT = 4; private static final int MSG_DISCARDED_DRAFT = 5; private static final int MSG_PERFORM_STALLED_ACTION = 6; private static final int ACTIVITY_REQUEST_PICK_ATTACHMENT = 1; private static final int REQUEST_MASK_RECIPIENT_PRESENTER = (1<<8); private static final int REQUEST_MASK_MESSAGE_BUILDER = (2<<8); /** * Regular expression to remove the first localized "Re:" prefix in subjects. * * Currently: * - "Aw:" (german: abbreviation for "Antwort") */ private static final Pattern PREFIX = Pattern.compile("^AW[:\\s]\\s*", Pattern.CASE_INSENSITIVE); /** * The account used for message composition. */ private Account mAccount; private Contacts mContacts; /** * This identity's settings are used for message composition. * Note: This has to be an identity of the account {@link #mAccount}. */ private Identity mIdentity; private boolean mIdentityChanged = false; private boolean mSignatureChanged = false; /** * Reference to the source message (in case of reply, forward, or edit * draft actions). */ private MessageReference mMessageReference; private Message mSourceMessage; /** * "Original" message body * * <p> * The contents of this string will be used instead of the body of a referenced message when * replying to or forwarding a message.<br> * Right now this is only used when replying to a signed or encrypted message. It then contains * the stripped/decrypted body of that message. * </p> * <p><strong>Note:</strong> * When this field is not {@code null} we assume that the message we are composing right now * should be encrypted. * </p> */ private String mSourceMessageBody; /** * Indicates that the source message has been processed at least once and should not * be processed on any subsequent loads. This protects us from adding attachments that * have already been added from the restore of the view state. */ private boolean mSourceMessageProcessed = false; private int mMaxLoaderId = 0; private RecipientPresenter recipientPresenter; private MessageBuilder currentMessageBuilder; private boolean mFinishAfterDraftSaved; @Override public void onFocusChange(View v, boolean hasFocus) { switch(v.getId()) { case R.id.message_content: case R.id.subject: if (hasFocus) { recipientPresenter.onNonRecipientFieldFocused(); } break; } } @Override public void onCryptoModeChanged(CryptoMode cryptoMode) { recipientPresenter.onCryptoModeChanged(cryptoMode); } enum Action { COMPOSE, REPLY, REPLY_ALL, FORWARD, EDIT_DRAFT } /** * Contains the action we're currently performing (e.g. replying to a message) */ private Action mAction; private boolean mReadReceipt = false; private QuotedTextMode mQuotedTextMode = QuotedTextMode.NONE; /** * Contains the format of the quoted text (text vs. HTML). */ private SimpleMessageFormat mQuotedTextFormat; /** * When this it {@code true} the message format setting is ignored and we're always sending * a text/plain message. */ private boolean mForcePlainText = false; private TextView mChooseIdentityButton; private EditText mSubjectView; private EolConvertingEditText mSignatureView; private EolConvertingEditText mMessageContentView; private LinearLayout mAttachments; private Button mQuotedTextShow; private View mQuotedTextBar; private ImageButton mQuotedTextEdit; private EolConvertingEditText mQuotedText; private MessageWebView mQuotedHTML; private InsertableHtmlContent mQuotedHtmlContent; // Container for HTML reply as it's being built. private String mOpenPgpProvider; private OpenPgpServiceConnection mOpenPgpServiceConnection; private String mReferences; private String mInReplyTo; private boolean mSourceProcessed = false; /** * The currently used message format. * * <p> * <strong>Note:</strong> * Don't modify this field directly. Use {@link #updateMessageFormat()}. * </p> */ private SimpleMessageFormat mMessageFormat; private QuoteStyle mQuoteStyle; private boolean draftNeedsSaving = false; private boolean isInSubActivity = false; /** * The database ID of this message's draft. This is used when saving drafts so the message in * the database is updated instead of being created anew. This property is INVALID_DRAFT_ID * until the first save. */ private long mDraftId = INVALID_DRAFT_ID; /** * Number of attachments currently being fetched. */ private int mNumAttachmentsLoading = 0; private enum WaitingAction { NONE, SEND, SAVE } /** * Specifies what action to perform once attachments have been fetched. */ private WaitingAction mWaitingForAttachments = WaitingAction.NONE; private Handler mHandler = new Handler() { @Override public void handleMessage(android.os.Message msg) { switch (msg.what) { case MSG_PROGRESS_ON: setProgressBarIndeterminateVisibility(true); break; case MSG_PROGRESS_OFF: setProgressBarIndeterminateVisibility(false); break; case MSG_SKIPPED_ATTACHMENTS: Toast.makeText( MessageCompose.this, getString(R.string.message_compose_attachments_skipped_toast), Toast.LENGTH_LONG).show(); break; case MSG_SAVED_DRAFT: mDraftId = (Long) msg.obj; Toast.makeText( MessageCompose.this, getString(R.string.message_saved_toast), Toast.LENGTH_LONG).show(); break; case MSG_DISCARDED_DRAFT: Toast.makeText( MessageCompose.this, getString(R.string.message_discarded_toast), Toast.LENGTH_LONG).show(); break; case MSG_PERFORM_STALLED_ACTION: performStalledAction(); break; default: super.handleMessage(msg); break; } } }; private Listener mListener = new Listener(); private FontSizes mFontSizes = K9.getFontSizes(); /** * Compose a new message using the given account. If account is null the default account * will be used. */ public static void actionCompose(Context context, Account account) { String accountUuid = (account == null) ? Preferences.getPreferences(context).getDefaultAccount().getUuid() : account.getUuid(); Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_ACCOUNT, accountUuid); i.setAction(ACTION_COMPOSE); context.startActivity(i); } /** * Get intent for composing a new message as a reply to the given message. If replyAll is true * the function is reply all instead of simply reply. * @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message */ public static Intent getActionReplyIntent( Context context, LocalMessage message, boolean replyAll, String messageBody) { Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_MESSAGE_BODY, messageBody); i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference()); if (replyAll) { i.setAction(ACTION_REPLY_ALL); } else { i.setAction(ACTION_REPLY); } return i; } public static Intent getActionReplyIntent(Context context, MessageReference messageReference) { Intent intent = new Intent(context, MessageCompose.class); intent.setAction(ACTION_REPLY); intent.putExtra(EXTRA_MESSAGE_REFERENCE, messageReference); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } /** * Compose a new message as a reply to the given message. If replyAll is true the function * is reply all instead of simply reply. * @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message */ public static void actionReply( Context context, LocalMessage message, boolean replyAll, String messageBody) { context.startActivity(getActionReplyIntent(context, message, replyAll, messageBody)); } /** * Compose a new message as a forward of the given message. * @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message */ public static void actionForward( Context context, LocalMessage message, String messageBody) { Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_MESSAGE_BODY, messageBody); i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference()); i.setAction(ACTION_FORWARD); context.startActivity(i); } /** * Continue composition of the given message. This action modifies the way this Activity * handles certain actions. * Save will attempt to replace the message in the given folder with the updated version. * Discard will delete the message from the given folder. */ public static void actionEditDraft(Context context, MessageReference messageReference) { Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_MESSAGE_REFERENCE, messageReference); i.setAction(ACTION_EDIT_DRAFT); context.startActivity(i); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (UpgradeDatabases.actionUpgradeDatabases(this, getIntent())) { finish(); return; } requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); if (K9.getK9ComposerThemeSetting() != K9.Theme.USE_GLOBAL) { // theme the whole content according to the theme (except the action bar) ContextThemeWrapper themeContext = new ContextThemeWrapper(this, K9.getK9ThemeResourceId(K9.getK9ComposerTheme())); @SuppressLint("InflateParams") // this is the top level activity element, it has no root View v = LayoutInflater.from(themeContext).inflate(R.layout.message_compose, null); TypedValue outValue = new TypedValue(); // background color needs to be forced themeContext.getTheme().resolveAttribute(R.attr.messageViewBackgroundColor, outValue, true); v.setBackgroundColor(outValue.data); setContentView(v); } else { setContentView(R.layout.message_compose); } final Intent intent = getIntent(); mMessageReference = intent.getParcelableExtra(EXTRA_MESSAGE_REFERENCE); mSourceMessageBody = intent.getStringExtra(EXTRA_MESSAGE_BODY); if (K9.DEBUG && mSourceMessageBody != null) { Log.d(K9.LOG_TAG, "Composing message with explicitly specified message body."); } final String accountUuid = (mMessageReference != null) ? mMessageReference.getAccountUuid() : intent.getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); if (mAccount == null) { mAccount = Preferences.getPreferences(this).getDefaultAccount(); } if (mAccount == null) { /* * There are no accounts set up. This should not have happened. Prompt the * user to set up an account as an acceptable bailout. */ startActivity(new Intent(this, Accounts.class)); draftNeedsSaving = false; finish(); return; } mContacts = Contacts.getInstance(MessageCompose.this); mChooseIdentityButton = (TextView) findViewById(R.id.identity); mChooseIdentityButton.setOnClickListener(this); RecipientMvpView recipientMvpView = new RecipientMvpView(this); recipientPresenter = new RecipientPresenter(this, recipientMvpView, mAccount); mSubjectView = (EditText) findViewById(R.id.subject); mSubjectView.getInputExtras(true).putBoolean("allowEmoji", true); EolConvertingEditText upperSignature = (EolConvertingEditText)findViewById(R.id.upper_signature); EolConvertingEditText lowerSignature = (EolConvertingEditText)findViewById(R.id.lower_signature); mMessageContentView = (EolConvertingEditText)findViewById(R.id.message_content); mMessageContentView.getInputExtras(true).putBoolean("allowEmoji", true); mAttachments = (LinearLayout)findViewById(R.id.attachments); mQuotedTextShow = (Button)findViewById(R.id.quoted_text_show); mQuotedTextBar = findViewById(R.id.quoted_text_bar); mQuotedTextEdit = (ImageButton)findViewById(R.id.quoted_text_edit); ImageButton mQuotedTextDelete = (ImageButton) findViewById(R.id.quoted_text_delete); mQuotedText = (EolConvertingEditText)findViewById(R.id.quoted_text); mQuotedText.getInputExtras(true).putBoolean("allowEmoji", true); mQuotedHTML = (MessageWebView) findViewById(R.id.quoted_html); mQuotedHTML.configure(); // Disable the ability to click links in the quoted HTML page. I think this is a nice feature, but if someone // feels this should be a preference (or should go away all together), I'm ok with that too. -achen 20101130 mQuotedHTML.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return true; } }); TextWatcher draftNeedsChangingTextWatcher = new SimpleTextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { draftNeedsSaving = true; } }; TextWatcher signTextWatcher = new SimpleTextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { draftNeedsSaving = true; mSignatureChanged = true; } }; recipientMvpView.addTextChangedListener(draftNeedsChangingTextWatcher); mSubjectView.addTextChangedListener(draftNeedsChangingTextWatcher); mMessageContentView.addTextChangedListener(draftNeedsChangingTextWatcher); mQuotedText.addTextChangedListener(draftNeedsChangingTextWatcher); /* * We set this to invisible by default. Other methods will turn it back on if it's * needed. */ showOrHideQuotedText(QuotedTextMode.NONE); mSubjectView.setOnFocusChangeListener(this); mMessageContentView.setOnFocusChangeListener(this); mQuotedTextShow.setOnClickListener(this); mQuotedTextEdit.setOnClickListener(this); mQuotedTextDelete.setOnClickListener(this); if (savedInstanceState != null) { /* * This data gets used in onCreate, so grab it here instead of onRestoreInstanceState */ mSourceMessageProcessed = savedInstanceState.getBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, false); } if (initFromIntent(intent)) { mAction = Action.COMPOSE; draftNeedsSaving = true; } else { String action = intent.getAction(); if (ACTION_COMPOSE.equals(action)) { mAction = Action.COMPOSE; } else if (ACTION_REPLY.equals(action)) { mAction = Action.REPLY; } else if (ACTION_REPLY_ALL.equals(action)) { mAction = Action.REPLY_ALL; } else if (ACTION_FORWARD.equals(action)) { mAction = Action.FORWARD; } else if (ACTION_EDIT_DRAFT.equals(action)) { mAction = Action.EDIT_DRAFT; } else { // This shouldn't happen Log.w(K9.LOG_TAG, "MessageCompose was started with an unsupported action"); mAction = Action.COMPOSE; } } if (mIdentity == null) { mIdentity = mAccount.getIdentity(0); } if (mAccount.isSignatureBeforeQuotedText()) { mSignatureView = upperSignature; lowerSignature.setVisibility(View.GONE); } else { mSignatureView = lowerSignature; upperSignature.setVisibility(View.GONE); } updateSignature(); mSignatureView.addTextChangedListener(signTextWatcher); if (!mIdentity.getSignatureUse()) { mSignatureView.setVisibility(View.GONE); } mReadReceipt = mAccount.isMessageReadReceiptAlways(); mQuoteStyle = mAccount.getQuoteStyle(); updateFrom(); if (!mSourceMessageProcessed) { if (mAction == Action.REPLY || mAction == Action.REPLY_ALL || mAction == Action.FORWARD || mAction == Action.EDIT_DRAFT) { /* * If we need to load the message we add ourself as a message listener here * so we can kick it off. Normally we add in onResume but we don't * want to reload the message every time the activity is resumed. * There is no harm in adding twice. */ MessagingController.getInstance(getApplication()).addListener(mListener); final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.getAccountUuid()); final String folderName = mMessageReference.getFolderName(); final String sourceMessageUid = mMessageReference.getUid(); MessagingController.getInstance(getApplication()).loadMessageForView(account, folderName, sourceMessageUid, null); } if (mAction != Action.EDIT_DRAFT) { String alwaysBccString = mAccount.getAlwaysBcc(); if (!TextUtils.isEmpty(alwaysBccString)) { recipientPresenter.addBccAddresses(Address.parse(alwaysBccString)); } } } if (mAction == Action.REPLY || mAction == Action.REPLY_ALL) { mMessageReference = mMessageReference.withModifiedFlag(Flag.ANSWERED); } if (mAction == Action.REPLY || mAction == Action.REPLY_ALL || mAction == Action.EDIT_DRAFT) { //change focus to message body. mMessageContentView.requestFocus(); } else { // Explicitly set focus to "To:" input field (see issue 2998) recipientMvpView.requestFocusOnToField(); } if (mAction == Action.FORWARD) { mMessageReference = mMessageReference.withModifiedFlag(Flag.FORWARDED); } mOpenPgpProvider = mAccount.getOpenPgpProvider(); if (isCryptoProviderEnabled()) { // attachKeyCheckBox = (CheckBox) findViewById(R.id.cb_attach_key); // attachKeyCheckBox.setEnabled(mAccount.getCryptoKey() != 0); mOpenPgpServiceConnection = new OpenPgpServiceConnection(this, mOpenPgpProvider, new OnBound() { @Override public void onBound(IOpenPgpService2 service) { recipientPresenter.onCryptoProviderBound(); } @Override public void onError(Exception e) { recipientPresenter.onCryptoProviderError(e); } }); mOpenPgpServiceConnection.bindToService(); updateMessageFormat(); } // Set font size of input controls int fontSize = mFontSizes.getMessageComposeInput(); recipientMvpView.setFontSizes(mFontSizes, fontSize); mFontSizes.setViewTextSize(mSubjectView, fontSize); mFontSizes.setViewTextSize(mMessageContentView, fontSize); mFontSizes.setViewTextSize(mQuotedText, fontSize); mFontSizes.setViewTextSize(mSignatureView, fontSize); updateMessageFormat(); setTitle(); currentMessageBuilder = (MessageBuilder) getLastNonConfigurationInstance(); if (currentMessageBuilder != null) { setProgressBarIndeterminateVisibility(true); currentMessageBuilder.reattachCallback(this); } } @Override public void onDestroy() { super.onDestroy(); if (mOpenPgpServiceConnection != null) { mOpenPgpServiceConnection.unbindFromService(); } } /** * Handle external intents that trigger the message compose activity. * * <p> * Supported external intents: * <ul> * <li>{@link Intent#ACTION_VIEW}</li> * <li>{@link Intent#ACTION_SENDTO}</li> * <li>{@link Intent#ACTION_SEND}</li> * <li>{@link Intent#ACTION_SEND_MULTIPLE}</li> * </ul> * </p> * * @param intent * The (external) intent that started the activity. * * @return {@code true}, if this activity was started by an external intent. {@code false}, * otherwise. */ private boolean initFromIntent(final Intent intent) { boolean startedByExternalIntent = false; final String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SENDTO.equals(action)) { /* * Someone has clicked a mailto: link. The address is in the URI. */ if (intent.getData() != null) { Uri uri = intent.getData(); if (MailTo.isMailTo(uri)) { MailTo mailTo = MailTo.parse(uri); initializeFromMailto(mailTo); } } /* * Note: According to the documentation ACTION_VIEW and ACTION_SENDTO don't accept * EXTRA_* parameters. * And previously we didn't process these EXTRAs. But it looks like nobody bothers to * read the official documentation and just copies wrong sample code that happens to * work with the AOSP Email application. And because even big players get this wrong, * we're now finally giving in and read the EXTRAs for those actions (below). */ } if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action) || Intent.ACTION_SENDTO.equals(action) || Intent.ACTION_VIEW.equals(action)) { startedByExternalIntent = true; /* * Note: Here we allow a slight deviation from the documented behavior. * EXTRA_TEXT is used as message body (if available) regardless of the MIME * type of the intent. In addition one or multiple attachments can be added * using EXTRA_STREAM. */ CharSequence text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT); // Only use EXTRA_TEXT if the body hasn't already been set by the mailto URI if (text != null && mMessageContentView.getText().length() == 0) { mMessageContentView.setCharacters(text); } String type = intent.getType(); if (Intent.ACTION_SEND.equals(action)) { Uri stream = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (stream != null) { addAttachment(stream, type); } } else { List<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (list != null) { for (Parcelable parcelable : list) { Uri stream = (Uri) parcelable; if (stream != null) { addAttachment(stream, type); } } } } String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); // Only use EXTRA_SUBJECT if the subject hasn't already been set by the mailto URI if (subject != null && mSubjectView.getText().length() == 0) { mSubjectView.setText(subject); } recipientPresenter.initFromSendOrViewIntent(intent); } return startedByExternalIntent; } @Override public void onResume() { super.onResume(); MessagingController.getInstance(getApplication()).addListener(mListener); } @Override public void onPause() { super.onPause(); MessagingController.getInstance(getApplication()).removeListener(mListener); boolean isPausingOnConfigurationChange = (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == ActivityInfo.CONFIG_ORIENTATION; boolean isCurrentlyBuildingMessage = currentMessageBuilder != null; if (isPausingOnConfigurationChange || isCurrentlyBuildingMessage || isInSubActivity) { return; } checkToSaveDraftImplicitly(); } /** * The framework handles most of the fields, but we need to handle stuff that we * dynamically show and hide: * Attachment list, * Cc field, * Bcc field, * Quoted text, */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_KEY_NUM_ATTACHMENTS_LOADING, mNumAttachmentsLoading); outState.putString(STATE_KEY_WAITING_FOR_ATTACHMENTS, mWaitingForAttachments.name()); outState.putParcelableArrayList(STATE_KEY_ATTACHMENTS, createAttachmentList()); outState.putSerializable(STATE_KEY_QUOTED_TEXT_MODE, mQuotedTextMode); outState.putBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, mSourceMessageProcessed); outState.putLong(STATE_KEY_DRAFT_ID, mDraftId); outState.putSerializable(STATE_IDENTITY, mIdentity); outState.putBoolean(STATE_IDENTITY_CHANGED, mIdentityChanged); outState.putString(STATE_IN_REPLY_TO, mInReplyTo); outState.putString(STATE_REFERENCES, mReferences); outState.putSerializable(STATE_KEY_HTML_QUOTE, mQuotedHtmlContent); outState.putBoolean(STATE_KEY_READ_RECEIPT, mReadReceipt); outState.putBoolean(STATE_KEY_DRAFT_NEEDS_SAVING, draftNeedsSaving); outState.putBoolean(STATE_KEY_FORCE_PLAIN_TEXT, mForcePlainText); outState.putSerializable(STATE_KEY_QUOTED_TEXT_FORMAT, mQuotedTextFormat); recipientPresenter.onSaveInstanceState(outState); } @Override public Object onRetainNonConfigurationInstance() { if (currentMessageBuilder != null) { currentMessageBuilder.detachCallback(); } return currentMessageBuilder; } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mAttachments.removeAllViews(); mMaxLoaderId = 0; mNumAttachmentsLoading = savedInstanceState.getInt(STATE_KEY_NUM_ATTACHMENTS_LOADING); mWaitingForAttachments = WaitingAction.NONE; try { String waitingFor = savedInstanceState.getString(STATE_KEY_WAITING_FOR_ATTACHMENTS); mWaitingForAttachments = WaitingAction.valueOf(waitingFor); } catch (Exception e) { Log.w(K9.LOG_TAG, "Couldn't read value \" + STATE_KEY_WAITING_FOR_ATTACHMENTS +" + "\" from saved instance state", e); } List<Attachment> attachments = savedInstanceState.getParcelableArrayList(STATE_KEY_ATTACHMENTS); // noinspection ConstantConditions, we know this is set in onSaveInstanceState for (Attachment attachment : attachments) { addAttachmentView(attachment); if (attachment.loaderId > mMaxLoaderId) { mMaxLoaderId = attachment.loaderId; } if (attachment.state == Attachment.LoadingState.URI_ONLY) { initAttachmentInfoLoader(attachment); } else if (attachment.state == Attachment.LoadingState.METADATA) { initAttachmentContentLoader(attachment); } } mReadReceipt = savedInstanceState.getBoolean(STATE_KEY_READ_RECEIPT); recipientPresenter.onRestoreInstanceState(savedInstanceState); mQuotedHtmlContent = (InsertableHtmlContent) savedInstanceState.getSerializable(STATE_KEY_HTML_QUOTE); if (mQuotedHtmlContent != null && mQuotedHtmlContent.getQuotedContent() != null) { mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent()); } mDraftId = savedInstanceState.getLong(STATE_KEY_DRAFT_ID); mIdentity = (Identity)savedInstanceState.getSerializable(STATE_IDENTITY); mIdentityChanged = savedInstanceState.getBoolean(STATE_IDENTITY_CHANGED); mInReplyTo = savedInstanceState.getString(STATE_IN_REPLY_TO); mReferences = savedInstanceState.getString(STATE_REFERENCES); draftNeedsSaving = savedInstanceState.getBoolean(STATE_KEY_DRAFT_NEEDS_SAVING); mForcePlainText = savedInstanceState.getBoolean(STATE_KEY_FORCE_PLAIN_TEXT); mQuotedTextFormat = (SimpleMessageFormat) savedInstanceState.getSerializable( STATE_KEY_QUOTED_TEXT_FORMAT); showOrHideQuotedText( (QuotedTextMode) savedInstanceState.getSerializable(STATE_KEY_QUOTED_TEXT_MODE)); updateFrom(); updateMessageFormat(); } private void setTitle() { switch (mAction) { case REPLY: { setTitle(R.string.compose_title_reply); break; } case REPLY_ALL: { setTitle(R.string.compose_title_reply_all); break; } case FORWARD: { setTitle(R.string.compose_title_forward); break; } case COMPOSE: default: { setTitle(R.string.compose_title_compose); break; } } } @Nullable private MessageBuilder createMessageBuilder(boolean isDraft) { MessageBuilder builder; if (!recipientPresenter.canSendOrError(isDraft)) { return null; } ComposeCryptoStatus cryptoStatus = recipientPresenter.getCurrentCryptoStatus(); // TODO encrypt drafts for storage if(!isDraft && cryptoStatus.shouldUsePgpMessageBuilder()) { PgpMessageBuilder pgpBuilder = new PgpMessageBuilder(getApplicationContext(), getOpenPgpApi()); pgpBuilder.setCryptoStatus(cryptoStatus); builder = pgpBuilder; } else { builder = new SimpleMessageBuilder(getApplicationContext()); } builder.setSubject(mSubjectView.getText().toString()) .setTo(recipientPresenter.getToAddresses()) .setCc(recipientPresenter.getCcAddresses()) .setBcc(recipientPresenter.getBccAddresses()) .setInReplyTo(mInReplyTo) .setReferences(mReferences) .setRequestReadReceipt(mReadReceipt) .setIdentity(mIdentity) .setMessageFormat(mMessageFormat) .setText(mMessageContentView.getCharacters()) .setAttachments(createAttachmentList()) .setSignature(mSignatureView.getCharacters()) .setQuoteStyle(mQuoteStyle) .setQuotedTextMode(mQuotedTextMode) .setQuotedText(mQuotedText.getCharacters()) .setQuotedHtmlContent(mQuotedHtmlContent) .setReplyAfterQuote(mAccount.isReplyAfterQuote()) .setSignatureBeforeQuotedText(mAccount.isSignatureBeforeQuotedText()) .setIdentityChanged(mIdentityChanged) .setSignatureChanged(mSignatureChanged) .setCursorPosition(mMessageContentView.getSelectionStart()) .setMessageReference(mMessageReference) .setDraft(isDraft); return builder; } private void checkToSendMessage() { if (recipientPresenter.checkRecipientsOkForSending()) { return; } if (mWaitingForAttachments != WaitingAction.NONE) { return; } if (mNumAttachmentsLoading > 0) { mWaitingForAttachments = WaitingAction.SEND; showWaitingForAttachmentDialog(); return; } performSendAfterChecks(); } private void checkToSaveDraftAndSave() { if (!mAccount.hasDraftsFolder()) { Toast.makeText(this, R.string.compose_error_no_draft_folder, Toast.LENGTH_SHORT).show(); return; } if (mWaitingForAttachments != WaitingAction.NONE) { return; } if (mNumAttachmentsLoading > 0) { mWaitingForAttachments = WaitingAction.SAVE; showWaitingForAttachmentDialog(); return; } mFinishAfterDraftSaved = true; performSaveAfterChecks(); } private void checkToSaveDraftImplicitly() { if (!mAccount.hasDraftsFolder()) { return; } if (!draftNeedsSaving) { return; } mFinishAfterDraftSaved = false; performSaveAfterChecks(); } private void performSaveAfterChecks() { currentMessageBuilder = createMessageBuilder(true); if (currentMessageBuilder != null) { setProgressBarIndeterminateVisibility(true); currentMessageBuilder.buildAsync(this); } } public void performSendAfterChecks() { currentMessageBuilder = createMessageBuilder(false); if (currentMessageBuilder != null) { draftNeedsSaving = false; setProgressBarIndeterminateVisibility(true); currentMessageBuilder.buildAsync(this); } } private void onDiscard() { if (mDraftId != INVALID_DRAFT_ID) { MessagingController.getInstance(getApplication()).deleteDraft(mAccount, mDraftId); mDraftId = INVALID_DRAFT_ID; } mHandler.sendEmptyMessage(MSG_DISCARDED_DRAFT); draftNeedsSaving = false; finish(); } private void onReadReceipt() { CharSequence txt; if (!mReadReceipt) { txt = getString(R.string.read_receipt_enabled); mReadReceipt = true; } else { txt = getString(R.string.read_receipt_disabled); mReadReceipt = false; } Context context = getApplicationContext(); Toast toast = Toast.makeText(context, txt, Toast.LENGTH_SHORT); toast.show(); } private ArrayList<Attachment> createAttachmentList() { ArrayList<Attachment> attachments = new ArrayList<>(); for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) { View view = mAttachments.getChildAt(i); Attachment attachment = (Attachment) view.getTag(); attachments.add(attachment); } return attachments; } /** * Kick off a picker for the specified MIME type and let Android take over. */ @SuppressLint("InlinedApi") private void onAddAttachment() { Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); isInSubActivity = true; startActivityForResult(Intent.createChooser(i, null), ACTIVITY_REQUEST_PICK_ATTACHMENT); } private void addAttachment(Uri uri) { addAttachment(uri, null); } private void addAttachment(Uri uri, String contentType) { Attachment attachment = new Attachment(); attachment.state = Attachment.LoadingState.URI_ONLY; attachment.uri = uri; attachment.contentType = contentType; attachment.loaderId = ++mMaxLoaderId; addAttachmentView(attachment); initAttachmentInfoLoader(attachment); } private void initAttachmentInfoLoader(Attachment attachment) { LoaderManager loaderManager = getLoaderManager(); Bundle bundle = new Bundle(); bundle.putParcelable(LOADER_ARG_ATTACHMENT, attachment); loaderManager.initLoader(attachment.loaderId, bundle, mAttachmentInfoLoaderCallback); } private void initAttachmentContentLoader(Attachment attachment) { LoaderManager loaderManager = getLoaderManager(); Bundle bundle = new Bundle(); bundle.putParcelable(LOADER_ARG_ATTACHMENT, attachment); loaderManager.initLoader(attachment.loaderId, bundle, mAttachmentContentLoaderCallback); } private void addAttachmentView(Attachment attachment) { boolean hasMetadata = (attachment.state != Attachment.LoadingState.URI_ONLY); boolean isLoadingComplete = (attachment.state == Attachment.LoadingState.COMPLETE); View view = getLayoutInflater().inflate(R.layout.message_compose_attachment, mAttachments, false); TextView nameView = (TextView) view.findViewById(R.id.attachment_name); View progressBar = view.findViewById(R.id.progressBar); if (hasMetadata) { nameView.setText(attachment.name); } else { nameView.setText(R.string.loading_attachment); } progressBar.setVisibility(isLoadingComplete ? View.GONE : View.VISIBLE); ImageButton delete = (ImageButton) view.findViewById(R.id.attachment_delete); delete.setOnClickListener(MessageCompose.this); delete.setTag(view); view.setTag(attachment); mAttachments.addView(view); } private View getAttachmentView(int loaderId) { for (int i = 0, childCount = mAttachments.getChildCount(); i < childCount; i++) { View view = mAttachments.getChildAt(i); Attachment tag = (Attachment) view.getTag(); if (tag != null && tag.loaderId == loaderId) { return view; } } return null; } private LoaderManager.LoaderCallbacks<Attachment> mAttachmentInfoLoaderCallback = new LoaderManager.LoaderCallbacks<Attachment>() { @Override public Loader<Attachment> onCreateLoader(int id, Bundle args) { onFetchAttachmentStarted(); Attachment attachment = args.getParcelable(LOADER_ARG_ATTACHMENT); return new AttachmentInfoLoader(MessageCompose.this, attachment); } @Override public void onLoadFinished(Loader<Attachment> loader, Attachment attachment) { int loaderId = loader.getId(); View view = getAttachmentView(loaderId); if (view != null) { view.setTag(attachment); TextView nameView = (TextView) view.findViewById(R.id.attachment_name); nameView.setText(attachment.name); attachment.loaderId = ++mMaxLoaderId; initAttachmentContentLoader(attachment); } else { onFetchAttachmentFinished(); } getLoaderManager().destroyLoader(loaderId); } @Override public void onLoaderReset(Loader<Attachment> loader) { onFetchAttachmentFinished(); } }; private LoaderManager.LoaderCallbacks<Attachment> mAttachmentContentLoaderCallback = new LoaderManager.LoaderCallbacks<Attachment>() { @Override public Loader<Attachment> onCreateLoader(int id, Bundle args) { Attachment attachment = args.getParcelable(LOADER_ARG_ATTACHMENT); return new AttachmentContentLoader(MessageCompose.this, attachment); } @Override public void onLoadFinished(Loader<Attachment> loader, Attachment attachment) { int loaderId = loader.getId(); View view = getAttachmentView(loaderId); if (view != null) { if (attachment.state == Attachment.LoadingState.COMPLETE) { view.setTag(attachment); View progressBar = view.findViewById(R.id.progressBar); progressBar.setVisibility(View.GONE); } else { mAttachments.removeView(view); } } onFetchAttachmentFinished(); getLoaderManager().destroyLoader(loaderId); } @Override public void onLoaderReset(Loader<Attachment> loader) { onFetchAttachmentFinished(); } }; public OpenPgpApi getOpenPgpApi() { return new OpenPgpApi(this, mOpenPgpServiceConnection.getService()); } private void onFetchAttachmentStarted() { mNumAttachmentsLoading += 1; } private void onFetchAttachmentFinished() { // We're not allowed to perform fragment transactions when called from onLoadFinished(). // So we use the Handler to call performStalledAction(). mHandler.sendEmptyMessage(MSG_PERFORM_STALLED_ACTION); } private void performStalledAction() { mNumAttachmentsLoading -= 1; WaitingAction waitingFor = mWaitingForAttachments; mWaitingForAttachments = WaitingAction.NONE; if (waitingFor != WaitingAction.NONE) { dismissWaitingForAttachmentDialog(); } switch (waitingFor) { case SEND: { performSendAfterChecks(); break; } case SAVE: { performSaveAfterChecks(); break; } case NONE: break; } } public void showContactPicker(int requestCode) { requestCode |= REQUEST_MASK_RECIPIENT_PRESENTER; isInSubActivity = true; startActivityForResult(mContacts.contactPickerIntent(), requestCode); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { isInSubActivity = false; if ((requestCode & REQUEST_MASK_MESSAGE_BUILDER) == REQUEST_MASK_MESSAGE_BUILDER) { requestCode ^= REQUEST_MASK_MESSAGE_BUILDER; if (currentMessageBuilder == null) { Log.e(K9.LOG_TAG, "Got a message builder activity result for no message builder, " + "this is an illegal state!"); return; } currentMessageBuilder.onActivityResult(this, requestCode, resultCode, data); return; } if ((requestCode & REQUEST_MASK_RECIPIENT_PRESENTER) == REQUEST_MASK_RECIPIENT_PRESENTER) { requestCode ^= REQUEST_MASK_RECIPIENT_PRESENTER; recipientPresenter.onActivityResult(resultCode, requestCode, data); return; } if (resultCode != RESULT_OK) { return; } if (data == null) { return; } switch (requestCode) { case ACTIVITY_REQUEST_PICK_ATTACHMENT: addAttachmentsFromResultIntent(data); draftNeedsSaving = true; break; } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void addAttachmentsFromResultIntent(Intent data) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { ClipData clipData = data.getClipData(); if (clipData != null) { for (int i = 0, end = clipData.getItemCount(); i < end; i++) { Uri uri = clipData.getItemAt(i).getUri(); if (uri != null) { addAttachment(uri); } } return; } } Uri uri = data.getData(); if (uri != null) { addAttachment(uri); } } private void onAccountChosen(Account account, Identity identity) { if (!mAccount.equals(account)) { if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Switching account from " + mAccount + " to " + account); } // on draft edit, make sure we don't keep previous message UID if (mAction == Action.EDIT_DRAFT) { mMessageReference = null; } // test whether there is something to save if (draftNeedsSaving || (mDraftId != INVALID_DRAFT_ID)) { final long previousDraftId = mDraftId; final Account previousAccount = mAccount; // make current message appear as new mDraftId = INVALID_DRAFT_ID; // actual account switch mAccount = account; if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Account switch, saving new draft in new account"); } checkToSaveDraftImplicitly(); if (previousDraftId != INVALID_DRAFT_ID) { if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Account switch, deleting draft from previous account: " + previousDraftId); } MessagingController.getInstance(getApplication()).deleteDraft(previousAccount, previousDraftId); } } else { mAccount = account; } // Show CC/BCC text input field when switching to an account that always wants them // displayed. // Please note that we're not hiding the fields if the user switches back to an account // that doesn't have this setting checked. recipientPresenter.onSwitchAccount(mAccount); // not sure how to handle mFolder, mSourceMessage? } switchToIdentity(identity); } private void switchToIdentity(Identity identity) { mIdentity = identity; mIdentityChanged = true; draftNeedsSaving = true; updateFrom(); updateSignature(); updateMessageFormat(); recipientPresenter.onSwitchIdentity(identity); } private void updateFrom() { mChooseIdentityButton.setText(mIdentity.getEmail()); } private void updateSignature() { if (mIdentity.getSignatureUse()) { mSignatureView.setCharacters(mIdentity.getSignature()); mSignatureView.setVisibility(View.VISIBLE); } else { mSignatureView.setVisibility(View.GONE); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.attachment_delete: /* * The view is the delete button, and we have previously set the tag of * the delete button to the view that owns it. We don't use parent because the * view is very complex and could change in the future. */ mAttachments.removeView((View) view.getTag()); draftNeedsSaving = true; break; case R.id.quoted_text_show: showOrHideQuotedText(QuotedTextMode.SHOW); updateMessageFormat(); draftNeedsSaving = true; break; case R.id.quoted_text_delete: showOrHideQuotedText(QuotedTextMode.HIDE); updateMessageFormat(); draftNeedsSaving = true; break; case R.id.quoted_text_edit: mForcePlainText = true; if (mMessageReference != null) { // shouldn't happen... // TODO - Should we check if mSourceMessageBody is already present and bypass the MessagingController call? MessagingController.getInstance(getApplication()).addListener(mListener); final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.getAccountUuid()); final String folderName = mMessageReference.getFolderName(); final String sourceMessageUid = mMessageReference.getUid(); MessagingController.getInstance(getApplication()).loadMessageForView(account, folderName, sourceMessageUid, null); } break; case R.id.identity: showDialog(DIALOG_CHOOSE_IDENTITY); break; } } /** * Show or hide the quoted text. * * @param mode * The value to set {@link #mQuotedTextMode} to. */ private void showOrHideQuotedText(QuotedTextMode mode) { mQuotedTextMode = mode; switch (mode) { case NONE: case HIDE: { if (mode == QuotedTextMode.NONE) { mQuotedTextShow.setVisibility(View.GONE); } else { mQuotedTextShow.setVisibility(View.VISIBLE); } mQuotedTextBar.setVisibility(View.GONE); mQuotedText.setVisibility(View.GONE); mQuotedHTML.setVisibility(View.GONE); mQuotedTextEdit.setVisibility(View.GONE); break; } case SHOW: { mQuotedTextShow.setVisibility(View.GONE); mQuotedTextBar.setVisibility(View.VISIBLE); if (mQuotedTextFormat == SimpleMessageFormat.HTML) { mQuotedText.setVisibility(View.GONE); mQuotedHTML.setVisibility(View.VISIBLE); mQuotedTextEdit.setVisibility(View.VISIBLE); } else { mQuotedText.setVisibility(View.VISIBLE); mQuotedHTML.setVisibility(View.GONE); mQuotedTextEdit.setVisibility(View.GONE); } break; } } } private void askBeforeDiscard(){ if (K9.confirmDiscardMessage()) { showDialog(DIALOG_CONFIRM_DISCARD); } else { onDiscard(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.send: checkToSendMessage(); break; case R.id.save: checkToSaveDraftAndSave(); break; case R.id.discard: askBeforeDiscard(); break; case R.id.add_from_contacts: recipientPresenter.onMenuAddFromContacts(); break; case R.id.add_attachment: onAddAttachment(); break; case R.id.read_receipt: onReadReceipt(); break; default: return super.onOptionsItemSelected(item); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.message_compose_option, menu); // Disable the 'Save' menu option if Drafts folder is set to -NONE- if (!mAccount.hasDraftsFolder()) { menu.findItem(R.id.save).setEnabled(false); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); recipientPresenter.onPrepareOptionsMenu(menu); return true; } @Override public void onBackPressed() { if (draftNeedsSaving) { if (!mAccount.hasDraftsFolder()) { showDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); } else { showDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); } } else { // Check if editing an existing draft. if (mDraftId == INVALID_DRAFT_ID) { onDiscard(); } else { super.onBackPressed(); } } } private void showWaitingForAttachmentDialog() { String title; switch (mWaitingForAttachments) { case SEND: { title = getString(R.string.fetching_attachment_dialog_title_send); break; } case SAVE: { title = getString(R.string.fetching_attachment_dialog_title_save); break; } default: { return; } } ProgressDialogFragment fragment = ProgressDialogFragment.newInstance(title, getString(R.string.fetching_attachment_dialog_message)); fragment.show(getFragmentManager(), FRAGMENT_WAITING_FOR_ATTACHMENT); } public void onCancel(ProgressDialogFragment fragment) { attachmentProgressDialogCancelled(); } void attachmentProgressDialogCancelled() { mWaitingForAttachments = WaitingAction.NONE; } private void dismissWaitingForAttachmentDialog() { ProgressDialogFragment fragment = (ProgressDialogFragment) getFragmentManager().findFragmentByTag(FRAGMENT_WAITING_FOR_ATTACHMENT); if (fragment != null) { fragment.dismiss(); } } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE: return new AlertDialog.Builder(this) .setTitle(R.string.save_or_discard_draft_message_dlg_title) .setMessage(R.string.save_or_discard_draft_message_instructions_fmt) .setPositiveButton(R.string.save_draft_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); checkToSaveDraftAndSave(); } }) .setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); onDiscard(); } }) .create(); case DIALOG_CONFIRM_DISCARD_ON_BACK: return new AlertDialog.Builder(this) .setTitle(R.string.confirm_discard_draft_message_title) .setMessage(R.string.confirm_discard_draft_message) .setPositiveButton(R.string.cancel_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); } }) .setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); Toast.makeText(MessageCompose.this, getString(R.string.message_discarded_toast), Toast.LENGTH_LONG).show(); onDiscard(); } }) .create(); case DIALOG_CHOOSE_IDENTITY: Context context = new ContextThemeWrapper(this, (K9.getK9Theme() == K9.Theme.LIGHT) ? R.style.Theme_K9_Dialog_Light : R.style.Theme_K9_Dialog_Dark); Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.send_as); final IdentityAdapter adapter = new IdentityAdapter(context); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { IdentityContainer container = (IdentityContainer) adapter.getItem(which); onAccountChosen(container.account, container.identity); } }); return builder.create(); case DIALOG_CONFIRM_DISCARD: { return new AlertDialog.Builder(this) .setTitle(R.string.dialog_confirm_delete_title) .setMessage(R.string.dialog_confirm_delete_message) .setPositiveButton(R.string.dialog_confirm_delete_confirm_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { onDiscard(); } }) .setNegativeButton(R.string.dialog_confirm_delete_cancel_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .create(); } } return super.onCreateDialog(id); } /** * Add all attachments of an existing message as if they were added by hand. * * @param part * The message part to check for being an attachment. This method will recurse if it's * a multipart part. * @param depth * The recursion depth. Currently unused. * * @return {@code true} if all attachments were able to be attached, {@code false} otherwise. * * @throws MessagingException * In case of an error */ private boolean loadAttachments(Part part, int depth) throws MessagingException { if (part.getBody() instanceof Multipart) { Multipart mp = (Multipart) part.getBody(); boolean ret = true; for (int i = 0, count = mp.getCount(); i < count; i++) { if (!loadAttachments(mp.getBodyPart(i), depth + 1)) { ret = false; } } return ret; } String contentType = MimeUtility.unfoldAndDecode(part.getContentType()); String name = MimeUtility.getHeaderParameter(contentType, "name"); if (name != null) { if (part instanceof LocalBodyPart) { LocalBodyPart localBodyPart = (LocalBodyPart) part; String accountUuid = localBodyPart.getAccountUuid(); long attachmentId = localBodyPart.getId(); Uri uri = AttachmentProvider.getAttachmentUri(accountUuid, attachmentId); addAttachment(uri); return true; } return false; } return true; } /** * Pull out the parts of the now loaded source message and apply them to the new message * depending on the type of message being composed. * * @param message * The source message used to populate the various text fields. */ private void processSourceMessage(LocalMessage message) { try { switch (mAction) { case REPLY: case REPLY_ALL: { processMessageToReplyTo(message); break; } case FORWARD: { processMessageToForward(message); break; } case EDIT_DRAFT: { processDraftMessage(message); break; } default: { Log.w(K9.LOG_TAG, "processSourceMessage() called with unsupported action"); break; } } } catch (MessagingException me) { /** * Let the user continue composing their message even if we have a problem processing * the source message. Log it as an error, though. */ Log.e(K9.LOG_TAG, "Error while processing source message: ", me); } finally { mSourceMessageProcessed = true; draftNeedsSaving = false; } updateMessageFormat(); } private void processMessageToReplyTo(Message message) throws MessagingException { if (message.getSubject() != null) { final String subject = PREFIX.matcher(message.getSubject()).replaceFirst(""); if (!subject.toLowerCase(Locale.US).startsWith("re:")) { mSubjectView.setText("Re: " + subject); } else { mSubjectView.setText(subject); } } else { mSubjectView.setText(""); } /* * If a reply-to was included with the message use that, otherwise use the from * or sender address. */ recipientPresenter.initFromReplyToMessage(message); if (message.getMessageId() != null && message.getMessageId().length() > 0) { mInReplyTo = message.getMessageId(); String[] refs = message.getReferences(); if (refs != null && refs.length > 0) { mReferences = TextUtils.join("", refs) + " " + mInReplyTo; } else { mReferences = mInReplyTo; } } else { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "could not get Message-ID."); } } // Quote the message and setup the UI. populateUIWithQuotedMessage(mAccount.isDefaultQuotedTextShown()); if (mAction == Action.REPLY || mAction == Action.REPLY_ALL) { Identity useIdentity = IdentityHelper.getRecipientIdentityFromMessage(mAccount, message); Identity defaultIdentity = mAccount.getIdentity(0); if (useIdentity != defaultIdentity) { switchToIdentity(useIdentity); } } } private void processMessageToForward(Message message) throws MessagingException { String subject = message.getSubject(); if (subject != null && !subject.toLowerCase(Locale.US).startsWith("fwd:")) { mSubjectView.setText("Fwd: " + subject); } else { mSubjectView.setText(subject); } mQuoteStyle = QuoteStyle.HEADER; // "Be Like Thunderbird" - on forwarded messages, set the message ID // of the forwarded message in the references and the reply to. TB // only includes ID of the message being forwarded in the reference, // even if there are multiple references. if (!TextUtils.isEmpty(message.getMessageId())) { mInReplyTo = message.getMessageId(); mReferences = mInReplyTo; } else { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "could not get Message-ID."); } } // Quote the message and setup the UI. populateUIWithQuotedMessage(true); if (!mSourceMessageProcessed) { if (message.isSet(Flag.X_DOWNLOADED_PARTIAL) || !loadAttachments(message, 0)) { mHandler.sendEmptyMessage(MSG_SKIPPED_ATTACHMENTS); } } } private void processDraftMessage(LocalMessage message) throws MessagingException { String showQuotedTextMode = "NONE"; mDraftId = MessagingController.getInstance(getApplication()).getId(message); mSubjectView.setText(message.getSubject()); recipientPresenter.initFromDraftMessage(message); // Read In-Reply-To header from draft final String[] inReplyTo = message.getHeader("In-Reply-To"); if (inReplyTo.length >= 1) { mInReplyTo = inReplyTo[0]; } // Read References header from draft final String[] references = message.getHeader("References"); if (references.length >= 1) { mReferences = references[0]; } if (!mSourceMessageProcessed) { loadAttachments(message, 0); } // Decode the identity header when loading a draft. // See buildIdentityHeader(TextBody) for a detailed description of the composition of this blob. Map<IdentityField, String> k9identity = new HashMap<>(); String[] identityHeaders = message.getHeader(K9.IDENTITY_HEADER); if (identityHeaders.length > 0 && identityHeaders[0] != null) { k9identity = IdentityHeaderParser.parse(identityHeaders[0]); } Identity newIdentity = new Identity(); if (k9identity.containsKey(IdentityField.SIGNATURE)) { newIdentity.setSignatureUse(true); newIdentity.setSignature(k9identity.get(IdentityField.SIGNATURE)); mSignatureChanged = true; } else { newIdentity.setSignatureUse(message.getFolder().getSignatureUse()); newIdentity.setSignature(mIdentity.getSignature()); } if (k9identity.containsKey(IdentityField.NAME)) { newIdentity.setName(k9identity.get(IdentityField.NAME)); mIdentityChanged = true; } else { newIdentity.setName(mIdentity.getName()); } if (k9identity.containsKey(IdentityField.EMAIL)) { newIdentity.setEmail(k9identity.get(IdentityField.EMAIL)); mIdentityChanged = true; } else { newIdentity.setEmail(mIdentity.getEmail()); } if (k9identity.containsKey(IdentityField.ORIGINAL_MESSAGE)) { mMessageReference = null; try { String originalMessage = k9identity.get(IdentityField.ORIGINAL_MESSAGE); MessageReference messageReference = new MessageReference(originalMessage); // Check if this is a valid account in our database Preferences prefs = Preferences.getPreferences(getApplicationContext()); Account account = prefs.getAccount(messageReference.getAccountUuid()); if (account != null) { mMessageReference = messageReference; } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Could not decode message reference in identity.", e); } } int cursorPosition = 0; if (k9identity.containsKey(IdentityField.CURSOR_POSITION)) { try { cursorPosition = Integer.parseInt(k9identity.get(IdentityField.CURSOR_POSITION)); } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not parse cursor position for MessageCompose; continuing.", e); } } if (k9identity.containsKey(IdentityField.QUOTED_TEXT_MODE)) { showQuotedTextMode = k9identity.get(IdentityField.QUOTED_TEXT_MODE); } mIdentity = newIdentity; updateSignature(); updateFrom(); Integer bodyLength = k9identity.get(IdentityField.LENGTH) != null ? Integer.valueOf(k9identity.get(IdentityField.LENGTH)) : 0; Integer bodyOffset = k9identity.get(IdentityField.OFFSET) != null ? Integer.valueOf(k9identity.get(IdentityField.OFFSET)) : 0; Integer bodyFooterOffset = k9identity.get(IdentityField.FOOTER_OFFSET) != null ? Integer.valueOf(k9identity.get(IdentityField.FOOTER_OFFSET)) : null; Integer bodyPlainLength = k9identity.get(IdentityField.PLAIN_LENGTH) != null ? Integer.valueOf(k9identity.get(IdentityField.PLAIN_LENGTH)) : null; Integer bodyPlainOffset = k9identity.get(IdentityField.PLAIN_OFFSET) != null ? Integer.valueOf(k9identity.get(IdentityField.PLAIN_OFFSET)) : null; mQuoteStyle = k9identity.get(IdentityField.QUOTE_STYLE) != null ? QuoteStyle.valueOf(k9identity.get(IdentityField.QUOTE_STYLE)) : mAccount.getQuoteStyle(); QuotedTextMode quotedMode; try { quotedMode = QuotedTextMode.valueOf(showQuotedTextMode); } catch (Exception e) { quotedMode = QuotedTextMode.NONE; } // Always respect the user's current composition format preference, even if the // draft was saved in a different format. // TODO - The current implementation doesn't allow a user in HTML mode to edit a draft that wasn't saved with K9mail. String messageFormatString = k9identity.get(IdentityField.MESSAGE_FORMAT); MessageFormat messageFormat = null; if (messageFormatString != null) { try { messageFormat = MessageFormat.valueOf(messageFormatString); } catch (Exception e) { /* do nothing */ } } if (messageFormat == null) { // This message probably wasn't created by us. The exception is legacy // drafts created before the advent of HTML composition. In those cases, // we'll display the whole message (including the quoted part) in the // composition window. If that's the case, try and convert it to text to // match the behavior in text mode. mMessageContentView.setCharacters(getBodyTextFromMessage(message, SimpleMessageFormat.TEXT)); mForcePlainText = true; showOrHideQuotedText(quotedMode); return; } if (messageFormat == MessageFormat.HTML) { Part part = MimeUtility.findFirstPartByMimeType(message, "text/html"); if (part != null) { // Shouldn't happen if we were the one who saved it. mQuotedTextFormat = SimpleMessageFormat.HTML; String text = MessageExtractor.getTextFromPart(part); if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Loading message with offset " + bodyOffset + ", length " + bodyLength + ". Text length is " + text.length() + "."); } if (bodyOffset + bodyLength > text.length()) { // The draft was edited outside of K-9 Mail? Log.d(K9.LOG_TAG, "The identity field from the draft contains an invalid LENGTH/OFFSET"); bodyOffset = 0; bodyLength = 0; } // Grab our reply text. String bodyText = text.substring(bodyOffset, bodyOffset + bodyLength); mMessageContentView.setCharacters(HtmlConverter.htmlToText(bodyText)); // Regenerate the quoted html without our user content in it. StringBuilder quotedHTML = new StringBuilder(); quotedHTML.append(text.substring(0, bodyOffset)); // stuff before the reply quotedHTML.append(text.substring(bodyOffset + bodyLength)); if (quotedHTML.length() > 0) { mQuotedHtmlContent = new InsertableHtmlContent(); mQuotedHtmlContent.setQuotedContent(quotedHTML); // We don't know if bodyOffset refers to the header or to the footer mQuotedHtmlContent.setHeaderInsertionPoint(bodyOffset); if (bodyFooterOffset != null) { mQuotedHtmlContent.setFooterInsertionPoint(bodyFooterOffset); } else { mQuotedHtmlContent.setFooterInsertionPoint(bodyOffset); } mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent()); } } if (bodyPlainOffset != null && bodyPlainLength != null) { processSourceMessageText(message, bodyPlainOffset, bodyPlainLength, false); } } else if (messageFormat == MessageFormat.TEXT) { mQuotedTextFormat = SimpleMessageFormat.TEXT; processSourceMessageText(message, bodyOffset, bodyLength, true); } else { Log.e(K9.LOG_TAG, "Unhandled message format."); } // Set the cursor position if we have it. try { mMessageContentView.setSelection(cursorPosition); } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not set cursor position in MessageCompose; ignoring.", e); } showOrHideQuotedText(quotedMode); } /** * Pull out the parts of the now loaded source message and apply them to the new message * depending on the type of message being composed. * @param message Source message * @param bodyOffset Insertion point for reply. * @param bodyLength Length of reply. * @param viewMessageContent Update mMessageContentView or not. * @throws MessagingException */ private void processSourceMessageText(Message message, Integer bodyOffset, Integer bodyLength, boolean viewMessageContent) throws MessagingException { Part textPart = MimeUtility.findFirstPartByMimeType(message, "text/plain"); if (textPart != null) { String text = MessageExtractor.getTextFromPart(textPart); if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Loading message with offset " + bodyOffset + ", length " + bodyLength + ". Text length is " + text.length() + "."); } // If we had a body length (and it was valid), separate the composition from the quoted text // and put them in their respective places in the UI. if (bodyLength > 0) { try { String bodyText = text.substring(bodyOffset, bodyOffset + bodyLength); // Regenerate the quoted text without our user content in it nor added newlines. StringBuilder quotedText = new StringBuilder(); if (bodyOffset == 0 && text.substring(bodyLength, bodyLength + 4).equals("\r\n\r\n")) { // top-posting: ignore two newlines at start of quote quotedText.append(text.substring(bodyLength + 4)); } else if (bodyOffset + bodyLength == text.length() && text.substring(bodyOffset - 2, bodyOffset).equals("\r\n")) { // bottom-posting: ignore newline at end of quote quotedText.append(text.substring(0, bodyOffset - 2)); } else { quotedText.append(text.substring(0, bodyOffset)); // stuff before the reply quotedText.append(text.substring(bodyOffset + bodyLength)); } if (viewMessageContent) { mMessageContentView.setCharacters(bodyText); } mQuotedText.setCharacters(quotedText); } catch (IndexOutOfBoundsException e) { // Invalid bodyOffset or bodyLength. The draft was edited outside of K-9 Mail? Log.d(K9.LOG_TAG, "The identity field from the draft contains an invalid bodyOffset/bodyLength"); if (viewMessageContent) { mMessageContentView.setCharacters(text); } } } else { if (viewMessageContent) { mMessageContentView.setCharacters(text); } } } } // Regexes to check for signature. private static final Pattern DASH_SIGNATURE_PLAIN = Pattern.compile("\r\n-- \r\n.*", Pattern.DOTALL); private static final Pattern DASH_SIGNATURE_HTML = Pattern.compile("(<br( /)?>|\r?\n)-- <br( /)?>", Pattern.CASE_INSENSITIVE); private static final Pattern BLOCKQUOTE_START = Pattern.compile("<blockquote", Pattern.CASE_INSENSITIVE); private static final Pattern BLOCKQUOTE_END = Pattern.compile("</blockquote>", Pattern.CASE_INSENSITIVE); /** * Build and populate the UI with the quoted message. * * @param showQuotedText * {@code true} if the quoted text should be shown, {@code false} otherwise. * * @throws MessagingException */ private void populateUIWithQuotedMessage(boolean showQuotedText) throws MessagingException { MessageFormat origMessageFormat = mAccount.getMessageFormat(); if (mForcePlainText || origMessageFormat == MessageFormat.TEXT) { // Use plain text for the quoted message mQuotedTextFormat = SimpleMessageFormat.TEXT; } else if (origMessageFormat == MessageFormat.AUTO) { // Figure out which message format to use for the quoted text by looking if the source // message contains a text/html part. If it does, we use that. mQuotedTextFormat = (MimeUtility.findFirstPartByMimeType(mSourceMessage, "text/html") == null) ? SimpleMessageFormat.TEXT : SimpleMessageFormat.HTML; } else { mQuotedTextFormat = SimpleMessageFormat.HTML; } // TODO -- I am assuming that mSourceMessageBody will always be a text part. Is this a safe assumption? // Handle the original message in the reply // If we already have mSourceMessageBody, use that. It's pre-populated if we've got crypto going on. String content = (mSourceMessageBody != null) ? mSourceMessageBody : getBodyTextFromMessage(mSourceMessage, mQuotedTextFormat); if (mQuotedTextFormat == SimpleMessageFormat.HTML) { // Strip signature. // closing tags such as </div>, </span>, </table>, </pre> will be cut off. if (mAccount.isStripSignature() && (mAction == Action.REPLY || mAction == Action.REPLY_ALL)) { Matcher dashSignatureHtml = DASH_SIGNATURE_HTML.matcher(content); if (dashSignatureHtml.find()) { Matcher blockquoteStart = BLOCKQUOTE_START.matcher(content); Matcher blockquoteEnd = BLOCKQUOTE_END.matcher(content); List<Integer> start = new ArrayList<>(); List<Integer> end = new ArrayList<>(); while (blockquoteStart.find()) { start.add(blockquoteStart.start()); } while (blockquoteEnd.find()) { end.add(blockquoteEnd.start()); } if (start.size() != end.size()) { Log.d(K9.LOG_TAG, "There are " + start.size() + " <blockquote> tags, but " + end.size() + " </blockquote> tags. Refusing to strip."); } else if (start.size() > 0) { // Ignore quoted signatures in blockquotes. dashSignatureHtml.region(0, start.get(0)); if (dashSignatureHtml.find()) { // before first <blockquote>. content = content.substring(0, dashSignatureHtml.start()); } else { for (int i = 0; i < start.size() - 1; i++) { // within blockquotes. if (end.get(i) < start.get(i + 1)) { dashSignatureHtml.region(end.get(i), start.get(i + 1)); if (dashSignatureHtml.find()) { content = content.substring(0, dashSignatureHtml.start()); break; } } } if (end.get(end.size() - 1) < content.length()) { // after last </blockquote>. dashSignatureHtml.region(end.get(end.size() - 1), content.length()); if (dashSignatureHtml.find()) { content = content.substring(0, dashSignatureHtml.start()); } } } } else { // No blockquotes found. content = content.substring(0, dashSignatureHtml.start()); } } // Fix the stripping off of closing tags if a signature was stripped, // as well as clean up the HTML of the quoted message. HtmlCleaner cleaner = new HtmlCleaner(); CleanerProperties properties = cleaner.getProperties(); // see http://htmlcleaner.sourceforge.net/parameters.php for descriptions properties.setNamespacesAware(false); properties.setAdvancedXmlEscape(false); properties.setOmitXmlDeclaration(true); properties.setOmitDoctypeDeclaration(false); properties.setTranslateSpecialEntities(false); properties.setRecognizeUnicodeChars(false); TagNode node = cleaner.clean(content); SimpleHtmlSerializer htmlSerialized = new SimpleHtmlSerializer(properties); content = htmlSerialized.getAsString(node, "UTF8"); } // Add the HTML reply header to the top of the content. mQuotedHtmlContent = quoteOriginalHtmlMessage(mSourceMessage, content, mQuoteStyle); // Load the message with the reply header. mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent()); // TODO: Also strip the signature from the text/plain part mQuotedText.setCharacters(quoteOriginalTextMessage(mSourceMessage, getBodyTextFromMessage(mSourceMessage, SimpleMessageFormat.TEXT), mQuoteStyle)); } else if (mQuotedTextFormat == SimpleMessageFormat.TEXT) { if (mAccount.isStripSignature() && (mAction == Action.REPLY || mAction == Action.REPLY_ALL)) { if (DASH_SIGNATURE_PLAIN.matcher(content).find()) { content = DASH_SIGNATURE_PLAIN.matcher(content).replaceFirst("\r\n"); } } mQuotedText.setCharacters(quoteOriginalTextMessage(mSourceMessage, content, mQuoteStyle)); } if (showQuotedText) { showOrHideQuotedText(QuotedTextMode.SHOW); } else { showOrHideQuotedText(QuotedTextMode.HIDE); } } /** * Fetch the body text from a message in the desired message format. This method handles * conversions between formats (html to text and vice versa) if necessary. * @param message Message to analyze for body part. * @param format Desired format. * @return Text in desired format. * @throws MessagingException */ private String getBodyTextFromMessage(final Message message, final SimpleMessageFormat format) throws MessagingException { Part part; if (format == SimpleMessageFormat.HTML) { // HTML takes precedence, then text. part = MimeUtility.findFirstPartByMimeType(message, "text/html"); if (part != null) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "getBodyTextFromMessage: HTML requested, HTML found."); } return MessageExtractor.getTextFromPart(part); } part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); if (part != null) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "getBodyTextFromMessage: HTML requested, text found."); } String text = MessageExtractor.getTextFromPart(part); return HtmlConverter.textToHtml(text); } } else if (format == SimpleMessageFormat.TEXT) { // Text takes precedence, then html. part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); if (part != null) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "getBodyTextFromMessage: Text requested, text found."); } return MessageExtractor.getTextFromPart(part); } part = MimeUtility.findFirstPartByMimeType(message, "text/html"); if (part != null) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "getBodyTextFromMessage: Text requested, HTML found."); } String text = MessageExtractor.getTextFromPart(part); return HtmlConverter.htmlToText(text); } } // If we had nothing interesting, return an empty string. return ""; } // Regular expressions to look for various HTML tags. This is no HTML::Parser, but hopefully it's good enough for // our purposes. private static final Pattern FIND_INSERTION_POINT_HTML = Pattern.compile("(?si:.*?(<html(?:>|\\s+[^>]*>)).*)"); private static final Pattern FIND_INSERTION_POINT_HEAD = Pattern.compile("(?si:.*?(<head(?:>|\\s+[^>]*>)).*)"); private static final Pattern FIND_INSERTION_POINT_BODY = Pattern.compile("(?si:.*?(<body(?:>|\\s+[^>]*>)).*)"); private static final Pattern FIND_INSERTION_POINT_HTML_END = Pattern.compile("(?si:.*(</html>).*?)"); private static final Pattern FIND_INSERTION_POINT_BODY_END = Pattern.compile("(?si:.*(</body>).*?)"); // The first group in a Matcher contains the first capture group. We capture the tag found in the above REs so that // we can locate the *end* of that tag. private static final int FIND_INSERTION_POINT_FIRST_GROUP = 1; // HTML bits to insert as appropriate // TODO is it safe to assume utf-8 here? private static final String FIND_INSERTION_POINT_HTML_CONTENT = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<html>"; private static final String FIND_INSERTION_POINT_HTML_END_CONTENT = "</html>"; private static final String FIND_INSERTION_POINT_HEAD_CONTENT = "<head><meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"></head>"; // Index of the start of the beginning of a String. private static final int FIND_INSERTION_POINT_START_OF_STRING = 0; /** * <p>Find the start and end positions of the HTML in the string. This should be the very top * and bottom of the displayable message. It returns a {@link InsertableHtmlContent}, which * contains both the insertion points and potentially modified HTML. The modified HTML should be * used in place of the HTML in the original message.</p> * * <p>This method loosely mimics the HTML forward/reply behavior of BlackBerry OS 4.5/BIS 2.5, which in turn mimics * Outlook 2003 (as best I can tell).</p> * * @param content Content to examine for HTML insertion points * @return Insertion points and HTML to use for insertion. */ private InsertableHtmlContent findInsertionPoints(final String content) { InsertableHtmlContent insertable = new InsertableHtmlContent(); // If there is no content, don't bother doing any of the regex dancing. if (content == null || content.equals("")) { return insertable; } // Search for opening tags. boolean hasHtmlTag = false; boolean hasHeadTag = false; boolean hasBodyTag = false; // First see if we have an opening HTML tag. If we don't find one, we'll add one later. Matcher htmlMatcher = FIND_INSERTION_POINT_HTML.matcher(content); if (htmlMatcher.matches()) { hasHtmlTag = true; } // Look for a HEAD tag. If we're missing a BODY tag, we'll use the close of the HEAD to start our content. Matcher headMatcher = FIND_INSERTION_POINT_HEAD.matcher(content); if (headMatcher.matches()) { hasHeadTag = true; } // Look for a BODY tag. This is the ideal place for us to start our content. Matcher bodyMatcher = FIND_INSERTION_POINT_BODY.matcher(content); if (bodyMatcher.matches()) { hasBodyTag = true; } if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Open: hasHtmlTag:" + hasHtmlTag + " hasHeadTag:" + hasHeadTag + " hasBodyTag:" + hasBodyTag); } // Given our inspections, let's figure out where to start our content. // This is the ideal case -- there's a BODY tag and we insert ourselves just after it. if (hasBodyTag) { insertable.setQuotedContent(new StringBuilder(content)); insertable.setHeaderInsertionPoint(bodyMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP)); } else if (hasHeadTag) { // Now search for a HEAD tag. We can insert after there. // If BlackBerry sees a HEAD tag, it inserts right after that, so long as there is no BODY tag. It doesn't // try to add BODY, either. Right or wrong, it seems to work fine. insertable.setQuotedContent(new StringBuilder(content)); insertable.setHeaderInsertionPoint(headMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP)); } else if (hasHtmlTag) { // Lastly, check for an HTML tag. // In this case, it will add a HEAD, but no BODY. StringBuilder newContent = new StringBuilder(content); // Insert the HEAD content just after the HTML tag. newContent.insert(htmlMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP), FIND_INSERTION_POINT_HEAD_CONTENT); insertable.setQuotedContent(newContent); // The new insertion point is the end of the HTML tag, plus the length of the HEAD content. insertable.setHeaderInsertionPoint(htmlMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP) + FIND_INSERTION_POINT_HEAD_CONTENT.length()); } else { // If we have none of the above, we probably have a fragment of HTML. Yahoo! and Gmail both do this. // Again, we add a HEAD, but not BODY. StringBuilder newContent = new StringBuilder(content); // Add the HTML and HEAD tags. newContent.insert(FIND_INSERTION_POINT_START_OF_STRING, FIND_INSERTION_POINT_HEAD_CONTENT); newContent.insert(FIND_INSERTION_POINT_START_OF_STRING, FIND_INSERTION_POINT_HTML_CONTENT); // Append the </HTML> tag. newContent.append(FIND_INSERTION_POINT_HTML_END_CONTENT); insertable.setQuotedContent(newContent); insertable.setHeaderInsertionPoint(FIND_INSERTION_POINT_HTML_CONTENT.length() + FIND_INSERTION_POINT_HEAD_CONTENT.length()); } // Search for closing tags. We have to do this after we deal with opening tags since it may // have modified the message. boolean hasHtmlEndTag = false; boolean hasBodyEndTag = false; // First see if we have an opening HTML tag. If we don't find one, we'll add one later. Matcher htmlEndMatcher = FIND_INSERTION_POINT_HTML_END.matcher(insertable.getQuotedContent()); if (htmlEndMatcher.matches()) { hasHtmlEndTag = true; } // Look for a BODY tag. This is the ideal place for us to place our footer. Matcher bodyEndMatcher = FIND_INSERTION_POINT_BODY_END.matcher(insertable.getQuotedContent()); if (bodyEndMatcher.matches()) { hasBodyEndTag = true; } if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Close: hasHtmlEndTag:" + hasHtmlEndTag + " hasBodyEndTag:" + hasBodyEndTag); } // Now figure out where to put our footer. // This is the ideal case -- there's a BODY tag and we insert ourselves just before it. if (hasBodyEndTag) { insertable.setFooterInsertionPoint(bodyEndMatcher.start(FIND_INSERTION_POINT_FIRST_GROUP)); } else if (hasHtmlEndTag) { // Check for an HTML tag. Add ourselves just before it. insertable.setFooterInsertionPoint(htmlEndMatcher.start(FIND_INSERTION_POINT_FIRST_GROUP)); } else { // If we have none of the above, we probably have a fragment of HTML. // Set our footer insertion point as the end of the string. insertable.setFooterInsertionPoint(insertable.getQuotedContent().length()); } return insertable; } static class SendMessageTask extends AsyncTask<Void, Void, Void> { Context context; Account account; Contacts contacts; Message message; Long draftId; SendMessageTask(Context context, Account account, Contacts contacts, Message message, Long draftId) { this.context = context; this.account = account; this.contacts = contacts; this.message = message; this.draftId = draftId; } @Override protected Void doInBackground(Void... params) { try { contacts.markAsContacted(message.getRecipients(RecipientType.TO)); contacts.markAsContacted(message.getRecipients(RecipientType.CC)); contacts.markAsContacted(message.getRecipients(RecipientType.BCC)); } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to mark contact as contacted.", e); } MessagingController.getInstance(context).sendMessage(account, message, null); if (draftId != null) { // TODO set draft id to invalid in MessageCompose! MessagingController.getInstance(context).deleteDraft(account, draftId); } return null; } } class Listener extends MessagingListener { @Override public void loadMessageForViewStarted(Account account, String folder, String uid) { if ((mMessageReference == null) || !mMessageReference.getUid().equals(uid)) { return; } mHandler.sendEmptyMessage(MSG_PROGRESS_ON); } @Override public void loadMessageForViewFinished(Account account, String folder, String uid, LocalMessage message) { if ((mMessageReference == null) || !mMessageReference.getUid().equals(uid)) { return; } mHandler.sendEmptyMessage(MSG_PROGRESS_OFF); } @Override public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, final Message message) { if ((mMessageReference == null) || !mMessageReference.getUid().equals(uid)) { return; } mSourceMessage = message; runOnUiThread(new Runnable() { @Override public void run() { loadLocalMessageForDisplay((LocalMessage) message); } }); } @Override public void loadMessageForViewFailed(Account account, String folder, String uid, Throwable t) { if ((mMessageReference == null) || !mMessageReference.getUid().equals(uid)) { return; } mHandler.sendEmptyMessage(MSG_PROGRESS_OFF); // TODO show network error } @Override public void messageUidChanged(Account account, String folder, String oldUid, String newUid) { // Track UID changes of the source message if (mMessageReference != null) { final Account sourceAccount = Preferences.getPreferences(MessageCompose.this).getAccount(mMessageReference.getAccountUuid()); final String sourceFolder = mMessageReference.getFolderName(); final String sourceMessageUid = mMessageReference.getUid(); if (account.equals(sourceAccount) && (folder.equals(sourceFolder))) { if (oldUid.equals(sourceMessageUid)) { mMessageReference = mMessageReference.withModifiedUid(newUid); } if ((mSourceMessage != null) && (oldUid.equals(mSourceMessage.getUid()))) { mSourceMessage.setUid(newUid); } } } } } private void loadLocalMessageForDisplay(LocalMessage message) { // We check to see if we've previously processed the source message since this // could be called when switching from HTML to text replies. If that happens, we // only want to update the UI with quoted text (which picks the appropriate // part). if (mSourceProcessed) { try { populateUIWithQuotedMessage(true); } catch (MessagingException e) { // Hm, if we couldn't populate the UI after source reprocessing, let's just delete it? showOrHideQuotedText(QuotedTextMode.HIDE); Log.e(K9.LOG_TAG, "Could not re-process source message; deleting quoted text to be safe.", e); } updateMessageFormat(); } else { processSourceMessage(message); mSourceProcessed = true; } } /** * When we are launched with an intent that includes a mailto: URI, we can actually * gather quite a few of our message fields from it. * * @param mailTo * The MailTo object we use to initialize message field */ private void initializeFromMailto(MailTo mailTo) { recipientPresenter.initFromMailto(mailTo); String subject = mailTo.getSubject(); if (subject != null && !subject.isEmpty()) { mSubjectView.setText(subject); } String body = mailTo.getBody(); if (body != null && !subject.isEmpty()) { mMessageContentView.setCharacters(body); } } private static class SaveMessageTask extends AsyncTask<Void, Void, Void> { Context context; Account account; Contacts contacts; Handler handler; Message message; long draftId; boolean saveRemotely; SaveMessageTask(Context context, Account account, Contacts contacts, Handler handler, Message message, long draftId, boolean saveRemotely) { this.context = context; this.account = account; this.contacts = contacts; this.handler = handler; this.message = message; this.draftId = draftId; this.saveRemotely = saveRemotely; } @Override protected Void doInBackground(Void... params) { final MessagingController messagingController = MessagingController.getInstance(context); Message draftMessage = messagingController.saveDraft(account, message, draftId, saveRemotely); draftId = messagingController.getId(draftMessage); android.os.Message msg = android.os.Message.obtain(handler, MSG_SAVED_DRAFT, draftId); handler.sendMessage(msg); return null; } } private static final int REPLY_WRAP_LINE_WIDTH = 72; private static final int QUOTE_BUFFER_LENGTH = 512; // amount of extra buffer to allocate to accommodate quoting headers or prefixes /** * Add quoting markup to a text message. * @param originalMessage Metadata for message being quoted. * @param messageBody Text of the message to be quoted. * @param quoteStyle Style of quoting. * @return Quoted text. * @throws MessagingException */ private String quoteOriginalTextMessage(final Message originalMessage, final String messageBody, final QuoteStyle quoteStyle) throws MessagingException { String body = messageBody == null ? "" : messageBody; String sentDate = getSentDateText(originalMessage); if (quoteStyle == QuoteStyle.PREFIX) { StringBuilder quotedText = new StringBuilder(body.length() + QUOTE_BUFFER_LENGTH); if (sentDate.length() != 0) { quotedText.append(String.format( getString(R.string.message_compose_reply_header_fmt_with_date) + "\r\n", sentDate, Address.toString(originalMessage.getFrom()))); } else { quotedText.append(String.format( getString(R.string.message_compose_reply_header_fmt) + "\r\n", Address.toString(originalMessage.getFrom())) ); } final String prefix = mAccount.getQuotePrefix(); final String wrappedText = Utility.wrap(body, REPLY_WRAP_LINE_WIDTH - prefix.length()); // "$" and "\" in the quote prefix have to be escaped for // the replaceAll() invocation. final String escapedPrefix = prefix.replaceAll("(\\\\|\\$)", "\\\\$1"); quotedText.append(wrappedText.replaceAll("(?m)^", escapedPrefix)); return quotedText.toString().replaceAll("\\\r", ""); } else if (quoteStyle == QuoteStyle.HEADER) { StringBuilder quotedText = new StringBuilder(body.length() + QUOTE_BUFFER_LENGTH); quotedText.append("\r\n"); quotedText.append(getString(R.string.message_compose_quote_header_separator)).append("\r\n"); if (originalMessage.getFrom() != null && Address.toString(originalMessage.getFrom()).length() != 0) { quotedText.append(getString(R.string.message_compose_quote_header_from)).append(" ").append(Address.toString(originalMessage.getFrom())).append("\r\n"); } if (sentDate.length() != 0) { quotedText.append(getString(R.string.message_compose_quote_header_send_date)).append(" ").append(sentDate).append("\r\n"); } if (originalMessage.getRecipients(RecipientType.TO) != null && originalMessage.getRecipients(RecipientType.TO).length != 0) { quotedText.append(getString(R.string.message_compose_quote_header_to)).append(" ").append(Address.toString(originalMessage.getRecipients(RecipientType.TO))).append("\r\n"); } if (originalMessage.getRecipients(RecipientType.CC) != null && originalMessage.getRecipients(RecipientType.CC).length != 0) { quotedText.append(getString(R.string.message_compose_quote_header_cc)).append(" ").append(Address.toString(originalMessage.getRecipients(RecipientType.CC))).append("\r\n"); } if (originalMessage.getSubject() != null) { quotedText.append(getString(R.string.message_compose_quote_header_subject)).append(" ").append(originalMessage.getSubject()).append("\r\n"); } quotedText.append("\r\n"); quotedText.append(body); return quotedText.toString(); } else { // Shouldn't ever happen. return body; } } /** * Add quoting markup to a HTML message. * @param originalMessage Metadata for message being quoted. * @param messageBody Text of the message to be quoted. * @param quoteStyle Style of quoting. * @return Modified insertable message. * @throws MessagingException */ private InsertableHtmlContent quoteOriginalHtmlMessage(final Message originalMessage, final String messageBody, final QuoteStyle quoteStyle) throws MessagingException { InsertableHtmlContent insertable = findInsertionPoints(messageBody); String sentDate = getSentDateText(originalMessage); if (quoteStyle == QuoteStyle.PREFIX) { StringBuilder header = new StringBuilder(QUOTE_BUFFER_LENGTH); header.append("<div class=\"gmail_quote\">"); if (sentDate.length() != 0) { header.append(HtmlConverter.textToHtmlFragment(String.format( getString(R.string.message_compose_reply_header_fmt_with_date), sentDate, Address.toString(originalMessage.getFrom())) )); } else { header.append(HtmlConverter.textToHtmlFragment(String.format( getString(R.string.message_compose_reply_header_fmt), Address.toString(originalMessage.getFrom())) )); } header.append("<blockquote class=\"gmail_quote\" " + "style=\"margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;\">\r\n"); String footer = "</blockquote></div>"; insertable.insertIntoQuotedHeader(header.toString()); insertable.insertIntoQuotedFooter(footer); } else if (quoteStyle == QuoteStyle.HEADER) { StringBuilder header = new StringBuilder(); header.append("<div style='font-size:10.0pt;font-family:\"Tahoma\",\"sans-serif\";padding:3.0pt 0in 0in 0in'>\r\n"); header.append("<hr style='border:none;border-top:solid #E1E1E1 1.0pt'>\r\n"); // This gets converted into a horizontal line during html to text conversion. if (originalMessage.getFrom() != null && Address.toString(originalMessage.getFrom()).length() != 0) { header.append("<b>").append(getString(R.string.message_compose_quote_header_from)).append("</b> ") .append(HtmlConverter.textToHtmlFragment(Address.toString(originalMessage.getFrom()))) .append("<br>\r\n"); } if (sentDate.length() != 0) { header.append("<b>").append(getString(R.string.message_compose_quote_header_send_date)).append("</b> ") .append(sentDate) .append("<br>\r\n"); } if (originalMessage.getRecipients(RecipientType.TO) != null && originalMessage.getRecipients(RecipientType.TO).length != 0) { header.append("<b>").append(getString(R.string.message_compose_quote_header_to)).append("</b> ") .append(HtmlConverter.textToHtmlFragment(Address.toString(originalMessage.getRecipients(RecipientType.TO)))) .append("<br>\r\n"); } if (originalMessage.getRecipients(RecipientType.CC) != null && originalMessage.getRecipients(RecipientType.CC).length != 0) { header.append("<b>").append(getString(R.string.message_compose_quote_header_cc)).append("</b> ") .append(HtmlConverter.textToHtmlFragment(Address.toString(originalMessage.getRecipients(RecipientType.CC)))) .append("<br>\r\n"); } if (originalMessage.getSubject() != null) { header.append("<b>").append(getString(R.string.message_compose_quote_header_subject)).append("</b> ") .append(HtmlConverter.textToHtmlFragment(originalMessage.getSubject())) .append("<br>\r\n"); } header.append("</div>\r\n"); header.append("<br>\r\n"); insertable.insertIntoQuotedHeader(header.toString()); } return insertable; } /** * Used to store an {@link Identity} instance together with the {@link Account} it belongs to. * * @see IdentityAdapter */ static class IdentityContainer { public final Identity identity; public final Account account; IdentityContainer(Identity identity, Account account) { this.identity = identity; this.account = account; } } /** * Adapter for the <em>Choose identity</em> list view. * * <p> * Account names are displayed as section headers, identities as selectable list items. * </p> */ static class IdentityAdapter extends BaseAdapter { private LayoutInflater mLayoutInflater; private List<Object> mItems; public IdentityAdapter(Context context) { mLayoutInflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); List<Object> items = new ArrayList<>(); Preferences prefs = Preferences.getPreferences(context.getApplicationContext()); Collection<Account> accounts = prefs.getAvailableAccounts(); for (Account account : accounts) { items.add(account); List<Identity> identities = account.getIdentities(); for (Identity identity : identities) { items.add(new IdentityContainer(identity, account)); } } mItems = items; } @Override public int getCount() { return mItems.size(); } @Override public int getViewTypeCount() { return 2; } @Override public int getItemViewType(int position) { return (mItems.get(position) instanceof Account) ? 0 : 1; } @Override public boolean isEnabled(int position) { return (mItems.get(position) instanceof IdentityContainer); } @Override public Object getItem(int position) { return mItems.get(position); } @Override public long getItemId(int position) { return position; } @Override public boolean hasStableIds() { return false; } @Override public View getView(int position, View convertView, ViewGroup parent) { Object item = mItems.get(position); View view = null; if (item instanceof Account) { if (convertView != null && convertView.getTag() instanceof AccountHolder) { view = convertView; } else { view = mLayoutInflater.inflate(R.layout.choose_account_item, parent, false); AccountHolder holder = new AccountHolder(); holder.name = (TextView) view.findViewById(R.id.name); holder.chip = view.findViewById(R.id.chip); view.setTag(holder); } Account account = (Account) item; AccountHolder holder = (AccountHolder) view.getTag(); holder.name.setText(account.getDescription()); holder.chip.setBackgroundColor(account.getChipColor()); } else if (item instanceof IdentityContainer) { if (convertView != null && convertView.getTag() instanceof IdentityHolder) { view = convertView; } else { view = mLayoutInflater.inflate(R.layout.choose_identity_item, parent, false); IdentityHolder holder = new IdentityHolder(); holder.name = (TextView) view.findViewById(R.id.name); holder.description = (TextView) view.findViewById(R.id.description); view.setTag(holder); } IdentityContainer identityContainer = (IdentityContainer) item; Identity identity = identityContainer.identity; IdentityHolder holder = (IdentityHolder) view.getTag(); holder.name.setText(identity.getDescription()); holder.description.setText(getIdentityDescription(identity)); } return view; } static class AccountHolder { public TextView name; public View chip; } static class IdentityHolder { public TextView name; public TextView description; } } private static String getIdentityDescription(Identity identity) { return String.format("%s <%s>", identity.getName(), identity.getEmail()); } private void setMessageFormat(SimpleMessageFormat format) { // This method will later be used to enable/disable the rich text editing mode. mMessageFormat = format; } private void updateMessageFormat() { MessageFormat origMessageFormat = mAccount.getMessageFormat(); SimpleMessageFormat messageFormat; if (origMessageFormat == MessageFormat.TEXT) { // The user wants to send text/plain messages. We don't override that choice under // any circumstances. messageFormat = SimpleMessageFormat.TEXT; } else if (mForcePlainText && includeQuotedText()) { // Right now we send a text/plain-only message when the quoted text was edited, no // matter what the user selected for the message format. messageFormat = SimpleMessageFormat.TEXT; } else if (recipientPresenter.isForceTextMessageFormat()) { // Right now we only support PGP inline which doesn't play well with HTML. So force // plain text in those cases. messageFormat = SimpleMessageFormat.TEXT; } else if (origMessageFormat == MessageFormat.AUTO) { if (mAction == Action.COMPOSE || mQuotedTextFormat == SimpleMessageFormat.TEXT || !includeQuotedText()) { // If the message format is set to "AUTO" we use text/plain whenever possible. That // is, when composing new messages and replying to or forwarding text/plain // messages. messageFormat = SimpleMessageFormat.TEXT; } else { messageFormat = SimpleMessageFormat.HTML; } } else { // In all other cases use HTML messageFormat = SimpleMessageFormat.HTML; } setMessageFormat(messageFormat); } private boolean includeQuotedText() { return (mQuotedTextMode == QuotedTextMode.SHOW); } /** * Extract the date from a message and convert it into a locale-specific * date string suitable for use in a header for a quoted message. * * @return A string with the formatted date/time */ private String getSentDateText(Message message) { try { final int dateStyle = DateFormat.LONG; final int timeStyle = DateFormat.LONG; Date date = message.getSentDate(); Locale locale = getResources().getConfiguration().locale; return DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale) .format(date); } catch (Exception e) { return ""; } } private boolean isCryptoProviderEnabled() { return mOpenPgpProvider != null; } @Override public void onMessageBuildSuccess(MimeMessage message, boolean isDraft) { if (isDraft) { draftNeedsSaving = false; currentMessageBuilder = null; if (mAction == Action.EDIT_DRAFT && mMessageReference != null) { message.setUid(mMessageReference.getUid()); } boolean saveRemotely = recipientPresenter.isAllowSavingDraftRemotely(); new SaveMessageTask(getApplicationContext(), mAccount, mContacts, mHandler, message, mDraftId, saveRemotely).execute(); if (mFinishAfterDraftSaved) { finish(); } else { setProgressBarIndeterminateVisibility(false); } } else { currentMessageBuilder = null; new SendMessageTask(getApplicationContext(), mAccount, mContacts, message, mDraftId != INVALID_DRAFT_ID ? mDraftId : null).execute(); finish(); } } @Override public void onMessageBuildCancel() { currentMessageBuilder = null; setProgressBarIndeterminateVisibility(false); } @Override public void onMessageBuildException(MessagingException me) { Log.e(K9.LOG_TAG, "Error sending message", me); Toast.makeText(MessageCompose.this, getString(R.string.send_aborted, me.getLocalizedMessage()), Toast.LENGTH_LONG).show(); currentMessageBuilder = null; setProgressBarIndeterminateVisibility(false); } @Override public void onMessageBuildReturnPendingIntent(PendingIntent pendingIntent, int requestCode) { requestCode |= REQUEST_MASK_MESSAGE_BUILDER; try { startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0); } catch (SendIntentException e) { Log.e(K9.LOG_TAG, "Error starting pending intent from builder!", e); } } public void launchUserInteractionPendingIntent(PendingIntent pendingIntent, int requestCode) { requestCode |= REQUEST_MASK_RECIPIENT_PRESENTER; try { startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0); } catch (SendIntentException e) { e.printStackTrace(); } } }
88d4148793ab78c715c8102965bcb9d59e57c606
9c3bb98eb9d0a587a302bdfa811f7b5c6a5a0a37
/Week 6/id_495/LeetCode_130_495.java
3cca47e98c0ba12b9dedf10a0d275aa6afa49997
[]
permissive
chenlei65368/algorithm004-05
842db9d9017556656aef0eeb6611eec3991f6c90
60e9ef1051a1d0441ab1c5484a51ab77a306bf5b
refs/heads/master
2020-08-07T23:09:30.548805
2019-12-17T10:48:22
2019-12-17T10:48:22
213,617,423
1
0
Apache-2.0
2019-12-17T10:48:24
2019-10-08T10:50:41
Java
UTF-8
Java
false
false
1,603
java
class LeetCode_130_495 { boolean[][] flag; //flag[i][j]ไธบfalse๏ผŒ่กจ็คบboard[i][j]่ต‹ๅ€ผไธบ'X' int[] vi = {-1, 0, 1, 0}; int[] vj = {0, 1, 0, -1}; public void solve(char[][] board) { int n = board.length; //ๅฐไบŽ3่กŒๆˆ–3ๅˆ—็›ดๆŽฅ่ฟ”ๅ›ž if(n < 3) return; int m = board[0].length; if(m < 3) return; flag = new boolean[n][m]; int i = 0, j = 0, a = 0, b = 0, d = 1; int total = 2 * (m + n) - 4; //็Ÿฉ้˜ต็š„4ๆก่พนไธŠ็š„ๅ…ƒ็ด ไธชๆ•ฐ for(int k = 1; k <= total; k++){ if(board[i][j] == 'O') //ๅช่ฆๅ‘็Žฐ็Ÿฉ้˜ต็š„่พนไธŠ็š„ๅ…ƒ็ด ไธบ'O',้‚ฃไนˆไธŽๆญค'O'็›ธๆŽฅ็š„ๆ‰€ไปฅ'O'้ƒฝไธ่ขซๆ”นๅ˜ dfs(i, j, n, m, board); a = i + vi[d]; b = j + vj[d]; if(a >= n || a < 0 || b >= m || b < 0){ d = (d + 1) % 4; a = i + vi[d]; b = j + vj[d]; } i = a; j = b; } for(int p = 0; p < n; p++) for(int q = 0; q < m; q++){ if(!flag[p][q]) board[p][q] = 'X'; } } void dfs(int i, int j, int n, int m, char[][] board){ flag[i][j] = true; for(int k = 0; k < 4; k++){ int a = i + vi[k], b = j + vj[k]; //ๅชๆœ‰a,bไธ่ถŠ็•Œ๏ผŒๅนถไธ”a,bๅœจboardๆ•ฐ็ป„ไธบ'O',่€Œไธ”a,bๆฒก่ตฐ่ฟ‡(ๅณflag[a][b] == false๏ผŒไธ็„ถไผšๆญปๅพช็Žฏ) if(a >= 0 && a < n && b >= 0 && b < m && board[a][b] == 'O' && flag[a][b] == false) dfs(a, b, n, m, board); } } }
685a44a89376c9882bd7af5d6f4c550fcaf3af22
ad9cf3ff1446c16ed4668c8303dcb16626c4e0c4
/basic/core/ch06/interfaces/basic/CmpEmployee.java
1bcfe9bbca98d0b0d90b659752ea607b1bf1ec4a
[]
no_license
YoungTaeSung/core-java-study
e30075822157c1d25f0cf362bc56cb009d4ea40d
f221596592bdb2357415b65b008fb4c4f573360a
refs/heads/master
2016-09-05T12:18:17.534357
2012-06-01T06:07:22
2012-06-01T06:07:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
951
java
package core.ch06.interfaces.basic; import java.util.Date; import java.util.GregorianCalendar; public class CmpEmployee implements Comparable { private String name; private double salary; private Date hireDay; public CmpEmployee(String n, double s, int year, int month, int day) { name = n; salary = s; GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); hireDay = calendar.getTime(); } public String getName() { return name; } public double getSalary() { return salary; } public Date getHireDay() { return hireDay; } public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } @Override public int compareTo(Object obj) { if(this.salary < ((CmpEmployee)obj).salary) return -1; else if(this.salary > ((CmpEmployee)obj).salary) return 1; else return 0; } }
0350a17e68c7de78293336613a7ad6009779a6fa
13ea5da0b7b8d4ba87d622a5f733dcf6b4c5f1e3
/crash-reproduction-ws/results/XWIKI-12889-2-1-Single_Objective_GGA-WeightedSum/org/xwiki/rest/internal/resources/job/JobStatusResourceImpl_ESTest_scaffolding.java
89841e26a58f3e951242692b103876e0b312b0f9
[ "MIT", "CC-BY-4.0" ]
permissive
STAMP-project/Botsing-basic-block-coverage-application
6c1095c6be945adc0be2b63bbec44f0014972793
80ea9e7a740bf4b1f9d2d06fe3dcc72323b848da
refs/heads/master
2022-07-28T23:05:55.253779
2022-04-20T13:54:11
2022-04-20T13:54:11
285,771,370
0
0
null
null
null
null
UTF-8
Java
false
false
463
java
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Wed Apr 01 03:00:42 UTC 2020 */ package org.xwiki.rest.internal.resources.job; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; @EvoSuiteClassExclude public class JobStatusResourceImpl_ESTest_scaffolding { // Empty scaffolding for empty test suite }
bc511e97c012c9a0cea128b8b38fe6b55977dd14
c10f2e1b8ddc9ce4f2897c2ca9a84cece693f32f
/SpringCore-Dependency-Injection-Setter-Method-Example/src/main/java/com/codewr/common/App.java
9787313c52c15461fd7e8f5602057c5303547185
[]
no_license
sieurobo196/Spring-Core
04aa3b6c0f65f8f04ca1aaefee8eb91228c5e28c
a11944ac84acef6ede3638c3480bbdf00bebdc82
refs/heads/master
2020-03-27T17:36:45.022265
2019-04-25T08:38:36
2019-04-25T08:38:36
146,861,726
0
0
null
null
null
null
UTF-8
Java
false
false
495
java
package com.codewr.common; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.codewr.output.OutputHelper; public class App { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "SpringBeans.xml"); OutputHelper output = (OutputHelper) context.getBean("OutputHelper"); output.generateSCVOutput(); } }
e67ad1211d241611fa5e44d8813b3a30c319df3a
e9f5017e5657abcd1d0154f52a7aacf529fad72a
/java/src/h_Oop/inheritancePolymorphism/CastingTest.java
3054c173fc3659c867a8b981ecb8bdf8ba14b7bb
[]
no_license
dmlee19/JavaTutorials
92e1a1ff77399ca0ca0ef179b55942aae7c568c2
b2091d8a8677035daf9ce478f4da6367e8d7eacc
refs/heads/master
2023-02-20T03:41:24.348559
2021-01-16T06:39:51
2021-01-16T06:39:51
null
0
0
null
null
null
null
UHC
Java
false
false
1,020
java
/** * Polymorphism and Casting * tests casting among objects. */ package h_Oop.inheritancePolymorphism; public class CastingTest { public static void main(String[] args) { GeometricObject geo = new GeometricObject(); Circle c = new Circle(3.0, "blue", true); Rectangle r = new Rectangle(4.5, 7.0, "green", false); double area1 = ((GeometricObject)c).getArea(); // return 0; System.out.printf("Cast Circle to GeometricObject area: %.3f\n", area1); // Cast Circle to GeometricObject area: 28.274 // runtime ์‹œ instance์ธ Circle์˜ getArea method ํ˜ธ์ถœ // double area2 = ((Circle)geo).getArea(); // System.out.printf("Cast GeometricObject to Circle area: %.3f\n", area2); // GeometricObject cannot be cast to Circle // compile์—๋Š” ๋ฌธ์ œ๊ฐ€ ์—†์ง€๋งŒ runtime์—์„œ ๋ฌธ์ œ ๋ฐœ์ƒ // double area3 = ((Rectangle)c).getArea(); // System.out.printf("Cast Circle to Rectangle area: %.3f\n", area3); // subclass๋ฅผ ๋˜ ๋‹ค๋ฅธ subclass๋กœ casing ==> compile ์˜ค๋ฅ˜ }// main }
338c6e68e05494ebc8354b55010a313ef600e3c4
78b0d36fde64fd9b96a0c2254505e31e4d2f9526
/Minggu 2/JualbeliTanahMain.java
446342fab23be5bea5ecee8ee06489301b8f268b
[]
no_license
MWPras/Algoritma-Struktur-Data
a1dad9d28810917157cfccab1e298b2bdd2c9473
c9896b5806d54f873a1cff0ccd9f7b2b758a9a44
refs/heads/master
2020-04-23T07:12:04.346670
2019-03-22T15:28:51
2019-03-22T15:28:51
170,999,334
1
0
null
null
null
null
UTF-8
Java
false
false
951
java
/* * 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 Minggu2; import java.util.Scanner; /** * * @author LENOVO */ public class JualbeliTanahMain { public static void main (String[] args){ JualbeliTanah[] jtArray = new JualbeliTanah[3]; Scanner scan = new Scanner(System.in); for(int i=1; i<4; i++){ jtArray[0] = new JualbeliTanah(); System.out.println("Persegi Panjang ke-"+i); System.out.print("Masukkan Panjang: "); jtArray[0].panjang = scan.nextInt(); System.out.print("Masukkan Lebar: "); jtArray[0].lebar = scan.nextInt(); } for(int i=1; i<4; i++){ System.out.println("Hitung Balok ke "+ i +": " + jtArray[i].hitungLuas()); } } }
20f5f4b613cd261ecfae002d560bbed9f758b6b6
25afd4c66a14a18d53349bd6dc83b6be641bb1e5
/test/comp/Control.java
b64ce91534bfc679de18887220a74f7d536d8fc2
[]
no_license
sakurai-kai/stock
215fa26dfee429b5f0b8f8bb4b9ca139232350b5
901be60187ad24adeff6ed136f0a8742a0862a31
refs/heads/master
2023-02-08T08:59:09.714035
2021-01-01T16:25:42
2021-01-01T16:25:42
324,389,486
0
0
null
null
null
null
UTF-8
Java
false
false
712
java
package test.comp; import javax.swing.JFrame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.WindowConstants; public class Control extends JFrame implements ActionListener{ private Button button; public Control(String title){ super(title); this.button = new Button("button"); this.add(button); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setSize(500,500); this.setVisible(true); } public void print(){ System.out.println(this.getTitle()); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }
998bcf87f90350dcca865360bcca5a90aefc08c3
fe11d5a66d98519ebf088be2aa786a33fda22c3b
/app/src/main/java/com/lgroup/ltms/com/lgroup/ltms/WebServiceContact.java
ea26adfad6210211551766d7302ca9875d35783c
[]
no_license
mhadieskandari/Ltms
272b3dc3c9946796869d8cd797f7b73776cac62f
5100ebe73f85a2ba7c9fd0a4af3792a95d1c7d63
refs/heads/master
2020-06-09T04:35:48.817617
2019-06-23T16:30:40
2019-06-23T16:30:40
193,371,171
0
0
null
null
null
null
UTF-8
Java
false
false
2,461
java
package com.lgroup.ltms.com.lgroup.ltms; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * Created by Asus on 01/02/2016. */ public class WebServiceContact { Context context; public WebServiceContact(Context context){ this.context=context; } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } public String requestContent(String url) { HttpClient httpclient = new DefaultHttpClient(); String result = null; HttpGet httpget = new HttpGet(url); HttpResponse response = null; InputStream instream = null; try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { instream = entity.getContent(); result = convertStreamToString(instream); } } catch (Exception e) { Log.i("MyTag", e.toString()); // manage exceptions } finally { if (instream != null) { try { instream.close(); } catch (Exception exc) { } } } return result; } public String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { } finally { try { is.close(); } catch (IOException e) { } } return sb.toString(); } }
75872fe6bbf6844546825995361bd2333438efc5
2812f2478e561d0d2ae9b51fa2b01d1a73265c1b
/src/test/java/com/erhanturkcan/airlineticketsystem/web/controller/RouteProcessControllerTest.java
eeac78d7094cec63b44a8233e361b5edca11e387
[]
no_license
erhanturkcan/airlineTicketSystem2
2595b744ce4efc9883f8b9c586f68c285289e938
0d38b42cbcb66b11a34953a0bb402e35efda31f0
refs/heads/master
2022-12-22T12:15:30.261489
2020-09-30T07:04:33
2020-09-30T07:04:33
299,299,157
0
0
null
null
null
null
UTF-8
Java
false
false
1,869
java
package com.erhanturkcan.airlineticketsystem.web.controller; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import org.junit.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.ComponentScan; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.erhanturkcan.airlineticketsystem.domain.dto.RouteDTO; import com.erhanturkcan.airlineticketsystem.domain.service.RouteService; import com.erhanturkcan.airlineticketsystem.mapper.RouteMapper; import com.erhanturkcan.airlineticketsystem.util.TestUtil; @WebMvcTest(controllers = RouteProcessController.class) @ComponentScan(basePackageClasses = { RouteMapper.class }) public class RouteProcessControllerTest extends AbstractControllerTest { @Autowired private MockMvc mockMvc; @MockBean private RouteService service; private final String URL = "/searchRouteByCodeorDepartFrom"; @Test public void givenCodeAndDepartFrom_whenGetRoute_thenShouldReturnHttpOkAndRoute() throws Exception { RouteDTO routeDto = TestUtil.getRoute(); when(service.searchRouteByCodeOrDepartFrom(Mockito.anyString(), Mockito.anyString())).thenReturn(routeDto); MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get(URL + "/code=ROU001&departFrom=IST") .accept(MediaType.APPLICATION_JSON_UTF8_VALUE)).andReturn(); int status = result.getResponse().getStatus(); assertThat(status).isEqualTo(HttpStatus.OK); } }
655af594205b1ebb542f555e91a20336d65bc27c
56adea945b27ccaf880decadb7f7cb86de450a8d
/core/ep-core/src/main/java/com/elasticpath/common/dto/CouponDtoMediatorImpl.java
957ae7bedea603e2975cede9bdb7004a7ecf4f1f
[]
no_license
ryanlfoster/ep-commerce-engine-68
89b56878806ca784eca453d58fb91836782a0987
7364bce45d25892e06df2e1c51da84dbdcebce5d
refs/heads/master
2020-04-16T04:27:40.577543
2013-12-10T19:31:52
2013-12-10T20:01:08
40,164,760
1
1
null
2015-08-04T05:15:25
2015-08-04T05:15:25
null
UTF-8
Java
false
false
3,563
java
package com.elasticpath.common.dto; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import com.elasticpath.commons.beanframework.BeanFactory; import com.elasticpath.domain.rules.Coupon; import com.elasticpath.domain.rules.CouponConfig; import com.elasticpath.base.exception.EpServiceException; import com.elasticpath.service.rules.CouponConfigService; import com.elasticpath.service.rules.CouponService; import com.elasticpath.service.rules.DuplicateCouponException; /** * Mediator to persist coupon DTO collections by transforming to domain objects * and calling the coupon service to do the persisting. */ public class CouponDtoMediatorImpl implements CouponDtoMediator { private CouponService couponService; private CouponConfigService couponConfigService; private BeanFactory beanFactory; private CouponModelDtoAssembler couponAssembler; @Override public void add(final Collection<CouponModelDto> addedCoupons, final String ruleCode) throws EpServiceException { CouponConfig config = getCouponConfigService().findByRuleCode(ruleCode); for (CouponModelDto dto : addedCoupons) { final Coupon coupon = getCouponAssembler().assembleDomain(dto, config); getCouponService().add(coupon); } } @Override public void validate(final Collection<CouponModelDto> addedCouponItems, final String ruleCode) { for (CouponModelDto dto : addedCouponItems) { if (getCouponService().findByCouponCode(dto.getCouponCode()) != null) { throw new DuplicateCouponException("Coupon code is duplicated", dto.getCouponCode()); } } } @Override public void update(final Collection<CouponModelDto> couponUpdates) throws EpServiceException { Map<Long, CouponModelDto> modelMap = new HashMap<Long, CouponModelDto>(); for (CouponModelDto dto : couponUpdates) { modelMap.put(dto.getUidPk(), dto); } List<Coupon> coupons = getCouponService().findByUids(modelMap.keySet()); for (Coupon coupon : coupons) { CouponModelDto dto = modelMap.get(coupon.getUidPk()); assembleDomain(coupon, dto); getCouponService().update(coupon); } } /** * Assemble the domain object from the DTO. * * @param coupon the domain object to assemble * @param dto the dto */ protected void assembleDomain(final Coupon coupon, final CouponModelDto dto) { coupon.setSuspended(dto.isSuspended()); coupon.setCouponCode(dto.getCouponCode()); } /** * @param couponService the couponService to set */ public void setCouponService(final CouponService couponService) { this.couponService = couponService; } /** * @return the couponService */ public CouponService getCouponService() { return couponService; } /** * * @param couponConfigService the couponConfigService to set */ public void setCouponConfigService(final CouponConfigService couponConfigService) { this.couponConfigService = couponConfigService; } /** * * @return the couponConfigService */ public CouponConfigService getCouponConfigService() { return couponConfigService; } /** * * @param beanFactory the beanFactory to set */ public void setBeanFactory(final BeanFactory beanFactory) { this.beanFactory = beanFactory; } /** * * @return the beanFactory */ public BeanFactory getBeanFactory() { return beanFactory; } /** * @return the assembler */ private CouponModelDtoAssembler getCouponAssembler() { if (couponAssembler == null) { couponAssembler = new CouponModelDtoAssembler(getBeanFactory()); } return couponAssembler; } }
a1c11526029938d6e47cb1ac599812ceaeea2e20
ac31aee56bae5fd20a4ba5047bb63451cc8ab0a5
/src/com/way/slidingmenu/SlidingActivityHelper.java
f24776590580498a75610ed836284be9f722e506
[]
no_license
tianshiaimili/TestSwipeListView
5578aeaeeec4b847dcc38a0d6ed02cdf831102be
fdd7fdb210887a2a84ae5b8e0e073ee9346a0910
refs/heads/master
2021-01-11T10:47:26.749902
2015-01-19T06:03:58
2015-01-19T06:03:58
29,456,003
0
0
null
null
null
null
UTF-8
Java
false
false
6,121
java
package com.way.slidingmenu; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import com.example.restswipelistview.R; public class SlidingActivityHelper { private Activity mActivity; private SlidingMenu mSlidingMenu; private View mViewAbove; private View mViewBehind; private boolean mBroadcasting = false; private boolean mOnPostCreateCalled = false; private boolean mEnableSlide = true; /** * Instantiates a new SlidingActivityHelper. * * @param activity the associated activity */ public SlidingActivityHelper(Activity activity) { mActivity = activity; } /** * Sets mSlidingMenu as a newly inflated SlidingMenu. Should be called within the activitiy's onCreate() * * @param savedInstanceState the saved instance state (unused) */ public void onCreate(Bundle savedInstanceState) { mSlidingMenu = (SlidingMenu) LayoutInflater.from(mActivity).inflate(R.layout.slidingmenumain, null); } /** * Further SlidingMenu initialization. Should be called within the activitiy's onPostCreate() * * @param savedInstanceState the saved instance state (unused) */ public void onPostCreate(Bundle savedInstanceState) { if (mViewBehind == null || mViewAbove == null) { throw new IllegalStateException("Both setBehindContentView must be called " + "in onCreate in addition to setContentView."); } mOnPostCreateCalled = true; mSlidingMenu.attachToActivity(mActivity, mEnableSlide ? SlidingMenu.SLIDING_WINDOW : SlidingMenu.SLIDING_CONTENT); final boolean open; final boolean secondary; if (savedInstanceState != null) { open = savedInstanceState.getBoolean("SlidingActivityHelper.open"); secondary = savedInstanceState.getBoolean("SlidingActivityHelper.secondary"); } else { open = false; secondary = false; } new Handler().post(new Runnable() { public void run() { if (open) { if (secondary) { mSlidingMenu.showSecondaryMenu(false); } else { mSlidingMenu.showMenu(false); } } else { mSlidingMenu.showContent(false); } } }); } /** * Controls whether the ActionBar slides along with the above view when the menu is opened, * or if it stays in place. * * @param slidingActionBarEnabled True if you want the ActionBar to slide along with the SlidingMenu, * false if you want the ActionBar to stay in place */ public void setSlidingActionBarEnabled(boolean slidingActionBarEnabled) { if (mOnPostCreateCalled) throw new IllegalStateException("enableSlidingActionBar must be called in onCreate."); mEnableSlide = slidingActionBarEnabled; } /** * Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle). * * @param id the resource id of the desired view * @return The view if found or null otherwise. */ public View findViewById(int id) { View v; if (mSlidingMenu != null) { v = mSlidingMenu.findViewById(id); if (v != null) return v; } return null; } /** * Called to retrieve per-instance state from an activity before being killed so that the state can be * restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method * will be passed to both). * * @param outState Bundle in which to place your saved state. */ public void onSaveInstanceState(Bundle outState) { outState.putBoolean("SlidingActivityHelper.open", mSlidingMenu.isMenuShowing()); outState.putBoolean("SlidingActivityHelper.secondary", mSlidingMenu.isSecondaryMenuShowing()); } /** * Register the above content view. * * @param v the above content view to register * @param params LayoutParams for that view (unused) */ public void registerAboveContentView(View v, LayoutParams params) { if (!mBroadcasting) mViewAbove = v; } /** * Set the activity content to an explicit view. This view is placed directly into the activity's view * hierarchy. It can itself be a complex view hierarchy. When calling this method, the layout parameters * of the specified view are ignored. Both the width and the height of the view are set by default to * MATCH_PARENT. To use your own layout parameters, invoke setContentView(android.view.View, * android.view.ViewGroup.LayoutParams) instead. * * @param v The desired content to display. */ public void setContentView(View v) { mBroadcasting = true; mActivity.setContentView(v); } /** * Set the behind view content to an explicit view. This view is placed directly into the behind view 's view hierarchy. * It can itself be a complex view hierarchy. * * @param view The desired content to display. * @param layoutParams Layout parameters for the view. (unused) */ public void setBehindContentView(View view, LayoutParams layoutParams) { mViewBehind = view; mSlidingMenu.setMenu(mViewBehind); } /** * Gets the SlidingMenu associated with this activity. * * @return the SlidingMenu associated with this activity. */ public SlidingMenu getSlidingMenu() { return mSlidingMenu; } /** * Toggle the SlidingMenu. If it is open, it will be closed, and vice versa. */ public void toggle() { mSlidingMenu.toggle(); } /** * Close the SlidingMenu and show the content view. */ public void showContent() { mSlidingMenu.showContent(); } /** * Open the SlidingMenu and show the menu view. */ public void showMenu() { mSlidingMenu.showMenu(); } /** * Open the SlidingMenu and show the secondary menu view. Will default to the regular menu * if there is only one. */ public void showSecondaryMenu() { mSlidingMenu.showSecondaryMenu(); } /** * On key up. * * @param keyCode the key code * @param event the event * @return true, if successful */ public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && mSlidingMenu.isMenuShowing()) { showContent(); return true; } return false; } }
[ "huyue52099" ]
huyue52099
232a4c70176c98d5ce7e9f8da8f0684b5628b529
005582b1767506d2e83f884f3780cf7a3769eb00
/src/NeuralNetworkTest.java
ae803c09d421e1eb15e653f0807442d477ee083c
[]
no_license
ChiaChunWang0821/NN_SOM
5268c1209784a9d321e7209f764a6a49bd517c58
d4bde15c4dddd6eb1f43ffc319764f2f4ef87d19
refs/heads/main
2023-02-07T02:36:58.800103
2020-12-27T16:03:19
2020-12-27T16:03:19
322,181,850
0
0
null
null
null
null
UTF-8
Java
false
false
1,254
java
public class NeuralNetworkTest{ public static void main(String[] args) { testSOM(); } private static void testSOM(){ NeuralNetworkJFrame neuralNetworkJFrame = new NeuralNetworkJFrame(); SOM som = new SOM(); OnNeuralNetworkCallback onNeuralNetworkCallback = new OnNeuralNetworkCallback() { DataSet set = null; @Override public void dataReadyCallback(DataSet dataSet) { set = dataSet; som.setDataSet((OnNeuralNetworkCallback)this, dataSet); } @Override public void showResultCallback() { if (set != null){ som.setDataSet((OnNeuralNetworkCallback)this, set); som.start((OnNeuralNetworkCallback)this, set); } } @Override public void getValueCallback(int type, String string) { som.setValue(type, string); } @Override public void setValueCallback(int type, String string) { neuralNetworkJFrame.updateValue(type, string); } }; neuralNetworkJFrame.actionListener(onNeuralNetworkCallback); } }
8feb57709ea4f8207210879a2279d0e158ebe577
bb859a3d4c7beda4dc8f837017afc2cae16d2350
/PalindromeNumber.java
8e458bf5a518f1b44eea252352788f98778bf5a7
[]
no_license
mahimaupadhya/leetcode
5f383aea7094b38f5718a57aae2ac88a29e71dc6
f68741257e4a58bdd70f2a5051cb9581edac95a6
refs/heads/main
2023-02-21T10:39:10.018204
2021-01-25T16:51:46
2021-01-25T16:51:46
325,039,918
0
0
null
null
null
null
UTF-8
Java
false
false
306
java
class Solution { public boolean isPalindrome(int x) { if(x==0){return true;} if(x<0 || x%10==0) { return false; } int b=0; while(x>b) { b=(b*10)+(x%10); x=x/10; } if(x==b || x==b/10) {return true;} else{ return false; } } }
554b6e66cc46cfc989f180867d414d701962dc64
b2041ed2001f1db327e3991cd77575b12cb7372a
/GoodsOwner/src/main/java/cn/com/goodsowner/activity/FAQActivity.java
0a4cf70e35944b4d15c2ca8bd7301e90cea6b999
[]
no_license
LFengYe/WorkProject_v3.3
4de58fc49c24a53b8be0c77f01669ebb86651c8f
59cc45cc07d2477957ba0cc124f00e5ea1217df7
refs/heads/master
2021-01-19T18:35:51.562958
2017-08-01T07:15:26
2017-08-01T07:15:28
88,365,855
1
1
null
null
null
null
UTF-8
Java
false
false
3,601
java
package cn.com.goodsowner.activity; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.android.volley.VolleyError; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.Map; import cn.com.goodsowner.R; import cn.com.goodsowner.base.BaseActivity; import cn.com.goodsowner.base.Contants; import cn.com.goodsowner.bean.MessageInfo; import cn.com.goodsowner.util.EncryptUtil; import cn.com.goodsowner.util.HttpUtil; import cn.com.goodsowner.util.LogUtil; import cn.com.goodsowner.util.VolleyInterface; public class FAQActivity extends BaseActivity { private TextView tv_title; private TextView tv_right; private ImageView iv_left_white; private TextView tv_msgtitle; private TextView tv_content; @Override protected int getLayout() { return R.layout.activity_faq; } @Override protected void findById() { RelativeLayout rl_head = (RelativeLayout) findViewById(cn.com.goodsowner.R.id.in_head); assert rl_head != null; tv_title = (TextView) rl_head.findViewById(cn.com.goodsowner.R.id.tv_title); tv_right = (TextView) rl_head.findViewById(cn.com.goodsowner.R.id.tv_right); iv_left_white = (ImageView) rl_head.findViewById(cn.com.goodsowner.R.id.iv_left_white); tv_content = (TextView) findViewById(cn.com.goodsowner.R.id.tv_content); tv_msgtitle = (TextView) findViewById(cn.com.goodsowner.R.id.tv_msgtitle); } @Override protected void initData() { } @Override protected void initView() { tv_title.setText(cn.com.goodsowner.R.string.faq); tv_right.setVisibility(View.GONE); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("Type", 1); jsonObject.addProperty("UserType", 1); Map<String, String> map = EncryptUtil.encryptDES(jsonObject.toString()); HttpUtil.doPost(FAQActivity.this, Contants.url_obtainMessage, "obtainMessage", map, new VolleyInterface(FAQActivity.this, VolleyInterface.mListener, VolleyInterface.mErrorListener) { @Override public void onSuccess(JsonElement result) { LogUtil.i(result.toString()); Gson gson = new Gson(); MessageInfo messageInfo = gson.fromJson(result, MessageInfo.class); String msgtitle = messageInfo.getTitle(); String content = messageInfo.getArticleContent(); try { msgtitle = EncryptUtil.decryptDES(msgtitle); content = EncryptUtil.decryptDES(content); tv_content.setText(content); tv_msgtitle.setText(msgtitle); } catch (Exception e) { e.printStackTrace(); } } @Override public void onError(VolleyError error) { showShortToastByString(getString(cn.com.goodsowner.R.string.timeoutError)); // LogUtil.i("hint",error.networkResponse.headers.toString()); // LogUtil.i("hint",error.networkResponse.statusCode+""); } @Override public void onStateError() { } }); iv_left_white.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case cn.com.goodsowner.R.id.iv_left_white: finish(); break; } } }
ae7a08bae10350d787b0b9c6929dd7186c6f08b4
0b5b53417b1cdbf4a91d09952741ff8ddd0c6cb3
/weboot-common/src/test/java/com/github/yangwk/weboot/test/sftp/WebootSftpTemplateConfiguration.java
8df98e8e2543d1fac5f8ba724d8b0b812e9a5fe2
[]
no_license
yangwk/weboot
b31b285b962bf8ef672629d9a545fdaa4e312750
e719a2ff715b19926309b8fd7e6f7b5221d907a8
refs/heads/master
2023-02-07T14:01:00.095520
2020-12-30T11:56:06
2020-12-30T11:56:06
325,538,069
3
0
null
null
null
null
UTF-8
Java
false
false
663
java
package com.github.yangwk.weboot.test.sftp; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.github.yangwk.weboot.common.sftp.SftpTemplateBuilder; @Configuration @EnableConfigurationProperties(WebootSftpConfigProperties.class) public class WebootSftpTemplateConfiguration { @Bean public WebootSftpTemplateHelper webootSftpTemplateHelper(WebootSftpConfigProperties webootSftpConfigProperties) { return new WebootSftpTemplateHelper(new SftpTemplateBuilder().build(webootSftpConfigProperties)); } }
16535c11381b7657ee4827efa5dbc2e62391756f
17e8438486cb3e3073966ca2c14956d3ba9209ea
/dso/tags/2.6.3/code/base/dso-l2/src/com/tc/objectserver/persistence/sleepycat/CustomSerializationAdapter.java
e4e2692319064b63d7cbe6f99a3845e4ff534b52
[]
no_license
sirinath/Terracotta
fedfc2c4f0f06c990f94b8b6c3b9c93293334345
00a7662b9cf530dfdb43f2dd821fa559e998c892
refs/heads/master
2021-01-23T05:41:52.414211
2015-07-02T15:21:54
2015-07-02T15:21:54
38,613,711
1
0
null
null
null
null
UTF-8
Java
false
false
2,586
java
/* * All content copyright (c) 2003-2008 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved. */ package com.tc.objectserver.persistence.sleepycat; import com.sleepycat.je.DatabaseEntry; import com.tc.io.serializer.TCObjectInputStream; import com.tc.io.serializer.TCObjectOutputStream; import com.tc.io.serializer.api.Serializer; import com.tc.io.serializer.impl.StringUTFSerializer; import com.tc.objectserver.core.api.ManagedObject; import com.tc.objectserver.managedobject.ManagedObjectSerializer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class CustomSerializationAdapter implements SerializationAdapter { private final ByteArrayOutputStream baout; private final TCObjectOutputStream out; private final ManagedObjectSerializer moSerializer; private final StringUTFSerializer stringSerializer; private final Object serializerLock = new Object(); public CustomSerializationAdapter(ManagedObjectSerializer moSerializer, StringUTFSerializer stringSerializer) { this.moSerializer = moSerializer; this.stringSerializer = stringSerializer; baout = new ByteArrayOutputStream(4096); out = new TCObjectOutputStream(baout); } public void serializeManagedObject(DatabaseEntry entry, ManagedObject managedObject) throws IOException { synchronized (serializerLock) { serialize(entry, managedObject, moSerializer); } } public synchronized void serializeString(DatabaseEntry entry, String string) throws IOException { synchronized (serializerLock) { serialize(entry, string, stringSerializer); } } private void serialize(DatabaseEntry entry, Object o, Serializer serializer) throws IOException { serializer.serializeTo(o, out); out.flush(); entry.setData(baout.toByteArray()); baout.reset(); } public synchronized ManagedObject deserializeManagedObject(DatabaseEntry data) throws IOException, ClassNotFoundException { return (ManagedObject) deserialize(data, moSerializer); } public String deserializeString(DatabaseEntry data) throws IOException, ClassNotFoundException { return (String) deserialize(data, stringSerializer); } private Object deserialize(DatabaseEntry entry, Serializer serializer) throws IOException, ClassNotFoundException { ByteArrayInputStream bain = new ByteArrayInputStream(entry.getData()); TCObjectInputStream in = new TCObjectInputStream(bain); return serializer.deserializeFrom(in); } }
[ "hhuynh@7fc7bbf3-cf45-46d4-be06-341739edd864" ]
hhuynh@7fc7bbf3-cf45-46d4-be06-341739edd864
905f1a5e5d5f5835ea5d1334a8274cb902ff7189
45c2caad8a7aa00cd482cef3628343585566d06b
/CompatibilityLib/common/src/main/java/com/elmakers/mine/bukkit/utility/platform/SpigotUtils.java
7b367882ee317e6f6b813b650f86eeb6adec504c
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
elBukkit/MagicPlugin
bb70f5adb13abbb4eb9b1f6d56eb458152a98881
71a48001701d164535da230b75165dc414f7cfc4
refs/heads/master
2023-08-16T13:29:28.980087
2023-08-13T21:15:12
2023-08-13T21:15:12
1,616,402
249
284
MIT
2023-09-12T16:36:37
2011-04-14T21:39:53
Java
UTF-8
Java
false
false
716
java
package com.elmakers.mine.bukkit.utility.platform; import java.util.List; import javax.annotation.Nullable; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public interface SpigotUtils { void sendMessage(CommandSender sender, String message); boolean sendActionBar(Player player, String message); boolean sendActionBar(Player player, String message, String font); @Nullable String serializeBossBar(String title); @Nullable String serializeBossBar(String title, String font); String getHexColor(String hexCode); String translateColors(String message); String stripColor(String message); List<String> serializeLore(List<String> lore); }
b25542ad4641d9ede21e398055f340eead7cb71e
528eeefa078879d549e7f11a1547f2d84aec27ce
/src/main/java/com/seniorsteps/trainningcenter/security/SecurityWebApplicationInitializer.java
3146c2cc1e84aec948183ea67a5456b3c83ba106
[]
no_license
AhmedElsheikh680/trainning-center-ms
779f8217e5df2b25f4ad0b4068a4a80516b836ab
b1fe97184e185b013e13a4222f1d7ab7a033e412
refs/heads/main
2023-01-21T10:30:52.675568
2020-12-05T21:14:32
2020-12-05T21:14:32
316,808,077
0
0
null
null
null
null
UTF-8
Java
false
false
248
java
package com.seniorsteps.trainningcenter.security; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { }
f7b62a78a6a049f4e16affda8ebc60476aaade62
8d15e71a02046144195b1187220f440a586715a7
/app/src/androidTest/java/com/lyk/immersivenote/ApplicationTest.java
187654eae4d7dd3ef4777f60df53c2b4dd1c2b6c
[]
no_license
moniren/CustomNote
31e15d55aaec1c5994b5c4c2e337fde2ef99f3e0
f4ef6fe7dda7e6a8afe811221359efa0319be700
refs/heads/master
2021-01-02T09:25:58.785579
2015-09-06T16:03:31
2015-09-06T16:03:31
41,159,324
4
0
null
null
null
null
UTF-8
Java
false
false
352
java
package com.lyk.immersivenote; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
fb89ac168e9cd2f56921ca8560ca13b1483c2b3e
89881fdc049acf59902210c3fbc146b1bed7cd2a
/gdchat/ๆœๅŠก็ซฏ/comm-modules/api-module/src/main/java/com/shiku/im/api/controller/NearbyController.java
10fecc98e0fc5f657caf5f69d2d49680f27caf34
[]
no_license
OuBigWhite/mymost3
18ba5dc6030b772cccaf5f0e3e1b3a101ecdde37
8f099a2ca59f7f591eae19b058edbd321cec4008
refs/heads/main
2023-07-27T01:06:54.605976
2021-09-02T13:08:18
2021-09-02T13:08:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,714
java
package com.shiku.im.api.controller; import com.shiku.im.comm.constants.KConstants; import com.shiku.im.comm.ex.ServiceException; import com.shiku.im.comm.utils.ReqUtil; import com.shiku.im.config.AppConfig; import com.shiku.im.user.entity.User; import com.shiku.im.user.model.NearbyUser; import com.shiku.im.user.service.impl.UserManagerImpl; import com.shiku.im.vo.JSONMessage; import com.shiku.utils.StringUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; /** * ้™„่ฟ‘ๆŽฅๅฃ * * * */ @Api(value="NearbyController",tags="้™„่ฟ‘ๆŽฅๅฃ") @RestController @RequestMapping(value="/nearby",method={RequestMethod.GET,RequestMethod.POST}) public class NearbyController { @Autowired private UserManagerImpl userManager; @Autowired private AppConfig appConfig; //้™„่ฟ‘็š„็”จๆˆท @ApiOperation("้™„่ฟ‘็š„็”จๆˆท") @RequestMapping(value = "/user") public JSONMessage nearbyUser(@ModelAttribute NearbyUser poi) { try { if(StringUtil.isEmpty(poi.getNickname())){ byte disableNearbyUser =appConfig.getDisableNearbyUser(); if(1==disableNearbyUser){ if(0==poi.getPageIndex()){ User user =userManager.getUser("8618938880001"); if(null!=user){ List<User> dataList=new ArrayList<>(); user.buildNoSelfUserVo(ReqUtil.getUserId()); user.setLoc(new User.Loc(poi.getLongitude(),poi.getLatitude())); dataList.add(user); return JSONMessage.success(dataList); } }else{ return JSONMessage.success(new ArrayList<>()); } } } List<User> nearbyUser=userManager.nearbyUser(poi); return JSONMessage.success(nearbyUser); } catch (ServiceException e) { return JSONMessage.failureByException(e); } } //้™„่ฟ‘็š„็”จๆˆท๏ผˆ็”จไบŽweb็‰ˆๅˆ†้กต๏ผ‰ @ApiOperation("้™„่ฟ‘็š„็”จๆˆท") @RequestMapping(value = "/nearbyUserWeb") public JSONMessage nearbyUserWeb(@ModelAttribute NearbyUser poi) { try { Object nearbyUser =userManager.nearbyUserWeb(poi); return JSONMessage.success(nearbyUser); } catch (Exception e) { return JSONMessage.failureByErrCode(KConstants.ResultCode.UserNotExist); } } //ๆœ€ๆ–ฐ็š„็”จๆˆท @RequestMapping("/newUser") @ApiOperation("ๆœ€ๆ–ฐ็š„็”จๆˆท") @ApiImplicitParams({ @ApiImplicitParam(paramType="query" , name="access_token" , value="ๆŽˆๆƒ้’ฅๅŒ™",dataType="String",required=true), @ApiImplicitParam(paramType="query" , name="pageIndex" , value="ๅฝ“ๅ‰้กต็ ๆ•ฐ",dataType="String"), @ApiImplicitParam(paramType="query" , name="pageSize" , value="ๆฏ้กตๆ•ฐๆฎๆกๆ•ฐ",dataType="String") }) public JSONMessage newUser(@RequestParam(defaultValue="0") int pageIndex,@RequestParam(defaultValue="12") int pageSize,@RequestParam(defaultValue="0") int isAuth) { JSONMessage jMessage = null; try { String phone =userManager.getUser(ReqUtil.getUserId()).getPhone(); if(!StringUtil.isEmpty(phone) && !phone.equals("18938880001")) { return JSONMessage.failureByErrCode(KConstants.ResultCode.NO_PERMISSION); } List<User> dataList =userManager.getUserlimit(pageIndex, pageSize,isAuth); if(null != dataList && dataList.size()>0){ User.LoginLog loginLog=null; for (User user : dataList) { loginLog=userManager.getLogin(user.getUserId()); user.setLoginLog(loginLog); } jMessage = JSONMessage.success(null,dataList); } } catch (ServiceException e) { return JSONMessage.failureByException(e); } return jMessage; } }
f13d8269057f247b1c417ca7ad9fe6045df49856
e1c1e452909527844e0ff5791f8a1dde1a2bf67d
/src/test/java/orgs/androidtown/customgallery/ExampleUnitTest.java
df9c2e533b1c0e9c3cb9bedcafd455ecbcf587b9
[]
no_license
JisangYou/ADS_Android_CustomGallery
cfce3c4043e91612ee9a6f6c0b6cf490d0519a09
d3febb7461a56ec88d96d948ded9723d310c385f
refs/heads/master
2021-09-03T14:19:31.936353
2018-01-09T19:11:37
2018-01-09T19:11:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
408
java
package orgs.androidtown.customgallery; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
498029927dc0fa4b5d0e20099524a98842448a2c
a866495f863acf920f76ac56913305314ee58dca
/sample/src/main/java/me/xiaopan/sketchsample/adapter/itemfactory/PhotoAlbumItemFactory.java
2d3b587e49c20d4851eddc5bf888e18ff70c3de8
[ "Apache-2.0" ]
permissive
PureAway/Sketch
3cfd8e8abbfdd936fffd31652f38daf8c7c93087
ebb5710f1a56d3b94f39867492190db89c4ce977
refs/heads/master
2020-06-10T18:25:38.566771
2016-11-29T09:13:37
2016-11-29T09:13:37
75,910,416
1
0
null
2016-12-08T06:36:21
2016-12-08T06:36:19
null
UTF-8
Java
false
false
4,953
java
package me.xiaopan.sketchsample.adapter.itemfactory; import android.content.Context; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.View; import android.view.ViewGroup; import butterknife.BindView; import me.xiaopan.assemblyadapter.AssemblyRecyclerItemFactory; import me.xiaopan.sketch.SketchImageView; import me.xiaopan.sketch.request.DisplayOptions; import me.xiaopan.sketch.shaper.ImageShaper; import me.xiaopan.sketch.shaper.RoundRectImageShaper; import me.xiaopan.sketch.util.SketchUtils; import me.xiaopan.sketchsample.ImageOptions; import me.xiaopan.sketchsample.R; import me.xiaopan.sketchsample.adapter.BindAssemblyRecyclerItem; import me.xiaopan.sketchsample.util.Settings; import me.xiaopan.sketchsample.widget.MyImageView; public class PhotoAlbumItemFactory extends AssemblyRecyclerItemFactory<PhotoAlbumItemFactory.PhotoAlbumItem> { private OnImageClickListener onImageClickListener; private int itemSize; public PhotoAlbumItemFactory(OnImageClickListener onImageClickListener) { this.onImageClickListener = onImageClickListener; } @Override public boolean isTarget(Object o) { return o instanceof String; } @Override public PhotoAlbumItem createAssemblyItem(ViewGroup viewGroup) { if (itemSize == 0) { itemSize = -1; if (viewGroup instanceof RecyclerView) { int spanCount = 1; RecyclerView recyclerView = (RecyclerView) viewGroup; RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { spanCount = ((GridLayoutManager) recyclerView.getLayoutManager()).getSpanCount(); } else if (layoutManager instanceof StaggeredGridLayoutManager) { spanCount = ((StaggeredGridLayoutManager) recyclerView.getLayoutManager()).getSpanCount(); } if (spanCount > 1) { int screenWidth = viewGroup.getResources().getDisplayMetrics().widthPixels; itemSize = (screenWidth - (SketchUtils.dp2px(viewGroup.getContext(), 8) * (spanCount + 1))) / spanCount; } } } return new PhotoAlbumItem(R.layout.list_item_photo_album_image, viewGroup); } public interface OnImageClickListener { void onImageClick(int position, String loadingImageOptionsId); } public class PhotoAlbumItem extends BindAssemblyRecyclerItem<String> { @BindView(R.id.image_photoAlbumImageItem) MyImageView sketchImageView; public PhotoAlbumItem(int itemLayoutId, ViewGroup parent) { super(itemLayoutId, parent); } @Override protected void onConfigViews(Context context) { sketchImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (onImageClickListener != null) { onImageClickListener.onImageClick(getAdapterPosition(), getData()); } } }); sketchImageView.setOptionsByName(ImageOptions.ROUND_RECT); ImageShaper imageShaper = sketchImageView.getOptions().getImageShaper(); if (imageShaper != null && imageShaper instanceof RoundRectImageShaper) { RoundRectImageShaper roundRectImageShaper = (RoundRectImageShaper) imageShaper; sketchImageView.setImageShape(SketchImageView.ImageShape.ROUNDED_RECT); sketchImageView.setImageShapeCornerRadius(roundRectImageShaper.getOuterRadii()); } if (itemSize > 0) { ViewGroup.LayoutParams layoutParams = sketchImageView.getLayoutParams(); layoutParams.width = itemSize; layoutParams.height = itemSize; sketchImageView.setLayoutParams(layoutParams); } } @Override protected void onSetData(int i, String imageUri) { boolean thumbnailMode = Settings.getBoolean(sketchImageView.getContext(), Settings.PREFERENCE_THUMBNAIL_MODE); DisplayOptions options = sketchImageView.getOptions(); options.setThumbnailMode(thumbnailMode); options.setCacheProcessedImageInDisk(Settings.getBoolean(sketchImageView.getContext(), Settings.PREFERENCE_CACHE_PROCESSED_IMAGE)); if (thumbnailMode) { if (options.getResize() == null && !options.isResizeByFixedSize()) { options.setResizeByFixedSize(true); } } else { options.setResizeByFixedSize(false); } sketchImageView.displayImage(imageUri); } } }
9880911d46e4d27b2251defcc1abb4e81a6f36ed
e7de78f2a54b2c252701c397df1d7f9c6d08803a
/src/service/ValidationDeLaSommeDesCaracteresDuJoueur.java
a50d8f504728e7f462c79049b220b5184ade023a
[]
no_license
borisgnimadi/magiword
aeb963e8687c13cd2ad427c138b72bcf41c2ff5c
b850afa4399c82434f7d02c570e0e1815e2efebe
refs/heads/master
2020-04-13T09:36:18.129663
2019-01-02T22:49:22
2019-01-02T22:49:22
163,115,750
0
0
null
null
null
null
ISO-8859-1
Java
false
false
1,136
java
package service; /** * Cette classe contient les mรฉthodes de validation des caractรจres des joueurs * @author user * */ public class ValidationDeLaSommeDesCaracteresDuJoueur { public static boolean validationNiveauOK (double valeurMaxAutorise) { boolean niveauOK = valeurMaxAutorise>=1 && valeurMaxAutorise <= 100 ? true : false ; return niveauOK; } public static boolean validationForceOK (double valeurMaxAutorise, double forceJoueurNumero) { boolean forceOK = (forceJoueurNumero <= valeurMaxAutorise) && validationNiveauOK(valeurMaxAutorise)? true : false ; return forceOK; } public static boolean validationIntelligenceOK (double d, double e, int valeurIntelligence) { boolean intelligenceOK = (e + valeurIntelligence <= d) && validationNiveauOK(d) ? true : false ; return intelligenceOK; } public static boolean validationAgiliteOK (double valeurNiveau, double valeurForce, double valeurIntelligence, double valeurAgilite) { boolean agiliteOK = (valeurForce + valeurIntelligence + valeurAgilite == valeurNiveau) && validationNiveauOK(valeurNiveau) ? true : false ; return agiliteOK; } }
fb7a52312771c536d4f817d028c7bd3cb98f03bd
379122f23b9d3b23ddc28e4dff996cf36e77c200
/src/main/java/admin/controllers/AdminDeactivatedStudents.java
bb1a72c66e2c1d7863d5e0e0e07936a341f7c0aa
[]
no_license
kalpeshrawal96/OnlineAttenadnceSystem
3aa5fab36e9f85f1935014c0900c06bb3fb9983d
6b63c7e940f9716d9cb1090ec81b56c8926db359
refs/heads/master
2020-07-03T15:46:41.673012
2019-08-12T15:29:53
2019-08-12T15:29:53
201,956,523
0
0
null
null
null
null
UTF-8
Java
false
false
1,039
java
/* * 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 admin.controllers; import entities.*; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import utility.Controller; import javax.persistence.criteria.JoinType; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.PrintWriter; import java.util.List; /** * @author sukhvir */ @WebServlet(urlPatterns = "/admin/students/deactivated") public class AdminDeactivatedStudents extends Controller { @Override public void process(HttpServletRequest req, HttpServletResponse resp, Session session, HttpSession httpSession, PrintWriter out) throws Exception { req.getRequestDispatcher("/WEB-INF/admin/deactivated-students.jsp") .include(req, resp); } }
c160cffbbef9e28a2c77c28f27cb1db1e799bcff
1281f3f1ce823b57b4b1c849755945ef63a93cae
/core/src/org/joat/mow/Model/DepthFirstSearch.java
b4acbdd41f34a708021a1e94b8b1bdfa72bdd0bd
[ "MIT" ]
permissive
bergmannf/MapsOfWar
c06e2f3eb2ac819500722a2fba6fc111feadaaa6
748e8c826d3352c7744448970c3d0f438de88d4f
refs/heads/master
2020-05-27T05:40:40.941114
2014-08-10T14:14:20
2014-08-10T14:14:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,078
java
package org.joat.mow.Model; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * Implementation of a depth first search. */ public class DepthFirstSearch { private final Graph graph; public DepthFirstSearch(Graph g) { this.graph = g; } /** * Returns a collection of all cells reachable from the start in maxDepth-steps. * @param start The start cell. * @param maxDepth The maximum depth to traverse. * @return A collection of reachable cells. */ public Collection<Cell> search(Cell start, int maxDepth) { Set<Cell> cells = new HashSet<Cell>(); this.search(start, maxDepth, cells); return cells; } private void search(Cell start, int maxDepth, Set<Cell> accumulator) { if (maxDepth == 0) { return; } Set<Edge> edges = this.graph.getAdjacencyList().get(start); for (Edge edge : edges) { accumulator.add(edge.end); this.search(edge.end, maxDepth - edge.cost, accumulator); } } }
4d4603487fbef164117e5988fd1388313e29564d
decb48786c9d47af82b6efa6ba61041ade0ccfb9
/jmx/src/test/java/rewards/RewardNetworkTests.java
813f37f96a2b345ec1c6dec526e4a78e7556b9a7
[]
no_license
CrAzE124/spring-certification
1c39421f593f05f993b83bce1c9b007fe0ca1c60
a4aad094fa946034558b1ced130bbb0b9548c3dc
refs/heads/master
2021-03-27T10:33:29.545195
2017-10-15T08:36:16
2017-10-15T08:36:16
101,179,285
2
1
null
null
null
null
UTF-8
Java
false
false
2,490
java
package rewards; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import common.money.MonetaryAmount; import config.RootConfig; /** * A system test that verifies the components of the RewardNetwork application work together to reward for dining * successfully. Uses Spring to bootstrap the application for use in a test environment. */ @ActiveProfiles("jpa") @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration // See the inner class below public class RewardNetworkTests { @Configuration @Import(RootConfig.class) public static class Config{ } /** * The object being tested. */ @Autowired private RewardNetwork rewardNetwork; @Test public void testRewardForDining() { // create a new dining of 100.00 charged to credit card '1234123412341234' by merchant '123457890' as test input Dining dining = Dining.createDining("100.00", "1234123412341234", "1234567890"); // call the 'rewardNetwork' to test its rewardAccountFor(Dining) method RewardConfirmation confirmation = rewardNetwork.rewardAccountFor(dining); // assert the expected reward confirmation results assertNotNull(confirmation); assertNotNull(confirmation.getConfirmationNumber()); // assert an account contribution was made AccountContribution contribution = confirmation.getAccountContribution(); assertNotNull(contribution); // the contribution account number should be '123456789' assertEquals("123456789", contribution.getAccountNumber()); // the total contribution amount should be 8.00 (8% of 100.00) assertEquals(MonetaryAmount.valueOf("8.00"), contribution.getAmount()); // the total contribution amount should have been split into 2 distributions assertEquals(2, contribution.getDistributions().size()); // each distribution should be 4.00 (as both have a 50% allocation) assertEquals(MonetaryAmount.valueOf("4.00"), contribution.getDistribution("Annabelle").getAmount()); assertEquals(MonetaryAmount.valueOf("4.00"), contribution.getDistribution("Corgan").getAmount()); } }
581c85d6b65201ba4cad9a12d26e760d4e63c14b
a52fcaa52f001b40ed21f57b4f0d11474f42028a
/ReflectClass/src/main/java/cn/cobight/beforeclass/demo.java
cff2bfef26f728dc8476ba9ad0aa059850c80f32
[]
no_license
cobight/secondstage
4e4e6f3bc97b801d2fd39b10e3216a55c991e6c7
c8d0105ea326deca211e2659bade75633797a464
refs/heads/master
2023-01-04T11:09:10.391732
2020-10-20T13:39:46
2020-10-20T13:39:46
290,418,379
0
0
null
null
null
null
UTF-8
Java
false
false
1,773
java
package cn.cobight.beforeclass; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @ClassName demo * @Description TODO * @Author cobight * @CreateTime 2020/8/26 8:33 * @Version 1.0 **/ public class demo { public static void main(String[] args) { Class<Cat> c = Cat.class; try { //ๆ‹ฟๅˆฐๆŒ‡ๅฎšๅ‚ๆ•ฐ็š„ๆž„้€ ๆ–นๆณ• Constructor<Cat> declaredConstructor = c.getDeclaredConstructor(String.class); //้€š่ฟ‡ๆž„้€ ๆ–นๆณ•new ๅฎžไพ‹ Cat cat = declaredConstructor.newInstance("ๅฐๆ™บ"); //่Žทๅ–ๆŒ‡ๅฎšๆˆๅ‘˜ๅ˜้‡ๅฏน่ฑก Field age = c.getDeclaredField("age"); //่ต‹ๅ€ผ age.setAccessible(true); age.set(cat,5); //่Žทๅ–ๆŒ‡ๅฎšๆ–นๆณ•ๅฏน่ฑก Method doSomeThing = c.getDeclaredMethod("doSomeThing",String.class); //่ฎฉๆŒ‡ๅฎšๅฏน่ฑก ๅธฆๅ‚ๆ‰ง่กŒ doSomeThing.invoke(cat,"eatting"); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } } } class Cat{ private String name; private Integer age; public Cat(){} public Cat(String name){ this.name=name; } /** *ๅšไป€ไนˆไบ‹ๆƒ… */ public void doSomeThing(String someThing){ System.out.println("ๆˆ‘ๅซ"+name+"ไปŠๅนด"+age+"ๅฒ,ๅœจ"+someThing); } }
598a3021a1cba171aacf7291abd8ad7716e8e542
5455234f3ea8e60a400c45f7d5c1786e29b882c7
/springcloud-securedms/src/main/java/com/example/model/TollUsage.java
a928214dd4e572688ae108c3dfe8a22406ab5c51
[]
no_license
muktar123/SOA-4thApril17
e024969fece04734717e4670c91322a7322532cb
3553b8598d6641f995c74e2ca7fd318b49122a96
refs/heads/master
2021-01-19T00:17:30.402717
2017-03-24T01:58:23
2017-03-24T01:58:23
87,149,601
0
0
null
null
null
null
UTF-8
Java
false
false
1,087
java
package com.example.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection="toll") public class TollUsage { @Id private String id; private String stationId; private String licensePlate; private String timeStamp; public TollUsage() { } public TollUsage(String id, String stationId, String licensePlate, String timeStamp) { super(); this.id = id; this.stationId = stationId; this.licensePlate = licensePlate; this.timeStamp = timeStamp; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getStationId() { return stationId; } public void setStationId(String stationId) { this.stationId = stationId; } public String getLicensePlate() { return licensePlate; } public void setLicensePlate(String licensePlate) { this.licensePlate = licensePlate; } public String getTimeStamp() { return timeStamp; } public void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } }
892d0884d23ba783c89e770aab314a3101780b7d
e37b5bcb043c6f747921a59058ece31704d338db
/SocialNetwork/Server/src/test/java/kl/socialnetwork/validations/serviceValidation/servicesImpl/RelationshipValidationServiceTests.java
08e305edbee94061cdf5546cf9f3f321f7d15740
[ "MIT" ]
permissive
kostadinlambov/Social-Network-Custom-Webpack-Config
270b05a48d72cf89ca14b332ebb3267d6b487094
e5e5f769e3fc3121cc4a91c7e4531bf255e6bfa3
refs/heads/master
2023-01-11T16:38:57.537088
2019-09-12T23:22:06
2019-09-12T23:22:06
207,564,784
0
0
MIT
2023-01-01T11:10:26
2019-09-10T13:19:11
Java
UTF-8
Java
false
false
1,384
java
package kl.socialnetwork.validations.serviceValidation.servicesImpl; import kl.socialnetwork.domain.entities.Relationship; import kl.socialnetwork.domain.entities.User; import kl.socialnetwork.testUtils.RelationshipsUtils; import kl.socialnetwork.testUtils.UsersUtils; import kl.socialnetwork.validations.serviceValidation.services.RelationshipValidationService; import org.junit.Before; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class RelationshipValidationServiceTests { private RelationshipValidationService relationshipValidationService; @Before public void setupTest(){ relationshipValidationService = new RelationshipValidationServiceImpl(); } @Test public void isValid_whenValid_true(){ List<User> users = UsersUtils.getUsers(2); User userOne = users.get(0); User userTwo = users.get(1); Relationship relationship = RelationshipsUtils.createRelationship(userOne, userTwo, 0, userOne); boolean result = relationshipValidationService.isValid(relationship); assertTrue(result); } @Test public void isValid_whenNull_false(){ Relationship relationship = null; boolean result = relationshipValidationService.isValid(relationship); assertFalse(result); } }