blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
listlengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
listlengths
1
1
author
stringlengths
0
161
b56eea7cd96604166145069758c87821b0ff3162
c861827ee403b282eb9119b7d74dc4e8e6b0dcb1
/app/src/main/java/es/ulpgc/eite/cleancode/quiz/QuestionRepository.java
cb6a8588803a9db7f04bda2e2d05b56c56591181
[]
no_license
DayronYaret/QuizLab2.1
a876d2c74b47912642fb809bf7fb7362e4b5005f
0fd2840fe19ec77091e541bc8b5759d2b732b225
refs/heads/master
2020-04-23T04:09:45.970477
2019-02-15T13:58:50
2019-02-15T13:58:50
170,900,603
0
0
null
null
null
null
UTF-8
Java
false
false
344
java
package es.ulpgc.eite.cleancode.quiz; public interface QuestionRepository { Boolean getCurrentAnswer(); String getCurrentQuestion(); void setupNextQuestion(); String getCurrentResult(); Integer getCurrentIndex(); void setCurrentIndex(Integer index); void checkCurrentAnswer(boolean userAnswer); boolean existNextQuestion(); }
[ "lhdez@iuma.ulpgc.es" ]
lhdez@iuma.ulpgc.es
951351048ccf157544d9a7890a8f63e907aa41c9
1a870eff07c27476074f979d8e5abddde2646840
/com/sun/corba/se/spi/activation/EndpointInfoListHelper.java
ee5a60b770e5c6f4427c6ea3ba266c929d40307f
[ "Apache-2.0" ]
permissive
zhenjunMa/JDK8Translation
ef6684e2292a6646129ba4206af136ffd292d0b0
0f9269a359b7ef2a778d89fb4e82ac4e47ea26e9
refs/heads/master
2021-06-07T18:59:11.037612
2020-09-18T02:49:43
2020-09-18T02:49:43
97,243,202
13
5
null
2020-09-18T02:49:44
2017-07-14T14:36:54
Java
UTF-8
Java
false
false
2,237
java
package com.sun.corba.se.spi.activation; /** * com/sun/corba/se/spi/activation/EndpointInfoListHelper.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from /Users/java_re/workspace/8-2-build-macosx-x86_64/jdk8u111/7883/corba/src/share/classes/com/sun/corba/se/spi/activation/activation.idl * Thursday, September 22, 2016 3:33:14 PM PDT */ abstract public class EndpointInfoListHelper { private static String _id = "IDL:activation/EndpointInfoList:1.0"; public static void insert (org.omg.CORBA.Any a, com.sun.corba.se.spi.activation.EndPointInfo[] that) { org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); a.type (type ()); write (out, that); a.read_value (out.create_input_stream (), type ()); } public static com.sun.corba.se.spi.activation.EndPointInfo[] extract (org.omg.CORBA.Any a) { return read (a.create_input_stream ()); } private static org.omg.CORBA.TypeCode __typeCode = null; synchronized public static org.omg.CORBA.TypeCode type () { if (__typeCode == null) { __typeCode = com.sun.corba.se.spi.activation.EndPointInfoHelper.type (); __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.corba.se.spi.activation.EndpointInfoListHelper.id (), "EndpointInfoList", __typeCode); } return __typeCode; } public static String id () { return _id; } public static com.sun.corba.se.spi.activation.EndPointInfo[] read (org.omg.CORBA.portable.InputStream istream) { com.sun.corba.se.spi.activation.EndPointInfo value[] = null; int _len0 = istream.read_long (); value = new com.sun.corba.se.spi.activation.EndPointInfo[_len0]; for (int _o1 = 0;_o1 < value.length; ++_o1) value[_o1] = com.sun.corba.se.spi.activation.EndPointInfoHelper.read (istream); return value; } public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.corba.se.spi.activation.EndPointInfo[] value) { ostream.write_long (value.length); for (int _i0 = 0;_i0 < value.length; ++_i0) com.sun.corba.se.spi.activation.EndPointInfoHelper.write (ostream, value[_i0]); } }
[ "mzj911101@yahoo.com" ]
mzj911101@yahoo.com
e56f6f04741da5b925b9eb3c37ebdc7e7e9a3443
a65c2b08239dec537badb39a81f6c2121fb66661
/api/src/org/mindswap/utils/QNameProvider.java
dccc2577270fe8af27e60c4591235528ec1ae927
[ "MIT" ]
permissive
FORMAS/OWL-S-Composer
9e466e1d11e5907fb20b3b5ee462ba55548150b0
73ef10bbde215cf8ebea0f60222975fd3dfeedad
refs/heads/develop
2021-06-02T03:30:04.858400
2019-07-18T20:10:54
2019-07-18T20:10:54
6,789,163
4
3
null
2013-11-19T11:56:38
2012-11-21T03:05:09
Java
UTF-8
Java
false
false
6,575
java
/* * Created on May 13, 2004 */ package org.mindswap.utils; import java.net.URI; import java.util.Hashtable; import java.util.Map; import java.util.Set; import org.mindswap.owl.vocabulary.OWL; import org.mindswap.owl.vocabulary.RDF; import org.mindswap.owl.vocabulary.RDFS; import org.mindswap.owl.vocabulary.XSD; /** * A class to convert URI's to QNames. Borrowed from SWOOP code. * * @author Evren Sirin */ public class QNameProvider { // stores a map of uri -> prefix Map uriToPrefix; Map prefixToUri; /** * */ public QNameProvider() { uriToPrefix = new Hashtable(); prefixToUri = new Hashtable(); // initialize it with standard stuff setMapping("owl", OWL.ns); setMapping("rdf", RDF.ns); setMapping("rdfs", RDFS.ns); setMapping("xsd", XSD.ns); } public static boolean isNameStartChar(char ch) { return (Character.isLetter(ch) || ch == '_'); } public static boolean isNameChar(char ch) { return (isNameStartChar(ch) || Character.isDigit(ch) || ch == '.' || ch == '-'); } public static int findNameStartIndex(String str) { char[] strChars = str.toCharArray(); int nameStartIndex = -1; boolean foundNameChar = false; for(int strIndex = strChars.length - 1; strIndex >= 0; strIndex--) { char letter = strChars[strIndex]; if(isNameStartChar(letter)) { nameStartIndex = strIndex; foundNameChar = true; } else if(foundNameChar && !isNameChar(letter)) { break; } } return nameStartIndex; } public static int findLastNameIndex(String str) { char[] strChars = str.toCharArray(); int nameIndex = -1; for(int strIndex = strChars.length - 1; strIndex >= 0; strIndex--) { char letter = strChars[strIndex]; if(isNameChar(letter)) { nameIndex = strIndex; } else { break; } } return nameIndex; } public static int findNextNonNameIndex(String str, int startIndex) { char[] strChars = str.toCharArray(); int nameIndex = startIndex; for(nameIndex = startIndex; nameIndex < strChars.length; nameIndex++) { char letter = strChars[nameIndex]; if(!isNameChar(letter)) { break; } } return nameIndex; } protected static String[] splitURI(String uriString) { int nameStart, prefixStart, prefixEnd; String base, prefix, name; String[] bpn = new String[3]; nameStart = findLastNameIndex(uriString); if(nameStart < 0) { //System.out.println("Couldn't find name for "+uriString); return null; } name = uriString.substring(nameStart); if(nameStart == 0) { //System.out.println("Name starts at beginning"); base = ""; prefix = "a"; // Pick a unique prefix later } else { base = uriString.substring(0, nameStart); //System.out.println("Uri: "+ uri + " Base: " +base); prefixStart = findNameStartIndex(base); if(prefixStart < 0) { //System.out.println("Prefix < 0"); prefix = "b"; // Pick a uniqe prefix later } else { prefixEnd = findNextNonNameIndex(base, prefixStart + 1); prefix = uriString.substring(prefixStart, prefixEnd); } } bpn[0] = base; bpn[1] = prefix; bpn[2] = name; return bpn; } public String getPrefix(String uri) { return (String) uriToPrefix.get(uri); } public String getURI(String prefix) { return (String) prefixToUri.get(prefix); } public void removePrefix(String prefix) { String uri = (String) prefixToUri.remove(prefix); if(uri != null) uriToPrefix.remove(uri); } public boolean setMapping(String prefix, String uri) { String currentUri = getURI(prefix); if(currentUri == null) { //System.out.println("Setting prefix "+prefix+": "+uri); prefixToUri.put(prefix, uri); uriToPrefix.put(uri, prefix); return true; } else if(currentUri == uri) { return true; } else { return false; } } public Set getPrefixSet() { return prefixToUri.keySet(); } public Set getURISet() { return uriToPrefix.keySet(); } public String shortForm(URI uri) { return shortForm(uri.toString()); } public String shortForm(String uri) { //System.out.println("Shortform for " + uri); return shortForm(uri, true); } public String shortForm(String uri, boolean default_to_uri) { String[] bpn = splitURI(uri); String base, possible_prefix, prefix, name; String qname; if(bpn == null) { if(default_to_uri) { return uri; } else { return null; } } base = bpn[0]; possible_prefix = bpn[1]; name = bpn[2]; if(possible_prefix.endsWith(".owl") || possible_prefix.endsWith(".rdf") || possible_prefix.endsWith(".xml")) possible_prefix = possible_prefix.substring(0, possible_prefix .length() - 4); if(Character.isLowerCase(possible_prefix.charAt(1))) possible_prefix = Character.toLowerCase(possible_prefix.charAt(0)) + possible_prefix.substring(1, possible_prefix.length()); prefix = getPrefix(base); if(prefix == null) { // Check prefix for uniqueness prefix = possible_prefix; int mod = 0; while(!setMapping(prefix, base)) { prefix = possible_prefix + mod; mod++; } } qname = prefix + ":" + name; return qname; } public String longForm(String qname) { String[] str = qname.split(":"); String prefix = str[0]; String localName = str[1]; String uri = getURI(prefix); if(uri == null) throw new IllegalArgumentException("Prefix " + prefix + " is not known!"); return uri + localName; } }
[ "marcoafilho@gmail.com" ]
marcoafilho@gmail.com
0d47169941304903789dfd2d47c90d8883240808
fbb8204c29f1d7d5f4b385a956854ddca2bb8e61
/src/main/java/pe/edu/upn/model/repository/UsuarioRepository.java
a28f063b8189c9e9364334bed9a75739b18c37da
[]
no_license
yalucepadi/restauranteRest
949c0d205fd9adb7c596ebe1422bedf9213a63b6
d0976499784706bb0a185d5319be5185873d1d1f
refs/heads/master
2020-09-29T01:28:38.983940
2019-12-09T17:02:38
2019-12-09T17:02:38
226,914,237
0
0
null
null
null
null
UTF-8
Java
false
false
371
java
package pe.edu.upn.model.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import pe.edu.upn.model.entity.Usuario; @Repository public interface UsuarioRepository extends JpaRepository<Usuario, Long> { Optional<Usuario> findByUsuarioNombre(String usuarioNombre); }
[ "yalucepa@gmail.com" ]
yalucepa@gmail.com
fb9d06b83a8d1716a20ceb5435479b961524ac42
6d1625b17a770cf56235fec16ba2a67ced23fb6c
/src/imageviewer_MVC/model/Image.java
f44d648522ccbde048c74a667c1e15741b5e0522
[]
no_license
rarbelo14/ImageViewer
b0df933937026007700b61f744778a78b6b094b8
777aafba44e6a353e80f0aff782d5235eb322426
refs/heads/master
2023-02-20T11:49:18.670596
2021-01-25T17:20:43
2021-01-25T17:20:43
318,614,656
0
1
null
null
null
null
UTF-8
Java
false
false
234
java
package imageviewer_MVC.model; public class Image { private final String name; public Image(String name) { this.name = name; } public String getName() { return name; } }
[ "Ricardo@DESKTOP-LPK2S35" ]
Ricardo@DESKTOP-LPK2S35
1cfeb9c14f3c6ed8384050e6b0b4d1bc4bc645e9
bed867264cc7b496dc3f017af1446e78ea8fe023
/src/main/java/org/apache/flink/QueryDueKey.java
3d408d03a01ec68f0e3c36a225c8087396e3efaf
[]
no_license
elidina/SABDNYT
e3296ee885de484f112bbe805db82ac775067f65
5e6b3cf1f153516211e550c8af00bf9d865d28c6
refs/heads/master
2020-06-19T09:17:09.451069
2019-07-12T23:58:12
2019-07-12T23:58:12
196,658,427
0
0
null
null
null
null
UTF-8
Java
false
false
5,817
java
package org.apache.flink; import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.common.functions.ReduceFunction; import org.apache.flink.core.fs.FileSystem; import org.apache.flink.entities.Comment; import org.apache.flink.entities.CommentQ2; import org.apache.flink.entities.CommentSchema; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor; import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.streaming.api.windowing.windows.TimeWindow; import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer; import org.apache.flink.util.Collector; import java.util.Calendar; import java.util.Date; import java.util.Properties; import java.util.TimeZone; import static org.apache.flink.utils.TimestampHandler.calcolaIndex; import static org.apache.flink.utils.TimestampHandler.estraiGiorno; /** * Implementazione della Query 2 senza custom window. * Ad ogni commento è stato assegnato un indice in base alla fascia oraria di appartenenza. * Lo stream è stato suddiviso in base alla key e la somma richiesta è stata calcolata con una reduce(). * Con una timewindow abbiamo calcolato i risultati nelle varie finestre temporali (un giorno, una settimana, un mese) e il risultato ottenuto è stato * scritto su un file di output. */ public class QueryDueKey { public static void main(String[] args) throws Exception { final int daily_Window_size = 24; final int weekly_Window_size = 24*7; final int monthly_Window_size = 24*30; final int window_dimension = daily_Window_size; String file_path = "query2_output_"+window_dimension+".txt"; final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); Properties properties = new Properties(); properties.setProperty("bootstrap.servers", "localhost:9092"); properties.setProperty("zookeeper.connect", "localhost:2181"); properties.setProperty("group.id", "flink"); DataStream<Comment> inputStream = env.addSource(new FlinkKafkaConsumer<>("flink", new CommentSchema(), properties)) .assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Comment>(Time.seconds(1)) { @Override public long extractTimestamp(Comment s) { //System.out.println(s.createDate * 1000); return s.createDate * 1000; } }) .filter(x -> x.userID != 0 && x.commentType.contains("comment")); DataStream<CommentQ2> windowCounts = inputStream.flatMap(new FlatMapFunction<Comment, CommentQ2>() { @Override public void flatMap(Comment c, Collector<CommentQ2> collector) throws Exception { int index = calcolaIndex(c.createDate*1000); int day = estraiGiorno(c.createDate*1000); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(c.createDate*1000); Date date = calendar.getTime(); CommentQ2 comment = new CommentQ2(c.createDate*1000, c.commentType, 1, index, day); collector.collect(comment); } }).keyBy("index") .timeWindow(Time.hours(24)) .reduce(new ReduceFunction<CommentQ2>() { @Override public CommentQ2 reduce(CommentQ2 commentQ2, CommentQ2 t1) throws Exception { return new CommentQ2(commentQ2.getTs(), t1.getType(), commentQ2.getCount() + t1.getCount(), commentQ2.getIndex(), commentQ2.getDay()); } }); DataStream<String> resultList = windowCounts .timeWindowAll(Time.hours(daily_Window_size)) .apply(new AllWindowFunction<CommentQ2, String, TimeWindow>() { @Override public void apply(TimeWindow timeWindow, Iterable<CommentQ2> iterable, Collector<String> collector) throws Exception { String result = new Date(timeWindow.getStart())+""; for (int i = 1; i < 13; i++) { boolean done = false; for(CommentQ2 c : iterable){ if(c.getIndex() == i){ done = true; //result += ", "+ ((i-1)*2)+"-"+ ((i*2)-1)+": "+c.getCount(); result += ", "+c.getCount(); } } if(!done){ result += ", 0"; } } System.out.println(result); collector.collect(result); } }); resultList.writeAsText(file_path, FileSystem.WriteMode.OVERWRITE).setParallelism(1); env.execute(); } }
[ "dinataleelisa@gmail.com" ]
dinataleelisa@gmail.com
c48b9434100b1947cd4bbe458b71afa9bb1d3a31
098f8fd9d20aede44266b873b4916b1215f4033a
/map_study/src/test/java/kr/or/dgit/it/map_study/ExampleUnitTest.java
52da4987e919b2de9f7e998dfa0d9b17d904896d
[]
no_license
hanseokPark/Chapter17_18
4e081b1c7e028e8d8ad10db58e89baff6a18aa30
575d52d9c5b2330915088e8adad1b89d6c620e23
refs/heads/master
2020-03-17T16:11:17.657883
2018-06-18T02:03:27
2018-06-18T02:03:27
133,738,912
0
0
null
null
null
null
UTF-8
Java
false
false
384
java
package kr.or.dgit.it.map_study; 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); } }
[ "es12850@naver.com" ]
es12850@naver.com
d1713f50b66bc7339a2083ddd7442a4ba3bcef81
220953d58fe923afa7b51b51ee5fde4caa2785ee
/WebScrapper/src/com/WebScrapper/setter/WebPage.java
75d349f69f25edb3e0a1564dda0a89080fd68cdc
[]
no_license
abdullah0116/WebScrapper
a9e0e437ce94f02aa3984960272f23748dd9963b
946c1d0d53cb9dca4633397840d7a8436138acd4
refs/heads/master
2020-03-17T20:58:09.561160
2018-05-18T10:31:27
2018-05-18T10:31:27
133,937,576
0
0
null
null
null
null
UTF-8
Java
false
false
1,016
java
package com.WebScrapper.setter; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import webscrapper.WebScrapper; public class WebPage { private Anchor anchor; private String webPageHash; private Document webDoc; private int anchorParseStatus; private int emailParseStatus; public WebPage(Anchor anchor) { this.anchor = anchor; } public Document getDoc() { return webDoc; } public void getWebDoc() { try { webDoc = Jsoup.connect(anchor.getAnchorURL()).get(); Elements links = webDoc.select("a"); for (Element elements : links) { System.out.println(elements.attr("abs:href")); } } catch (IOException ex) { Logger.getLogger(WebScrapper.class.getName()).log(Level.SEVERE, null, ex); } } }
[ "akasak56@gmail.com" ]
akasak56@gmail.com
1e57722cdc7f29599d66f11f755592a04cb1d540
69a4f2d51ebeea36c4d8192e25cfb5f3f77bef5e
/methods/Method_21095.java
d0859ae1a958320f878f49b97fddf7fd090ee03d
[]
no_license
P79N6A/icse_20_user_study
5b9c42c6384502fdc9588430899f257761f1f506
8a3676bc96059ea2c4f6d209016f5088a5628f3c
refs/heads/master
2020-06-24T08:25:22.606717
2019-07-25T15:31:16
2019-07-25T15:31:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
525
java
@OnClick(R.id.terms_and_privacy) protected void termsAndPrivacyClicked(){ final CharSequence[] items=new CharSequence[]{this.termsOfUseString,this.privacyPolicyString}; new AlertDialog.Builder(this).setItems(items,(__,which) -> { final Intent intent; if (which == 0) { intent=new Intent(this,HelpActivity.Terms.class); } else { intent=new Intent(this,HelpActivity.Privacy.class); } startActivityWithTransition(intent,R.anim.slide_in_right,R.anim.fade_out_slide_out_left); } ).show(); }
[ "sonnguyen@utdallas.edu" ]
sonnguyen@utdallas.edu
55ea42b75cd61e87ff03e0e389de6aeecc096f3a
dfc0ef8c3017ebfe80fe8ee657b4f593330d3ef6
/Reversed/framework/com/samsung/android/app/interactivepanoramaviewer/sharevia/EncoderInterface.java
bfb28028d3fc374edc1bb13010facdc93714e483
[]
no_license
khomsn/SCoverRE
fe079b6006281112ee37b66c5d156bb959e15420
2374565740e4c7bfc653b3f05bd9be519e722e32
refs/heads/master
2020-04-13T15:36:19.925426
2017-06-01T07:31:37
2017-06-01T07:31:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,241
java
package com.samsung.android.app.interactivepanoramaviewer.sharevia; import android.media.MediaCodec; import android.media.MediaCodec.BufferInfo; import android.media.MediaFormat; import android.media.MediaMuxer; import android.util.Log; import java.io.IOException; import java.nio.Buffer; import java.nio.ByteBuffer; public class EncoderInterface { private static final String MIME_TYPE = "video/avc"; private static final String TAG = "EncoderInterface"; private static final boolean VERBOSE = true; int EncBitRate = 6000000; int FRAME_RATE; int IFRAME_INTERVAL = 5; int TIMEOUT_USEC = 0; int frameEncoded; private BufferInfo mBufferInfo; private MediaCodec mEncoder; private MediaMuxer mMuxer; private boolean mMuxerStarted; private int mOrientation; private int mTrackIndex; private void drainEncoder(boolean z, byte[] bArr) { Log.m29d(TAG, "drainEncoder(" + z + ")"); ByteBuffer[] inputBuffers = this.mEncoder.getInputBuffers(); ByteBuffer[] outputBuffers = this.mEncoder.getOutputBuffers(); boolean z2 = z; while (true) { int dequeueInputBuffer; boolean z3; if (z) { dequeueInputBuffer = this.mEncoder.dequeueInputBuffer(0); if (dequeueInputBuffer < 0) { z3 = z2; } else { this.mEncoder.queueInputBuffer(dequeueInputBuffer, 0, 0, 0, 4); Log.m29d(TAG, "sending EOS to encoder"); z3 = z2; } } else if (z2) { z3 = z2; } else { dequeueInputBuffer = this.mEncoder.dequeueInputBuffer(0); if (dequeueInputBuffer < 0) { z3 = false; if (dequeueInputBuffer == -1) { Log.m29d(TAG, "no input available, spinning to encode buffer"); } } else { Buffer buffer = inputBuffers[dequeueInputBuffer]; buffer.position(0); buffer.put(bArr); buffer.position(0); int i = this.frameEncoded; this.frameEncoded = i + 1; long presentationTimeUs = getPresentationTimeUs(i); Log.m35v(TAG, "ts of frame " + (this.frameEncoded - 1) + " is " + presentationTimeUs); this.mEncoder.queueInputBuffer(dequeueInputBuffer, 0, bArr.length, presentationTimeUs, 0); z3 = true; } } dequeueInputBuffer = this.mEncoder.dequeueOutputBuffer(this.mBufferInfo, (long) this.TIMEOUT_USEC); if (dequeueInputBuffer != -1) { if (dequeueInputBuffer == -3) { outputBuffers = this.mEncoder.getOutputBuffers(); z2 = z3; } else if (dequeueInputBuffer != -2) { if (dequeueInputBuffer >= 0) { Buffer buffer2 = outputBuffers[dequeueInputBuffer]; if (buffer2 != null) { if ((this.mBufferInfo.flags & 2) != 0) { Log.m29d(TAG, "ignoring BUFFER_FLAG_CODEC_CONFIG"); this.mBufferInfo.size = 0; } if (this.mBufferInfo.size != 0) { if (this.mMuxerStarted) { buffer2.position(this.mBufferInfo.offset); buffer2.limit(this.mBufferInfo.offset + this.mBufferInfo.size); this.mMuxer.writeSampleData(this.mTrackIndex, buffer2, this.mBufferInfo); Log.m29d(TAG, "sent " + this.mBufferInfo.size + " bytes to muxer"); } else { throw new RuntimeException("muxer hasn't started"); } } this.mEncoder.releaseOutputBuffer(dequeueInputBuffer, false); if ((this.mBufferInfo.flags & 4) != 0) { break; } z2 = z3; } else { throw new RuntimeException("encoderOutputBuffer " + dequeueInputBuffer + " was null"); } } Log.m37w(TAG, "unexpected result from encoder.dequeueOutputBuffer: " + dequeueInputBuffer); z2 = z3; } else if (this.mMuxerStarted) { throw new RuntimeException("format changed twice"); } else { MediaFormat outputFormat = this.mEncoder.getOutputFormat(); Log.m29d(TAG, "encoder output format changed: " + outputFormat); this.mTrackIndex = this.mMuxer.addTrack(outputFormat); this.mMuxer.start(); this.mMuxerStarted = true; z2 = z3; } } else if (z || !z3) { Log.m29d(TAG, "no output available, spinning to await EOS"); z2 = z3; } else { return; } } if (z) { Log.m29d(TAG, "end of stream reached"); } else { Log.m37w(TAG, "reached end of stream unexpectedly"); } } private int prepareEncoder(int i, int i2, int i3, int i4, int i5, int i6, String str) { this.mBufferInfo = new BufferInfo(); MediaFormat createVideoFormat = MediaFormat.createVideoFormat(MIME_TYPE, i, i2); createVideoFormat.setInteger("color-format", 21); createVideoFormat.setInteger("bitrate", i3); createVideoFormat.setInteger("frame-rate", i4); createVideoFormat.setInteger("i-frame-interval", i5); Log.m29d(TAG, "format: " + createVideoFormat); try { this.mEncoder = MediaCodec.createEncoderByType(MIME_TYPE); this.mEncoder.configure(createVideoFormat, null, null, 1); this.mEncoder.start(); } catch (Throwable e) { e.printStackTrace(); } if (this.mEncoder != null) { Log.m33i(TAG, "Output file is " + str); try { this.mMuxer = new MediaMuxer(str, 0); this.mTrackIndex = -1; this.mMuxerStarted = false; return 0; } catch (IOException e2) { Log.m37w(TAG, "MediaMuxer creation failed"); return -1; } } Log.m31e(TAG, "mEncoder is null returning"); return -1; } private void releaseEncoder() { Log.m29d(TAG, "releasing encoder objects"); if (this.mEncoder != null) { this.mEncoder.stop(); this.mEncoder.release(); this.mEncoder = null; } if (this.mMuxer != null) { this.mMuxer.stop(); this.mMuxer.release(); this.mMuxer = null; } } public void deinit() { drainEncoder(true, null); releaseEncoder(); } public void encode(byte[] bArr) { drainEncoder(false, bArr); } long getPresentationTimeUs(int i) { return ((long) i) * ((long) (1000000 / this.FRAME_RATE)); } public int init(int i, int i2, int i3, int i4, int i5, int i6, String str, int i7) { if (str == null || str.isEmpty()) { Log.m29d(TAG, "wrong arguments to init"); return -1; } else if (i6 == 21) { this.FRAME_RATE = i4; this.EncBitRate = i3; this.mOrientation = i7; Log.m29d(TAG, "video/avc output " + i + "x" + i2 + " @" + i3); return prepareEncoder(i, i2, i3, i4, i5, i6, str); } else { Log.m37w(TAG, "color format not supported as of now"); return -1; } } public void setTimeOutUs(int i) { this.TIMEOUT_USEC = i; } }
[ "fonix232@gmail.com" ]
fonix232@gmail.com
5514e3fec9166ce403a68abb258f284cfb6a817d
97acf7adc451150ff5fce2e3c4634dbbe6a7c074
/src/com/zia/androidpopupprojectwithlist/MainActivity.java
cfa24f7371d50a863cbccaa52ba55a18cfee44f9
[]
no_license
cupatil/AndroidPopUpProjectWithList
43c59c4dc8bcba1a34851928938cb44bf476b9d4
0d7e285ec60407341e63672af3e437d37b827b48
refs/heads/master
2021-01-18T13:02:09.212289
2014-10-30T11:06:03
2014-10-30T11:06:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,279
java
package com.zia.androidpopupprojectwithlist; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements OnItemClickListener { ArrayList<item> items = new ArrayList<item>(); ListView listview = null; EntryAdapter adapter; // /////////// Button popUpButton; PopupWindow pw; // List view // private ListView lv; // Listview Adapter // ArrayAdapter<String> adapter; // Search EditText EditText inputSearch; // ArrayList for Listview ArrayList<HashMap<String, String>> productList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); popUpButton = (Button) findViewById(R.id.buttonPopUp); popUpButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { initiatePopupWindow(); } }); } private void initiatePopupWindow() { try { // Listview Data // String products[] = getResources().getStringArray( // R.array.Spinner_Country); // We need to get the instance of the LayoutInflater, use the // context of this activity LayoutInflater inflater = (LayoutInflater) MainActivity.this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Inflate the view from a predefined XML layout View layout = inflater.inflate(R.layout.poplistwithsearch, (ViewGroup) findViewById(R.id.popup_element)); // create a 300px width and 470px height PopupWindow pw = new PopupWindow(layout, 300, 470, true); // display the popup in the center pw.showAtLocation(layout, Gravity.CENTER, 0, 0); Button buttoncancel = (Button) layout.findViewById(R.id.button1); buttoncancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { pw.dismiss(); } }); // //////// // lv = (ListView) layout.findViewById(R.id.list_view); listview = (ListView) layout.findViewById(R.id.list_view); items.add(new SectionItem("My Friends")); items.add(new EntryItem("Zia")); items.add(new EntryItem("Anum")); items.add(new EntryItem("Nazish")); items.add(new EntryItem("salman")); items.add(new EntryItem("Abhi Tripathi")); items.add(new EntryItem("Sandeep Pal")); items.add(new EntryItem("Amit Verma")); items.add(new EntryItem("Awadhesh Diwaker ")); items.add(new SectionItem("Android Version")); items.add(new EntryItem("Jelly Bean")); items.add(new EntryItem("IceCream Sandwich")); items.add(new EntryItem("Honey Comb")); items.add(new EntryItem("Ginger Bread ")); items.add(new SectionItem("Android Phones")); items.add(new EntryItem("Samsung")); items.add(new EntryItem("Sony Ericson")); items.add(new EntryItem("Nokiya")); inputSearch = (EditText) layout.findViewById(R.id.inputSearch); adapter = new EntryAdapter(this, items); listview.setAdapter(adapter); listview.setOnItemClickListener(this); listview.setTextFilterEnabled(true); // Adding items to listview // adapter = new ArrayAdapter<String>(this, R.layout.list_item, // R.id.product_name, products); // lv.setAdapter(adapter); /** * Enabling Search Filter * */ inputSearch.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence cs, int start, int before, int count) { // When user changed the Text if (count < before) { // We're deleting char so we need to reset the adapter // data adapter.resetData(); } adapter.getFilter().filter(cs.toString()); // MainActivity.this.adapter.getFilter().filter(cs); } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // } @Override public void afterTextChanged(Editable arg0) { // } }); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { TextView v = (TextView) arg1 .findViewById(R.id.product_name); arg1.setBackgroundColor(Color.GREEN); String text = ((TextView) arg1 .findViewById(R.id.product_name)).getText() .toString(); System.out.println(arg2 + "=postion=" + v.getText() + "String=" + text); } }); } catch (Exception e) { e.printStackTrace(); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { EntryItem item = (EntryItem) items.get(position); Toast.makeText(this, "You clicked " + item.title, Toast.LENGTH_SHORT) .show(); } }
[ "ziagaggoo@gmail.com" ]
ziagaggoo@gmail.com
0d8c2d78f0d34600e9d88dab205c6d1c5fea8a1f
b8e2d1d7da1a99ee99802d4cdb950ab26db92717
/src/main/java/com/library/dao/MusicDAO.java
39b0bfaffeb3119a129153ecc7098c732328a7ee
[ "MIT" ]
permissive
sbarakad/QAProject
710b52805facdfcbf6b3e078d4bdcb9ffd363e5d
a3b66ff709969339153b99b40073385e4b8a3268
refs/heads/master
2022-08-01T03:50:18.781993
2019-05-23T16:43:08
2019-05-23T16:43:08
188,271,633
0
0
MIT
2022-06-21T01:09:32
2019-05-23T16:38:34
Java
UTF-8
Java
false
false
10,463
java
package com.library.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.library.businessModelSetter.IMusicSetter; import com.library.businessModelSetter.MusicSetter; import com.library.businessModels.LibraryItem; import com.library.businessModels.Music; import com.library.dbConnection.DatabaseConnection; import com.library.search.MusicSearch; public class MusicDAO implements IMusicDAO { private PreparedStatement preparedStatement; String query; Connection connection; IMusicSetter musicSetter = new MusicSetter(); private static final Logger logger = LogManager.getLogger(MusicDAO.class); ResultSet resultSet; DatabaseConnection databaseConnection; public MusicDAO() { try { databaseConnection = DatabaseConnection.getDatabaseConnectionInstance(); this.connection = databaseConnection.getConnection(); } catch (Exception e) { logger.log(Level.ALL, "Unable to connect to database", e); } } @Override public Music getMusicById(int itemID) { Music music = new Music(); this.connection = databaseConnection.getConnection(); List<Music> musics = new ArrayList<>(); query = MusicDAOEnums.QUERY_GET_MUSIC_BY_ID.getQuery(); try { preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, itemID); resultSet = preparedStatement.executeQuery(); musics = musicSetter.mapMusic(resultSet); music = musics.get(0); } catch (SQLException e) { logger.log(Level.ALL, "Check the SQL syntax of :"+query, e); } catch (Exception e) { logger.log(Level.ALL, "Can not fetch music with itemId["+itemID+"] from music table", e); } finally { databaseConnection.closeConnection(resultSet, preparedStatement); } return music; } @Override public List<Music> getMusicByCategory(String category) { this.connection = databaseConnection.getConnection(); query = MusicDAOEnums.QUERY_GET_MUSICS_BY_CATEGORY.getQuery(); List<Music> musicsByCategory = new ArrayList<Music>(); try { preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, "%" + category + "%"); resultSet = preparedStatement.executeQuery(); musicsByCategory = musicSetter.mapMusic(resultSet); } catch (SQLException e) { logger.log(Level.ALL, "Check the SQL syntax of :" +query, e); } catch (Exception e) { logger.log(Level.ALL, "Can not fetch the list of music with category ["+category+"] from music table", e); } finally { databaseConnection.closeConnection(resultSet, preparedStatement); } return musicsByCategory; } @Override public int createMusic(Music music) { this.connection = databaseConnection.getConnection(); String musicCategory = music.getCategory(); String musicTitle = music.getTitle(); String musicArtist = music.getArtist(); String musicRecordLabel = music.getRecordLabel(); int recentlyAddedMusicId = 0; int defaultAvailablity = 5; try { query = MusicDAOEnums.QUERY_INSERT_MUSIC.getQuery(); preparedStatement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, musicCategory); preparedStatement.setString(2, musicTitle); preparedStatement.setString(3, musicArtist); preparedStatement.setString(4, musicRecordLabel); preparedStatement.setInt(5, defaultAvailablity); preparedStatement.executeUpdate(); resultSet = preparedStatement.getGeneratedKeys(); if (resultSet.next()) { recentlyAddedMusicId = resultSet.getInt(1); } return recentlyAddedMusicId; } catch (SQLException e) { logger.log(Level.ALL, "Check the SQL syntax of :"+query, e); } catch (Exception e) { logger.log(Level.ALL, "Can not create music with category["+musicCategory+"], title["+musicTitle+"] and artist["+musicArtist+"] entry in music table", e); } finally { databaseConnection.closeConnection(resultSet, preparedStatement); } return recentlyAddedMusicId; } @Override public Boolean deleteMusic(int itemID) { this.connection = databaseConnection.getConnection(); try { query = MusicDAOEnums.QUERY_DELETE_MUSIC_BY_ID.getQuery(); preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, itemID); preparedStatement.executeUpdate(); return true; } catch (SQLException e) { logger.log(Level.ALL, "Check the SQL syntax of :"+query, e); } catch (Exception e) { logger.log(Level.ALL, "Can not delete music with itemId["+itemID+"] from music table", e); } finally { databaseConnection.closeConnection(resultSet, preparedStatement); } return false; } private String prepareSearchQuery(MusicSearch requestDetails, String searchTerms) { if (0 == searchTerms.length()) { logger.log(Level.ERROR, "No search terms are supplied"); return null; } String query = "SELECT DISTINCT * FROM music WHERE "; String[] searchterms = searchTerms.split("\\s"); for (String term : searchterms) { if (requestDetails.isSearchMusicAlbumName()) { query += "Title like \"%" + term + "%\" or "; } if (requestDetails.isSearchMusicArtist()) { query += "Artist like \"%" + term + "%\" or "; } if (requestDetails.isSearchMusicRecordLabel()) { query += "Record_Label like \"%" + term + "%\" or "; } } query = query.substring(0, query.length() - 4); return query; } @Override public List<LibraryItem> getMusicBySearchTerms(MusicSearch requestDetails, String searchTerms) { this.connection = databaseConnection.getConnection(); List<LibraryItem> musics = new LinkedList<LibraryItem>(); List<Music> tempMusics = new ArrayList<>(); if (!requestDetails.isSearchInMusic()) { return musics; } String query = prepareSearchQuery(requestDetails, searchTerms); if (null == query) { return musics; } try { preparedStatement = connection.prepareStatement(query); resultSet = preparedStatement.executeQuery(); tempMusics = musicSetter.mapMusic(resultSet); musics.addAll(tempMusics); return musics; } catch (SQLException e) { logger.log(Level.ERROR, "Failed to prepare SQL statement OR execute a query OR parse a query resultSet :"+query, e); } finally { databaseConnection.closeConnection(resultSet, preparedStatement); } return musics; } @Override public List<String> getMusicCategories() { this.connection = databaseConnection.getConnection(); List<String> categories = new ArrayList<String>(); query = MusicDAOEnums.QUERY_GET_MUSIC_CATEGORIES.getQuery(); try { preparedStatement = connection.prepareStatement(query); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { categories.add(resultSet.getString("Category")); } } catch (SQLException e) { logger.log(Level.ALL, "Check the SQL syntax of :"+query, e); } catch (Exception e) { logger.log(Level.ALL, "Error fetching the list of Music Categories", e); } finally { databaseConnection.closeConnection(resultSet, preparedStatement); } return categories; } @Override public int getAvailability(int itemID) { int musicsAvailable = 0; try { this.connection = databaseConnection.getConnection(); query = MusicDAOEnums.QUERY_GET_CURRENT_AVAILABILITY_OF_MUSIC.getQuery(); preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, itemID); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { musicsAvailable = resultSet.getInt("Availability"); } } catch (SQLException e) { logger.log(Level.ALL, "Check the SQL syntax of :"+query, e); } catch (Exception e) { logger.log(Level.ALL, "Error fetching the availability of Music with itemId["+itemID+"]", e); } finally { databaseConnection.closeConnection(resultSet, preparedStatement); } return musicsAvailable; } public boolean checkMusicDuplicacy(Music music) { this.connection = databaseConnection.getConnection(); String artistToBeAdded = music.getArtist(); String titleToBeAdded = music.getTitle(); boolean isMusicAvailable = false; query = MusicDAOEnums.QUERY_IS_DUPLICATE_MUSIC.getQuery(); try { preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, titleToBeAdded); preparedStatement.setString(2, artistToBeAdded); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { isMusicAvailable = true; } else { isMusicAvailable = false; } } catch (SQLException e) { logger.log(Level.ALL, "Check the SQL syntax of :"+query, e); } catch (Exception e) { logger.log(Level.ALL, "Error fetching the list of Musics with artist ["+artistToBeAdded+"] and title ["+titleToBeAdded+"]", e); } finally { databaseConnection.closeConnection(resultSet, preparedStatement); } return isMusicAvailable; } @Override public Boolean increaseCount(int itemID) { Boolean countIncrease = false; try { this.connection = databaseConnection.getConnection(); query = MusicDAOEnums.QUERY_INCREASE_MUSIC_COUNT.getQuery(); preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, itemID); preparedStatement.execute(); countIncrease = true; } catch (SQLException e) { logger.log(Level.ALL, "Check the SQL syntax of :"+query, e); } catch (Exception e) { logger.log(Level.ALL, "Error increasing count of Music with itemId ["+itemID+"]", e); } finally { databaseConnection.closeConnection(resultSet, preparedStatement); } return countIncrease; } @Override public void updateAvailability(int itemId, int udatedAvailability) { try { this.connection = databaseConnection.getConnection(); query = MusicDAOEnums.QUERY_UPDATE_AVAILABILITY.getQuery(); preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, udatedAvailability); preparedStatement.setInt(2, itemId); preparedStatement.executeUpdate(); } catch (SQLException e) { logger.log(Level.ALL, "Check the SQL syntax of :"+query, e); } catch (Exception e) { logger.log(Level.ALL, "Error updating availability of music with itemId ["+itemId+"]", e); } finally { databaseConnection.closeConnection(resultSet, preparedStatement); } } }
[ "eg343462@dal.ca" ]
eg343462@dal.ca
f1146d2243c4c086844c0a0b3c3991d10f99760e
205d18401445f4bb5e955e270b0f072202b0ec22
/oracles/membership-oracles/src/main/java/de/learnlib/oracle/membership/MappedOracle.java
2838ce2d65f73331295c480a12819f7f2254ab0b
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
damascenodiego/learnlib
b56d07bb904a9b6a770496e09bac687304dee053
09b7f505bcee188efe4605a038536a36a2e4c98c
refs/heads/develop
2021-06-04T12:26:36.840535
2018-11-26T19:02:56
2018-11-26T19:02:56
159,353,246
0
0
Apache-2.0
2021-02-18T09:46:00
2018-11-27T15:02:47
Java
UTF-8
Java
false
false
2,006
java
/* Copyright (C) 2013-2018 TU Dortmund * This file is part of LearnLib, http://www.learnlib.de/. * * 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.learnlib.oracle.membership; import de.learnlib.api.Mapper.AsynchronousMapper; import de.learnlib.api.oracle.QueryAnswerer; import de.learnlib.api.oracle.SingleQueryOracle; import net.automatalib.words.Word; /** * A utility class that allows to lift a membership oracle of concrete input/output symbols to a membership oracle of * abstract input/output symbols, given a corresponding mapper. * * @param <AI> * abstract input symbol type. * @param <AO> * abstract output symbol type. * @param <CI> * concrete input symbol type. * @param <CO> * concrete output symbol type. * * @author frohme */ public class MappedOracle<AI, AO, CI, CO> implements SingleQueryOracle<AI, AO> { private final QueryAnswerer<CI, CO> delegate; private final AsynchronousMapper<AI, AO, CI, CO> mapper; public MappedOracle(QueryAnswerer<CI, CO> delegate, AsynchronousMapper<AI, AO, CI, CO> mapper) { this.delegate = delegate; this.mapper = mapper; } @Override public AO answerQuery(Word<AI> prefix, Word<AI> suffix) { mapper.pre(); final CO output = delegate.answerQuery(prefix.transform(mapper::mapInput), suffix.transform(mapper::mapInput)); final AO result = mapper.mapOutput(output); mapper.post(); return result; } }
[ "markus.frohme@udo.edu" ]
markus.frohme@udo.edu
44bec1913cd3f4cde833d0f1e7a00dfda3a0562c
d4fe1cc9ad233c75e73d09ed61d609c116255729
/src/main/java/com/blackboxgaming/engine/components/Child.java
14056f7a0eed209f189c7be424b9b975e1265976
[]
no_license
BlackBoxGaming/Engine
697482fb24eb6e04f30f53ba0d23977a92771803
65f74118d3d3b6dfd305bc7e0024c1052c73eeaf
refs/heads/master
2021-01-20T15:44:26.921792
2015-04-09T14:48:22
2015-04-09T14:48:22
32,343,265
0
1
null
null
null
null
UTF-8
Java
false
false
1,046
java
package com.blackboxgaming.engine.components; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.blackboxgaming.engine.Entity; public class Child implements IComponent { public final Entity parent; public final Matrix4 relativeTransformToParent; public boolean resetRotation; public Child(Entity parent, Matrix4 relativeTransformToParent) { this.parent = parent; this.relativeTransformToParent = relativeTransformToParent; } public Child(Entity parent) { this.parent = parent; this.relativeTransformToParent = new Matrix4(); } public Child(Entity parent, Vector3 position) { this.parent = parent; this.relativeTransformToParent = new Matrix4().setToTranslation(position); } public Child(Entity parent, Vector3 position, boolean resetRotation) { this.resetRotation = resetRotation; this.parent = parent; this.relativeTransformToParent = new Matrix4().setToTranslation(position); } }
[ "ad_robotics@yahoo.com" ]
ad_robotics@yahoo.com
61a6203fe65fbe64545ada2244598d6f8a614718
ff34fd7ab8fb5ba005263affdaf7bacc0f326c93
/src/main/java/com/crud/h2/ServletInitializer.java
56f0fb8446dbe237afc74fbafe2b0b9cc64a75d4
[]
no_license
sansung14/T25_3
396e88e253bd61d32a58012ce8d8c9b716e4d878
8357f11e6ed7e95c002be9d3904b93c08a97553f
refs/heads/master
2023-03-26T08:19:01.414526
2021-03-10T19:54:58
2021-03-10T19:54:58
346,471,798
0
0
null
null
null
null
UTF-8
Java
false
false
389
java
package com.crud.h2; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(T25_3.class); } }
[ "78426816+sansung14@users.noreply.github.com" ]
78426816+sansung14@users.noreply.github.com
8ac88e72462cea01d5e732b314a99ca14ff72a8a
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/java/spring-boot/2017/12/DefaultServletWebServerFactoryCustomizer.java
6421e82bfb1de11071720698593928f4a2c997e9
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
Java
false
false
24,244
java
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.web.servlet; import java.time.Duration; import java.util.LinkedHashSet; import java.util.Set; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.SessionCookieConfig; import io.undertow.UndertowOptions; import org.apache.catalina.Lifecycle; import org.apache.catalina.valves.AccessLogValve; import org.apache.catalina.valves.RemoteIpValve; import org.apache.coyote.AbstractProtocol; import org.apache.coyote.ProtocolHandler; import org.apache.coyote.http11.AbstractHttp11Protocol; import org.eclipse.jetty.server.AbstractConnector; import org.eclipse.jetty.server.ConnectionFactory; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.NCSARequestLog; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.HandlerWrapper; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.autoconfigure.web.ServerProperties.Session; import org.springframework.boot.autoconfigure.web.ServerProperties.Tomcat.Resource; import org.springframework.boot.cloud.CloudPlatform; import org.springframework.boot.web.embedded.jetty.JettyServerCustomizer; import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.ServletContextInitializer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.boot.web.servlet.server.InitParameterConfiguringServletContextInitializer; import org.springframework.context.EnvironmentAware; import org.springframework.core.Ordered; import org.springframework.core.env.Environment; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Default {@link WebServerFactoryCustomizer} for {@link ServerProperties}. * * @author Brian Clozel * @author Stephane Nicoll * @author Olivier Lamy * @since 2.0.0 */ public class DefaultServletWebServerFactoryCustomizer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, EnvironmentAware, Ordered { private final ServerProperties serverProperties; private Environment environment; public DefaultServletWebServerFactoryCustomizer(ServerProperties serverProperties) { this.serverProperties = serverProperties; } public void setLoader(String value) { // no op to support Tomcat running as a traditional server (not embedded) } @Override public int getOrder() { return 0; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } @Override public void customize(ConfigurableServletWebServerFactory factory) { if (this.serverProperties.getPort() != null) { factory.setPort(this.serverProperties.getPort()); } if (this.serverProperties.getAddress() != null) { factory.setAddress(this.serverProperties.getAddress()); } if (this.serverProperties.getServlet().getContextPath() != null) { factory.setContextPath(this.serverProperties.getServlet().getContextPath()); } if (this.serverProperties.getDisplayName() != null) { factory.setDisplayName(this.serverProperties.getDisplayName()); } if (this.serverProperties.getSession().getTimeout() != null) { factory.setSessionTimeout(this.serverProperties.getSession().getTimeout()); } factory.setPersistSession(this.serverProperties.getSession().isPersistent()); factory.setSessionStoreDir(this.serverProperties.getSession().getStoreDir()); if (this.serverProperties.getSsl() != null) { factory.setSsl(this.serverProperties.getSsl()); } if (this.serverProperties.getServlet() != null) { factory.setJsp(this.serverProperties.getServlet().getJsp()); } if (this.serverProperties.getCompression() != null) { factory.setCompression(this.serverProperties.getCompression()); } if (this.serverProperties.getHttp2() != null) { factory.setHttp2(this.serverProperties.getHttp2()); } factory.setServerHeader(this.serverProperties.getServerHeader()); if (factory instanceof TomcatServletWebServerFactory) { TomcatCustomizer.customizeTomcat(this.serverProperties, this.environment, (TomcatServletWebServerFactory) factory); } if (factory instanceof JettyServletWebServerFactory) { JettyCustomizer.customizeJetty(this.serverProperties, this.environment, (JettyServletWebServerFactory) factory); } if (factory instanceof UndertowServletWebServerFactory) { UndertowCustomizer.customizeUndertow(this.serverProperties, this.environment, (UndertowServletWebServerFactory) factory); } factory.addInitializers( new SessionConfiguringInitializer(this.serverProperties.getSession())); factory.addInitializers(new InitParameterConfiguringServletContextInitializer( this.serverProperties.getServlet().getContextParameters())); } private static boolean getOrDeduceUseForwardHeaders(ServerProperties serverProperties, Environment environment) { if (serverProperties.isUseForwardHeaders() != null) { return serverProperties.isUseForwardHeaders(); } CloudPlatform platform = CloudPlatform.getActive(environment); return (platform == null ? false : platform.isUsingForwardHeaders()); } /** * {@link ServletContextInitializer} to apply appropriate parts of the {@link Session} * configuration. */ private static class SessionConfiguringInitializer implements ServletContextInitializer { private final Session session; SessionConfiguringInitializer(Session session) { this.session = session; } @Override public void onStartup(ServletContext servletContext) throws ServletException { if (this.session.getTrackingModes() != null) { servletContext .setSessionTrackingModes(unwrap(this.session.getTrackingModes())); } configureSessionCookie(servletContext.getSessionCookieConfig()); } private void configureSessionCookie(SessionCookieConfig config) { Session.Cookie cookie = this.session.getCookie(); if (cookie.getName() != null) { config.setName(cookie.getName()); } if (cookie.getDomain() != null) { config.setDomain(cookie.getDomain()); } if (cookie.getPath() != null) { config.setPath(cookie.getPath()); } if (cookie.getComment() != null) { config.setComment(cookie.getComment()); } if (cookie.getHttpOnly() != null) { config.setHttpOnly(cookie.getHttpOnly()); } if (cookie.getSecure() != null) { config.setSecure(cookie.getSecure()); } if (cookie.getMaxAge() != null) { config.setMaxAge((int) cookie.getMaxAge().getSeconds()); } } private Set<javax.servlet.SessionTrackingMode> unwrap( Set<Session.SessionTrackingMode> modes) { if (modes == null) { return null; } Set<javax.servlet.SessionTrackingMode> result = new LinkedHashSet<>(); for (Session.SessionTrackingMode mode : modes) { result.add(javax.servlet.SessionTrackingMode.valueOf(mode.name())); } return result; } } private static class TomcatCustomizer { public static void customizeTomcat(ServerProperties serverProperties, Environment environment, TomcatServletWebServerFactory factory) { ServerProperties.Tomcat tomcatProperties = serverProperties.getTomcat(); if (tomcatProperties.getBasedir() != null) { factory.setBaseDirectory(tomcatProperties.getBasedir()); } if (tomcatProperties.getBackgroundProcessorDelay() != null) { factory.setBackgroundProcessorDelay((int) tomcatProperties .getBackgroundProcessorDelay().getSeconds()); } customizeRemoteIpValve(serverProperties, environment, factory); if (tomcatProperties.getMaxThreads() > 0) { customizeMaxThreads(factory, tomcatProperties.getMaxThreads()); } if (tomcatProperties.getMinSpareThreads() > 0) { customizeMinThreads(factory, tomcatProperties.getMinSpareThreads()); } int maxHttpHeaderSize = (serverProperties.getMaxHttpHeaderSize() > 0 ? serverProperties.getMaxHttpHeaderSize() : tomcatProperties.getMaxHttpHeaderSize()); if (maxHttpHeaderSize > 0) { customizeMaxHttpHeaderSize(factory, maxHttpHeaderSize); } if (tomcatProperties.getMaxHttpPostSize() != 0) { customizeMaxHttpPostSize(factory, tomcatProperties.getMaxHttpPostSize()); } if (tomcatProperties.getAccesslog().isEnabled()) { customizeAccessLog(tomcatProperties, factory); } if (tomcatProperties.getUriEncoding() != null) { factory.setUriEncoding(tomcatProperties.getUriEncoding()); } if (serverProperties.getConnectionTimeout() != null) { customizeConnectionTimeout(factory, serverProperties.getConnectionTimeout()); } if (tomcatProperties.getRedirectContextRoot() != null) { customizeRedirectContextRoot(factory, tomcatProperties.getRedirectContextRoot()); } if (tomcatProperties.getUseRelativeRedirects() != null) { customizeUseRelativeRedirects(factory, tomcatProperties.getUseRelativeRedirects()); } if (tomcatProperties.getMaxConnections() > 0) { customizeMaxConnections(factory, tomcatProperties.getMaxConnections()); } if (tomcatProperties.getAcceptCount() > 0) { customizeAcceptCount(factory, tomcatProperties.getAcceptCount()); } if (!ObjectUtils.isEmpty(tomcatProperties.getAdditionalTldSkipPatterns())) { factory.getTldSkipPatterns() .addAll(tomcatProperties.getAdditionalTldSkipPatterns()); } customizeStaticResources(serverProperties.getTomcat().getResource(), factory); } private static void customizeAcceptCount(TomcatServletWebServerFactory factory, int acceptCount) { factory.addConnectorCustomizers((connector) -> { ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof AbstractProtocol) { AbstractProtocol<?> protocol = (AbstractProtocol<?>) handler; protocol.setAcceptCount(acceptCount); } }); } private static void customizeMaxConnections(TomcatServletWebServerFactory factory, int maxConnections) { factory.addConnectorCustomizers((connector) -> { ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof AbstractProtocol) { AbstractProtocol<?> protocol = (AbstractProtocol<?>) handler; protocol.setMaxConnections(maxConnections); } }); } private static void customizeConnectionTimeout( TomcatServletWebServerFactory factory, Duration connectionTimeout) { factory.addConnectorCustomizers((connector) -> { ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof AbstractProtocol) { AbstractProtocol<?> protocol = (AbstractProtocol<?>) handler; protocol.setConnectionTimeout((int) connectionTimeout.toMillis()); } }); } private static void customizeRemoteIpValve(ServerProperties properties, Environment environment, TomcatServletWebServerFactory factory) { String protocolHeader = properties.getTomcat().getProtocolHeader(); String remoteIpHeader = properties.getTomcat().getRemoteIpHeader(); // For back compatibility the valve is also enabled if protocol-header is set if (StringUtils.hasText(protocolHeader) || StringUtils.hasText(remoteIpHeader) || getOrDeduceUseForwardHeaders(properties, environment)) { RemoteIpValve valve = new RemoteIpValve(); valve.setProtocolHeader(StringUtils.hasLength(protocolHeader) ? protocolHeader : "X-Forwarded-Proto"); if (StringUtils.hasLength(remoteIpHeader)) { valve.setRemoteIpHeader(remoteIpHeader); } // The internal proxies default to a white list of "safe" internal IP // addresses valve.setInternalProxies(properties.getTomcat().getInternalProxies()); valve.setPortHeader(properties.getTomcat().getPortHeader()); valve.setProtocolHeaderHttpsValue( properties.getTomcat().getProtocolHeaderHttpsValue()); // ... so it's safe to add this valve by default. factory.addEngineValves(valve); } } @SuppressWarnings("rawtypes") private static void customizeMaxThreads(TomcatServletWebServerFactory factory, int maxThreads) { factory.addConnectorCustomizers((connector) -> { ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof AbstractProtocol) { AbstractProtocol protocol = (AbstractProtocol) handler; protocol.setMaxThreads(maxThreads); } }); } @SuppressWarnings("rawtypes") private static void customizeMinThreads(TomcatServletWebServerFactory factory, int minSpareThreads) { factory.addConnectorCustomizers((connector) -> { ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof AbstractProtocol) { AbstractProtocol protocol = (AbstractProtocol) handler; protocol.setMinSpareThreads(minSpareThreads); } }); } @SuppressWarnings("rawtypes") private static void customizeMaxHttpHeaderSize( TomcatServletWebServerFactory factory, int maxHttpHeaderSize) { factory.addConnectorCustomizers((connector) -> { ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof AbstractHttp11Protocol) { AbstractHttp11Protocol protocol = (AbstractHttp11Protocol) handler; protocol.setMaxHttpHeaderSize(maxHttpHeaderSize); } }); } private static void customizeMaxHttpPostSize( TomcatServletWebServerFactory factory, int maxHttpPostSize) { factory.addConnectorCustomizers( (connector) -> connector.setMaxPostSize(maxHttpPostSize)); } private static void customizeAccessLog(ServerProperties.Tomcat tomcatProperties, TomcatServletWebServerFactory factory) { AccessLogValve valve = new AccessLogValve(); valve.setPattern(tomcatProperties.getAccesslog().getPattern()); valve.setDirectory(tomcatProperties.getAccesslog().getDirectory()); valve.setPrefix(tomcatProperties.getAccesslog().getPrefix()); valve.setSuffix(tomcatProperties.getAccesslog().getSuffix()); valve.setRenameOnRotate(tomcatProperties.getAccesslog().isRenameOnRotate()); valve.setFileDateFormat(tomcatProperties.getAccesslog().getFileDateFormat()); valve.setRequestAttributesEnabled( tomcatProperties.getAccesslog().isRequestAttributesEnabled()); valve.setRotatable(tomcatProperties.getAccesslog().isRotate()); valve.setBuffered(tomcatProperties.getAccesslog().isBuffered()); factory.addEngineValves(valve); } private static void customizeRedirectContextRoot( TomcatServletWebServerFactory factory, boolean redirectContextRoot) { factory.addContextCustomizers((context) -> context .setMapperContextRootRedirectEnabled(redirectContextRoot)); } private static void customizeUseRelativeRedirects( TomcatServletWebServerFactory factory, boolean useRelativeRedirects) { factory.addContextCustomizers( (context) -> context.setUseRelativeRedirects(useRelativeRedirects)); } private static void customizeStaticResources(Resource resource, TomcatServletWebServerFactory factory) { if (resource.getCacheTtl() == null) { return; } factory.addContextCustomizers((context) -> { context.addLifecycleListener((event) -> { if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) { long ttl = resource.getCacheTtl().toMillis(); context.getResources().setCacheTtl(ttl); } }); }); } } private static class UndertowCustomizer { protected static void customizeUndertow(ServerProperties serverProperties, Environment environment, UndertowServletWebServerFactory factory) { ServerProperties.Undertow undertowProperties = serverProperties.getUndertow(); ServerProperties.Undertow.Accesslog accesslogProperties = undertowProperties .getAccesslog(); if (undertowProperties.getBufferSize() != null) { factory.setBufferSize(undertowProperties.getBufferSize()); } if (undertowProperties.getIoThreads() != null) { factory.setIoThreads(undertowProperties.getIoThreads()); } if (undertowProperties.getWorkerThreads() != null) { factory.setWorkerThreads(undertowProperties.getWorkerThreads()); } if (undertowProperties.getDirectBuffers() != null) { factory.setDirectBuffers(undertowProperties.getDirectBuffers()); } if (undertowProperties.getAccesslog().getEnabled() != null) { factory.setAccessLogEnabled(accesslogProperties.getEnabled()); } factory.setAccessLogDirectory(accesslogProperties.getDir()); factory.setAccessLogPattern(accesslogProperties.getPattern()); factory.setAccessLogPrefix(accesslogProperties.getPrefix()); factory.setAccessLogSuffix(accesslogProperties.getSuffix()); factory.setAccessLogRotate(accesslogProperties.isRotate()); factory.setUseForwardHeaders( getOrDeduceUseForwardHeaders(serverProperties, environment)); if (serverProperties.getMaxHttpHeaderSize() > 0) { customizeMaxHttpHeaderSize(factory, serverProperties.getMaxHttpHeaderSize()); } if (undertowProperties.getMaxHttpPostSize() > 0) { customizeMaxHttpPostSize(factory, undertowProperties.getMaxHttpPostSize()); } if (serverProperties.getConnectionTimeout() != null) { customizeConnectionTimeout(factory, serverProperties.getConnectionTimeout()); } factory.addDeploymentInfoCustomizers((deploymentInfo) -> deploymentInfo .setEagerFilterInit(undertowProperties.isEagerFilterInit())); } private static void customizeConnectionTimeout( UndertowServletWebServerFactory factory, Duration connectionTimeout) { factory.addBuilderCustomizers((builder) -> builder.setSocketOption( UndertowOptions.NO_REQUEST_TIMEOUT, (int) connectionTimeout.toMillis())); } private static void customizeMaxHttpHeaderSize( UndertowServletWebServerFactory factory, int maxHttpHeaderSize) { factory.addBuilderCustomizers((builder) -> builder .setServerOption(UndertowOptions.MAX_HEADER_SIZE, maxHttpHeaderSize)); } private static void customizeMaxHttpPostSize( UndertowServletWebServerFactory factory, long maxHttpPostSize) { factory.addBuilderCustomizers((builder) -> builder .setServerOption(UndertowOptions.MAX_ENTITY_SIZE, maxHttpPostSize)); } } private static class JettyCustomizer { public static void customizeJetty(ServerProperties serverProperties, Environment environment, JettyServletWebServerFactory factory) { ServerProperties.Jetty jettyProperties = serverProperties.getJetty(); factory.setUseForwardHeaders( getOrDeduceUseForwardHeaders(serverProperties, environment)); if (jettyProperties.getAcceptors() != null) { factory.setAcceptors(jettyProperties.getAcceptors()); } if (jettyProperties.getSelectors() != null) { factory.setSelectors(jettyProperties.getSelectors()); } if (serverProperties.getMaxHttpHeaderSize() > 0) { customizeMaxHttpHeaderSize(factory, serverProperties.getMaxHttpHeaderSize()); } if (jettyProperties.getMaxHttpPostSize() > 0) { customizeMaxHttpPostSize(factory, jettyProperties.getMaxHttpPostSize()); } if (serverProperties.getConnectionTimeout() != null) { customizeConnectionTimeout(factory, serverProperties.getConnectionTimeout()); } if (jettyProperties.getAccesslog().isEnabled()) { customizeAccessLog(factory, jettyProperties.getAccesslog()); } } private static void customizeConnectionTimeout( JettyServletWebServerFactory factory, Duration connectionTimeout) { factory.addServerCustomizers((server) -> { for (org.eclipse.jetty.server.Connector connector : server .getConnectors()) { if (connector instanceof AbstractConnector) { ((AbstractConnector) connector) .setIdleTimeout(connectionTimeout.toMillis()); } } }); } private static void customizeMaxHttpHeaderSize( JettyServletWebServerFactory factory, int maxHttpHeaderSize) { factory.addServerCustomizers(new JettyServerCustomizer() { @Override public void customize(Server server) { for (org.eclipse.jetty.server.Connector connector : server .getConnectors()) { try { for (ConnectionFactory connectionFactory : connector .getConnectionFactories()) { if (connectionFactory instanceof HttpConfiguration.ConnectionFactory) { customize( (HttpConfiguration.ConnectionFactory) connectionFactory); } } } catch (NoSuchMethodError ex) { customizeOnJetty8(connector, maxHttpHeaderSize); } } } private void customize(HttpConfiguration.ConnectionFactory factory) { HttpConfiguration configuration = factory.getHttpConfiguration(); configuration.setRequestHeaderSize(maxHttpHeaderSize); configuration.setResponseHeaderSize(maxHttpHeaderSize); } private void customizeOnJetty8( org.eclipse.jetty.server.Connector connector, int maxHttpHeaderSize) { try { connector.getClass().getMethod("setRequestHeaderSize", int.class) .invoke(connector, maxHttpHeaderSize); connector.getClass().getMethod("setResponseHeaderSize", int.class) .invoke(connector, maxHttpHeaderSize); } catch (Exception ex) { throw new RuntimeException(ex); } } }); } private static void customizeMaxHttpPostSize(JettyServletWebServerFactory factory, int maxHttpPostSize) { factory.addServerCustomizers(new JettyServerCustomizer() { @Override public void customize(Server server) { setHandlerMaxHttpPostSize(maxHttpPostSize, server.getHandlers()); } private void setHandlerMaxHttpPostSize(int maxHttpPostSize, Handler... handlers) { for (Handler handler : handlers) { if (handler instanceof ContextHandler) { ((ContextHandler) handler) .setMaxFormContentSize(maxHttpPostSize); } else if (handler instanceof HandlerWrapper) { setHandlerMaxHttpPostSize(maxHttpPostSize, ((HandlerWrapper) handler).getHandler()); } else if (handler instanceof HandlerCollection) { setHandlerMaxHttpPostSize(maxHttpPostSize, ((HandlerCollection) handler).getHandlers()); } } } }); } private static void customizeAccessLog(JettyServletWebServerFactory factory, ServerProperties.Jetty.Accesslog properties) { factory.addServerCustomizers((server) -> { NCSARequestLog log = new NCSARequestLog(); if (properties.getFilename() != null) { log.setFilename(properties.getFilename()); } if (properties.getFileDateFormat() != null) { log.setFilenameDateFormat(properties.getFileDateFormat()); } log.setRetainDays(properties.getRetentionPeriod()); log.setAppend(properties.isAppend()); log.setExtended(properties.isExtendedFormat()); if (properties.getDateFormat() != null) { log.setLogDateFormat(properties.getDateFormat()); } if (properties.getLocale() != null) { log.setLogLocale(properties.getLocale()); } if (properties.getTimeZone() != null) { log.setLogTimeZone(properties.getTimeZone().getID()); } log.setLogCookies(properties.isLogCookies()); log.setLogServer(properties.isLogServer()); log.setLogLatency(properties.isLogLatency()); server.setRequestLog(log); }); } } }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
98b3aab80a4227cf9eef562b8d2ff36c2772ae28
14cb2085987e1ba5b02022666ee1763e77c42d88
/src/main/java/magento/ShoppingCartProductEntity.java
85e8c7789eadb7c7b64bb4bd878adfd729bfa5d5
[]
no_license
jcpantunes/eai-camel-mq
bbc0d48e086ac172006bca5c8e10545c4421e060
b7cd7e2063080aca7b24296e125e91a4fa39568b
refs/heads/master
2020-12-06T19:11:53.606918
2013-11-21T20:23:03
2013-11-21T20:23:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,363
java
package magento; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for shoppingCartProductEntity complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="shoppingCartProductEntity"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="product_id" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="sku" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="qty" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/> * &lt;element name="options" type="{urn:Magento}associativeArray" minOccurs="0"/> * &lt;element name="bundle_option" type="{urn:Magento}associativeArray" minOccurs="0"/> * &lt;element name="bundle_option_qty" type="{urn:Magento}associativeArray" minOccurs="0"/> * &lt;element name="links" type="{urn:Magento}ArrayOfString" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "shoppingCartProductEntity", propOrder = { "productId", "sku", "qty", "options", "bundleOption", "bundleOptionQty", "links" }) public class ShoppingCartProductEntity { @XmlElement(name = "product_id") protected String productId; protected String sku; protected Double qty; protected AssociativeArray options; @XmlElement(name = "bundle_option") protected AssociativeArray bundleOption; @XmlElement(name = "bundle_option_qty") protected AssociativeArray bundleOptionQty; protected ArrayOfString links; /** * Gets the value of the productId property. * * @return * possible object is * {@link String } * */ public String getProductId() { return productId; } /** * Sets the value of the productId property. * * @param value * allowed object is * {@link String } * */ public void setProductId(String value) { this.productId = value; } /** * Gets the value of the sku property. * * @return * possible object is * {@link String } * */ public String getSku() { return sku; } /** * Sets the value of the sku property. * * @param value * allowed object is * {@link String } * */ public void setSku(String value) { this.sku = value; } /** * Gets the value of the qty property. * * @return * possible object is * {@link Double } * */ public Double getQty() { return qty; } /** * Sets the value of the qty property. * * @param value * allowed object is * {@link Double } * */ public void setQty(Double value) { this.qty = value; } /** * Gets the value of the options property. * * @return * possible object is * {@link AssociativeArray } * */ public AssociativeArray getOptions() { return options; } /** * Sets the value of the options property. * * @param value * allowed object is * {@link AssociativeArray } * */ public void setOptions(AssociativeArray value) { this.options = value; } /** * Gets the value of the bundleOption property. * * @return * possible object is * {@link AssociativeArray } * */ public AssociativeArray getBundleOption() { return bundleOption; } /** * Sets the value of the bundleOption property. * * @param value * allowed object is * {@link AssociativeArray } * */ public void setBundleOption(AssociativeArray value) { this.bundleOption = value; } /** * Gets the value of the bundleOptionQty property. * * @return * possible object is * {@link AssociativeArray } * */ public AssociativeArray getBundleOptionQty() { return bundleOptionQty; } /** * Sets the value of the bundleOptionQty property. * * @param value * allowed object is * {@link AssociativeArray } * */ public void setBundleOptionQty(AssociativeArray value) { this.bundleOptionQty = value; } /** * Gets the value of the links property. * * @return * possible object is * {@link ArrayOfString } * */ public ArrayOfString getLinks() { return links; } /** * Sets the value of the links property. * * @param value * allowed object is * {@link ArrayOfString } * */ public void setLinks(ArrayOfString value) { this.links = value; } }
[ "joao.lima@vilivesoft.com" ]
joao.lima@vilivesoft.com
c57b32a6e0d02996ed3f059fc944c03e5f356a57
b920bec12babc58efb71b1aeff26faba5d7b42a1
/dockerApps/collabtive/src/main/java/tests/UpdateIssueStatusAssignedTest.java
972b4376f0a36081f76f0b82b7f69b252d850909
[]
no_license
yrahulkr/maewu
98254aba4302596874165b777bab85243f6da8b3
acd20541e1cf46d697f621ba8156f5e721c75798
refs/heads/main
2023-07-08T15:07:15.642183
2023-07-03T22:57:18
2023-07-03T22:57:18
364,141,157
6
3
null
null
null
null
UTF-8
Java
false
false
1,620
java
package tests; import static org.junit.Assert.assertEquals; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.Select; import utils.DriverProvider; import utils.Properties; public class UpdateIssueStatusAssignedTest { private WebDriver driver; @Before public void setUp() { driver = DriverProvider.getInstance().getDriver(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.get(Properties.app_url); } @Test public void testMantisBTUpdateIssueStatusAssigned() throws Exception { driver.findElement(By.name("username")).clear(); driver.findElement(By.name("username")).sendKeys("administrator"); driver.findElement(By.name("password")).clear(); driver.findElement(By.name("password")).sendKeys("root"); driver.findElement(By.cssSelector("input.button")).click(); driver.findElement(By.linkText("View Issues")).click(); driver.findElement(By.cssSelector("img[alt=\"Edit\"]")).click(); new Select(driver.findElement(By.name("status"))).selectByVisibleText("assigned"); driver.findElement(By.cssSelector("input.button")).click(); driver.findElement(By.linkText("View Issues")).click(); assertEquals("assigned (administrator)", driver.findElement(By.xpath(".//*[@id='buglist']/tbody/tr[4]/td[8]")).getText()); driver.findElement(By.linkText("Logout")).click(); } @After public void tearDown() throws Exception { driver.quit(); } }
[ "yrahulkr@github.com" ]
yrahulkr@github.com
ffc40017bd21f020941eb55beaa1ce42945c6726
3a344dabdacbe91a9d301c15144f44d6539f161a
/vlc/src/main/java/org/videolan/vlc/widget/SlidingPaneLayout.java
a7d83cea4034a8f2fa590c1bda86b8c60c145e71
[]
no_license
Simon199201/vlc-android-sample
fcbfc1bf5c92d6a5128df6074e8649c8bdaa7bdf
61b6b02ea7ed2a7478a9f0124651067905002b5c
refs/heads/master
2021-01-24T18:24:56.212820
2017-03-09T10:23:47
2017-03-09T10:23:47
84,425,695
0
0
null
null
null
null
UTF-8
Java
false
false
40,115
java
package org.videolan.vlc.widget; /* * Copyright (C) 2012 The Android Open Source Project * * 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. */ /* * This class originally comes from the android support library v4: * android.support.v4.widget.SlidingPaneLayout * It was modified to slide the view vertically instead of horizontally * and a simplified to fit the needs of the VLC Android app. */ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import org.videolan.vlc.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.view.AccessibilityDelegateCompat; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.support.v4.widget.ViewDragHelper; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; public class SlidingPaneLayout extends ViewGroup { private static final String TAG = "VLC/SlidingPaneLayout"; /** * Default size of the overhang for a pane in the open state. * At least this much of a sliding pane will remain visible. * This indicates that there is more content available and provides * a "physical" edge to grab to pull it closed. */ private static final int DEFAULT_OVERHANG_SIZE = 64; // dp; /** * Minimum velocity that will be detected as a fling */ private static final int MIN_FLING_VELOCITY = 400; // dips per second /** * The fade color used for the panel covered by the slider. 0 = no fading. */ private int mCoveredFadeColor; /** * Drawable used to draw the shadow between panes. */ private Drawable mShadowDrawable; /** * The size of the overhang in pixels. * This is the minimum section of the sliding panel that will * be visible in the open state to allow for a closing drag. */ private int mOverhangSize; /** * True if a panel can slide with the current measurements */ private boolean mCanSlide; /** * The child view that can slide, if any. */ private View mSlideableView; /** * How far the panel is offset from its closed position. * range [0, 1] where 0 = closed, 1 = open. */ private float mSlideOffset; /** * How far in pixels the slideable panel may move. */ private int mSlideRange; /** * A panel view is locked into internal scrolling or another condition that * is preventing a drag. */ private boolean mIsUnableToDrag; /** * The opening states of the pane. */ public final int STATE_OPENED_ENTIRELY = 0; public final int STATE_OPENED = 1; public final int STATE_CLOSED = 2; private int mState; private float mInitialMotionX; private float mInitialMotionY; private final ViewDragHelper mDragHelper; private boolean mFirstLayout = true; private final Rect mTmpRect = new Rect(); private final ArrayList<DisableLayerRunnable> mPostedRunnables = new ArrayList<DisableLayerRunnable>(); static final SlidingPanelLayoutImpl IMPL; static { final int deviceVersion = Build.VERSION.SDK_INT; if (deviceVersion >= 16) { IMPL = new SlidingPanelLayoutImplJB(); } else { IMPL = new SlidingPanelLayoutImplBase(); } } private PanelSlideListener mPanelSlideListener; /** * Listener for monitoring events about the sliding pane. */ public interface PanelSlideListener { /** * Called when the sliding pane position changes. * @param slideOffset The new offset of this sliding pane within its range, from 0-1 */ public void onPanelSlide(float slideOffset); /** * Called when the sliding pane becomes slid open. */ public void onPanelOpened(); /** * Called when the sliding pane becomes slid open entirely. */ public void onPanelOpenedEntirely(); /** * Called when a sliding pane becomes slid completely closed. */ public void onPanelClosed(); } public SlidingPaneLayout(Context context) { this(context, null); } public SlidingPaneLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SlidingPaneLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mOverhangSize = -1; if (attrs != null) { TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SlidingPaneLayout); if (ta != null) { mOverhangSize = ta.getDimensionPixelSize(R.styleable.SlidingPaneLayout_overhangSize, -1); ta.recycle(); } } final float density = context.getResources().getDisplayMetrics().density; if (mOverhangSize == -1) { mOverhangSize = (int) (DEFAULT_OVERHANG_SIZE * density + 0.5f); } setWillNotDraw(false); ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegate()); ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); mDragHelper = ViewDragHelper.create(this, 1.0f, new DragHelperCallback()); mDragHelper.setMinVelocity(MIN_FLING_VELOCITY * density); } /** * Set the panel slide listener. * @param l the PanelSlideListener */ public void setPanelSlideListener(PanelSlideListener l) { mPanelSlideListener = l; } /** * Set the color used to fade the pane covered by the sliding pane out when the pane * will become fully covered in the closed state. * * @param color An ARGB-packed color value */ public void setCoveredFadeColor(int color) { mCoveredFadeColor = color; } /** * @return The ARGB-packed color value used to fade the fixed pane */ public int getCoveredFadeColor() { return mCoveredFadeColor; } void updateObscuredViewsVisibility(View panel) { final int leftBound = getPaddingLeft(); final int rightBound = getWidth() - getPaddingRight(); final int topBound = getPaddingTop(); final int bottomBound = getHeight() - getPaddingBottom(); final int left; final int right; final int top; final int bottom; if (panel != null && viewIsOpaque(panel)) { left = panel.getLeft(); right = panel.getRight(); top = panel.getTop(); bottom = panel.getBottom(); } else { left = right = top = bottom = 0; } for (int i = 0, childCount = getChildCount(); i < childCount; i++) { final View child = getChildAt(i); if (child == panel) { // There are still more children above the panel but they won't be affected. break; } final int clampedChildLeft = Math.max(leftBound, child.getLeft()); final int clampedChildTop = Math.max(topBound, child.getTop()); final int clampedChildRight = Math.min(rightBound, child.getRight()); final int clampedChildBottom = Math.min(bottomBound, child.getBottom()); final int vis; if (clampedChildLeft >= left && clampedChildTop >= top && clampedChildRight <= right && clampedChildBottom <= bottom) { vis = INVISIBLE; } else { vis = VISIBLE; } child.setVisibility(vis); } } void setAllChildrenVisible() { for (int i = 0, childCount = getChildCount(); i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == INVISIBLE) { child.setVisibility(VISIBLE); } } } private static boolean viewIsOpaque(View v) { if (ViewCompat.isOpaque(v)) return true; // View#isOpaque didn't take all valid opaque scrollbar modes into account // before API 18 (JB-MR2). On newer devices rely solely on isOpaque above and return false // here. On older devices, check the view's background drawable directly as a fallback. if (Build.VERSION.SDK_INT >= 18) return false; final Drawable bg = v.getBackground(); if (bg != null) { return bg.getOpacity() == PixelFormat.OPAQUE; } return false; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mFirstLayout = true; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mFirstLayout = true; for (int i = 0, count = mPostedRunnables.size(); i < count; i++) { final DisableLayerRunnable dlr = mPostedRunnables.get(i); dlr.run(); } mPostedRunnables.clear(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); if (heightMode != MeasureSpec.EXACTLY) { if (isInEditMode()) { // Don't crash the layout editor. Consume all of the space if specified // or pick a magic number from thin air otherwise. // TODO Better communication with tools of this bogus state. // It will crash on a real device. if (heightMode == MeasureSpec.AT_MOST) { heightMode = MeasureSpec.EXACTLY; } else if (heightMode == MeasureSpec.UNSPECIFIED) { heightMode = MeasureSpec.EXACTLY; heightMode = 300; } } else { throw new IllegalStateException("Height must have an exact value or MATCH_PARENT"); } } else if (widthMode == MeasureSpec.UNSPECIFIED) { if (isInEditMode()) { // Don't crash the layout editor. Pick a magic number from thin air instead. // TODO Better communication with tools of this bogus state. // It will crash on a real device. if (widthMode == MeasureSpec.UNSPECIFIED) { widthMode = MeasureSpec.AT_MOST; widthMode = 300; } } else { throw new IllegalStateException("Width must not be UNSPECIFIED"); } } int layoutWidth = 0; int maxLayoutWidth = -1; switch (widthMode) { case MeasureSpec.EXACTLY: layoutWidth = maxLayoutWidth = widthSize - getPaddingLeft() - getPaddingRight(); break; case MeasureSpec.AT_MOST: maxLayoutWidth = widthSize - getPaddingLeft() - getPaddingRight(); break; } boolean canSlide = false; final int heightAvailable = heightSize - getPaddingTop() - getPaddingBottom(); final int childCount = getChildCount(); if (childCount > 2) { Log.e(TAG, "onMeasure: More than two child views are not supported."); } // We'll find the current one below. mSlideableView = null; // First pass. Measure based on child LayoutParams width/height. for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (child.getVisibility() == GONE) { continue; } int childHeightSpec; final int verticalMargin = lp.topMargin + lp.bottomMargin; if (lp.height == LayoutParams.WRAP_CONTENT) { childHeightSpec = MeasureSpec.makeMeasureSpec(heightAvailable - verticalMargin, MeasureSpec.AT_MOST); } else if (lp.height == LayoutParams.MATCH_PARENT) { childHeightSpec = MeasureSpec.makeMeasureSpec(heightAvailable - verticalMargin, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY); } int childWidthSpec; if (lp.width == LayoutParams.WRAP_CONTENT) { childWidthSpec = MeasureSpec.makeMeasureSpec(maxLayoutWidth, MeasureSpec.AT_MOST); } else if (lp.width == LayoutParams.MATCH_PARENT) { childWidthSpec = MeasureSpec.makeMeasureSpec(maxLayoutWidth, MeasureSpec.EXACTLY); } else { childWidthSpec = MeasureSpec.makeMeasureSpec(lp.width, MeasureSpec.EXACTLY); } child.measure(childWidthSpec, childHeightSpec); final int childWidth = child.getMeasuredWidth(); if (widthMode == MeasureSpec.AT_MOST && childWidth > layoutWidth) { layoutWidth = Math.min(childWidth, maxLayoutWidth); } if (i == childCount - 1) { canSlide |= lp.slideable = true; mSlideableView = child; } } final int measuredHeight = heightSize; final int measuredWidth = layoutWidth + getPaddingLeft() + getPaddingRight(); setMeasuredDimension(measuredWidth, measuredHeight); mCanSlide = canSlide; if (mDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE && !canSlide) { // Cancel scrolling in progress, it's no longer relevant. mDragHelper.abort(); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int height = b - t; final int paddingTop = getPaddingTop(); final int paddingBottom = getPaddingBottom(); final int paddingLeft = getPaddingLeft(); final int childCount = getChildCount(); int yStart = paddingTop; int nextYStart = yStart; for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int childHeight = child.getMeasuredHeight(); int offset = 0; if (lp.slideable) { final int margin = lp.topMargin + lp.bottomMargin; final int range = Math.min(nextYStart, height - paddingBottom) - yStart - margin; mSlideRange = range; if (mFirstLayout) { switch (mState) { case STATE_CLOSED: mSlideOffset = mCanSlide ? 0.f : 1.f; break; case STATE_OPENED: mSlideOffset = mCanSlide ? 1 - (float)mOverhangSize / mSlideRange : 1.f; break; default: // STATE_OPENED_ENTIRELY mSlideOffset = 1.f; break; } } final int pos = (int) (range * mSlideOffset); yStart += pos + lp.topMargin; mSlideOffset = (float) pos / mSlideRange; } else { yStart = nextYStart; } final int childTop = yStart - offset; final int childBottom = childTop + childHeight; final int childLeft = paddingLeft; final int childRight = childLeft + child.getMeasuredWidth(); child.layout(paddingLeft, childTop, childRight, childBottom); nextYStart += child.getHeight(); } if (mFirstLayout) { updateObscuredViewsVisibility(mSlideableView); } mFirstLayout = false; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // Recalculate sliding panes and their details if (h != oldh) { mFirstLayout = true; } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { final int action = MotionEventCompat.getActionMasked(ev); if (!mCanSlide || (mIsUnableToDrag && action != MotionEvent.ACTION_DOWN)) { mDragHelper.cancel(); return super.onInterceptTouchEvent(ev); } if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { mDragHelper.cancel(); return false; } float x,y; switch (action) { case MotionEvent.ACTION_DOWN: mIsUnableToDrag = false; x = ev.getX(); y = ev.getY(); mInitialMotionX = x; mInitialMotionY = y; break; case MotionEvent.ACTION_MOVE: x = ev.getX(); y = ev.getY(); final float adx = Math.abs(x - mInitialMotionX); final float ady = Math.abs(y - mInitialMotionY); final int slop = mDragHelper.getTouchSlop(); if (ady > slop && adx > ady) { mDragHelper.cancel(); mIsUnableToDrag = true; return false; } } final boolean interceptForDrag = mDragHelper.shouldInterceptTouchEvent(ev) // Intercept touch events only in the overhang area. && (ev.getY() <= mSlideOffset * mSlideRange + mOverhangSize && mState != STATE_OPENED_ENTIRELY); return interceptForDrag; } @Override public boolean onTouchEvent(MotionEvent ev) { if (!mCanSlide) { return super.onTouchEvent(ev); } try { mDragHelper.processTouchEvent(ev); } catch (IllegalArgumentException ex) { } catch (ArrayIndexOutOfBoundsException ex) { } return true; } private boolean closePane(View pane, int initialVelocity) { if (mFirstLayout) { mState = STATE_CLOSED; if (mPanelSlideListener != null) mPanelSlideListener.onPanelClosed(); return true; } else if (smoothSlideTo(0.f, initialVelocity)) return true; else return false; } private boolean openPaneEntirely(View pane, int initialVelocity) { if (mFirstLayout) { mState = STATE_OPENED_ENTIRELY; if (mPanelSlideListener != null) mPanelSlideListener.onPanelOpenedEntirely(); return true; } else if (smoothSlideTo(1.f, initialVelocity)) return true; else return false; } private boolean openPane(View pane, int initialVelocity) { if (mFirstLayout) { mState = STATE_OPENED; if (mPanelSlideListener != null) mPanelSlideListener.onPanelOpened(); return true; } else if (smoothSlideTo(1 - (float)mOverhangSize / mSlideRange, initialVelocity)) return true; else return false; } /** * Open partially the sliding pane if it is currently slideable. If first layout * has already completed this will animate. * * @return true if the pane was slideable and is now open/in the process of opening */ public boolean openPane() { return openPane(mSlideableView, 0); } /** * Open entirely the sliding pane if it is currently slideable. If first layout * has already completed this will animate. * * @return true if the pane was slideable and is now closed/in the process of closing */ public boolean openPaneEntirely() { return openPaneEntirely(mSlideableView, 0); } /** * Close the sliding pane if it is currently slideable. If first layout * has already completed this will animate. * * @return true if the pane was slideable and is now closed/in the process of closing */ public boolean closePane() { return closePane(mSlideableView, 0); } /** * Return the open state of the pane. * @return STATE_OPEN, STATE_OPEN_ENTIRELY or STATE_CLOSED */ public int getState() { return mState; } /** * Check if the content in this layout cannot fully fit side by side and therefore * the content pane can be slid back and forth. * * @return true if content in this layout can be slid open and closed */ public boolean isSlideable() { return mCanSlide; } private void onPanelDragged(int newTop) { if (mSlideableView == null) { // This can happen if we're aborting motion during layout because everything now fits. mSlideOffset = 0; return; } final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams(); final int topBound = getPaddingTop() + lp.topMargin; mSlideOffset = (float) (newTop - topBound) / mSlideRange; } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); boolean result; final int save = canvas.save(Canvas.CLIP_SAVE_FLAG); if (mCanSlide && !lp.slideable && mSlideableView != null) { // Clip against the slider; no sense drawing what will immediately be covered. canvas.getClipBounds(mTmpRect); mTmpRect.bottom = Math.min(mTmpRect.bottom, mSlideableView.getTop()); canvas.clipRect(mTmpRect); } result = super.drawChild(canvas, child, drawingTime); canvas.restoreToCount(save); return result; } private void invalidateChildRegion(View v) { IMPL.invalidateChildRegion(this, v); } /** * Smoothly animate mDraggingPane to the target X position within its range. * * @param slideOffset position to animate to * @param velocity initial velocity in case of fling, or 0. */ boolean smoothSlideTo(float slideOffset, int velocity) { if (!mCanSlide) { // Nothing to do. return false; } final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams(); final int topBound = getPaddingTop() + lp.topMargin; int y = (int) (topBound + slideOffset * mSlideRange); if (mDragHelper.smoothSlideViewTo(mSlideableView, mSlideableView.getLeft(), y)) { setAllChildrenVisible(); ViewCompat.postInvalidateOnAnimation(this); return true; } return false; } @Override public void computeScroll() { if (mDragHelper.continueSettling(true)) { if (!mCanSlide) { mDragHelper.abort(); return; } ViewCompat.postInvalidateOnAnimation(this); } } /** * Set a drawable to use as a shadow cast by the right pane onto the left pane * during opening/closing. * * @param d drawable to use as a shadow */ public void setShadowDrawable(Drawable d) { mShadowDrawable = d; } /** * Set a drawable to use as a shadow cast by the right pane onto the left pane * during opening/closing. * * @param resId Resource ID of a drawable to use */ public void setShadowResource(int resId) { setShadowDrawable(getResources().getDrawable(resId)); } @Override public void draw(Canvas c) { super.draw(c); final View shadowView = getChildCount() > 1 ? getChildAt(1) : null; if (shadowView == null || mShadowDrawable == null) { // No need to draw a shadow if we don't have one. return; } final int shadowHeight = mShadowDrawable.getIntrinsicHeight(); final int right = shadowView.getRight(); final int left = shadowView.getLeft(); final int bottom = shadowView.getTop(); final int top = bottom - shadowHeight; mShadowDrawable.setBounds(left, top, right, bottom); mShadowDrawable.draw(c); } /** * Tests scrollability within child views of v given a delta of dy. * * @param v View to test for vertical scrollability * @param checkV Whether the view v passed should itself be checked for scrollability (true), * or just its children (false). * @param dy Delta scrolled in pixels * @param x X coordinate of the active touch point * @param y Y coordinate of the active touch point * @return true if child views of v can be scrolled by delta of dy. */ protected boolean canScroll(View v, boolean checkV, int dy, int x, int y) { if (v instanceof ViewGroup) { final ViewGroup group = (ViewGroup) v; final int scrollX = v.getScrollX(); final int scrollY = v.getScrollY(); final int count = group.getChildCount(); // Count backwards - let topmost views consume scroll distance first. for (int i = count - 1; i >= 0; i--) { // TODO: Add versioned support here for transformed views. // This will not work for transformed views in Honeycomb+ final View child = group.getChildAt(i); if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && canScroll(child, true, dy, x + scrollX - child.getLeft(), y + scrollY - child.getTop())) { return true; } } } return checkV && ViewCompat.canScrollVertically(v, -dy); } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(); } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return p instanceof MarginLayoutParams ? new LayoutParams((MarginLayoutParams) p) : new LayoutParams(p); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams && super.checkLayoutParams(p); } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.state = mState; return ss; } @Override protected void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); switch(ss.state) { case STATE_OPENED: openPane(); break; case STATE_OPENED_ENTIRELY: openPaneEntirely(); break; case STATE_CLOSED: closePane(); } } private class DragHelperCallback extends ViewDragHelper.Callback { @Override public boolean tryCaptureView(View child, int pointerId) { if (mIsUnableToDrag) { return false; } return ((LayoutParams) child.getLayoutParams()).slideable; } @Override public void onViewCaptured(View capturedChild, int activePointerId) { // Make all child views visible in preparation for sliding things around setAllChildrenVisible(); } @Override public void onViewDragStateChanged(int state) { if (mDragHelper.getViewDragState() == ViewDragHelper.STATE_IDLE) { if (mSlideOffset == 0) { if (mState != STATE_CLOSED) { mState = STATE_CLOSED; if (mPanelSlideListener != null) mPanelSlideListener.onPanelClosed(); } } else if (Math.abs(mSlideOffset - (1 - (float)mOverhangSize / mSlideRange)) <= 0.001) { if (mState != STATE_OPENED) { mState = STATE_OPENED; if (mPanelSlideListener != null) mPanelSlideListener.onPanelOpened(); } } else if (mSlideOffset == 1) { if (mState != STATE_OPENED_ENTIRELY) { mState = STATE_OPENED_ENTIRELY; if (mPanelSlideListener != null) mPanelSlideListener.onPanelOpenedEntirely(); } } } } @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { onPanelDragged(top); if (mPanelSlideListener != null) mPanelSlideListener.onPanelSlide(mSlideOffset); invalidate(); } @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { final LayoutParams lp = (LayoutParams) releasedChild.getLayoutParams(); int top = getPaddingTop() + lp.topMargin; if (yvel > 0 || (yvel == 0 && mSlideOffset > 0.5f)) { top += mSlideRange - mOverhangSize; } mDragHelper.settleCapturedViewAt(releasedChild.getLeft(), top); invalidate(); } @Override public int getViewVerticalDragRange(View child) { return mSlideRange; } @Override public int clampViewPositionVertical(View child, int top, int dy) { final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams(); final int topBound = getPaddingTop() + lp.topMargin; final int bottomBound = topBound + mSlideRange - mOverhangSize; final int newTop = Math.min(Math.max(top, topBound), bottomBound); return newTop; } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { // Make sure we never move views horizontally. // This could happen if the child has less width than its parent. return child.getLeft(); } } /** * Test if the second child is displayed under the coordinates given in parameters. * @param x * @param y * @return true if the second child is displayed else false. */ public boolean isSecondChildUnder(int x, int y) { View secondChild = getChildAt(1); if (secondChild == null) return false; return mDragHelper.isViewUnder(secondChild, x, y); } public static class LayoutParams extends ViewGroup.MarginLayoutParams { /** * True if this pane is the slidable pane in the layout. */ boolean slideable; public LayoutParams() { super(MATCH_PARENT, MATCH_PARENT); } public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(android.view.ViewGroup.LayoutParams source) { super(source); } public LayoutParams(MarginLayoutParams source) { super(source); } public LayoutParams(LayoutParams source) { super(source); } public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); } } static class SavedState extends BaseSavedState { int state; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); state = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(state); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } interface SlidingPanelLayoutImpl { void invalidateChildRegion(SlidingPaneLayout parent, View child); } static class SlidingPanelLayoutImplBase implements SlidingPanelLayoutImpl { @Override public void invalidateChildRegion(SlidingPaneLayout parent, View child) { ViewCompat.postInvalidateOnAnimation(parent, child.getLeft(), child.getTop(), child.getRight(), child.getBottom()); } } static class SlidingPanelLayoutImplJB extends SlidingPanelLayoutImplBase { /* * Private API hacks! Nasty! Bad! * * In Jellybean, some optimizations in the hardware UI renderer * prevent a changed Paint on a View using a hardware layer from having * the intended effect. This twiddles some internal bits on the view to force * it to recreate the display list. */ private Method mGetDisplayList; private Field mRecreateDisplayList; SlidingPanelLayoutImplJB() { try { mGetDisplayList = View.class.getDeclaredMethod("getDisplayList", (Class[]) null); } catch (NoSuchMethodException e) { Log.e(TAG, "Couldn't fetch getDisplayList method; dimming won't work right.", e); } try { mRecreateDisplayList = View.class.getDeclaredField("mRecreateDisplayList"); mRecreateDisplayList.setAccessible(true); } catch (NoSuchFieldException e) { Log.e(TAG, "Couldn't fetch mRecreateDisplayList field; dimming will be slow.", e); } } @Override public void invalidateChildRegion(SlidingPaneLayout parent, View child) { if (mGetDisplayList != null && mRecreateDisplayList != null) { try { mRecreateDisplayList.setBoolean(child, true); mGetDisplayList.invoke(child, (Object[]) null); } catch (Exception e) { Log.e(TAG, "Error refreshing display list state", e); } } else { // Slow path. REALLY slow path. Let's hope we don't get here. child.invalidate(); return; } super.invalidateChildRegion(parent, child); } } class AccessibilityDelegate extends AccessibilityDelegateCompat { private final Rect mTmpRect = new Rect(); @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { final AccessibilityNodeInfoCompat superNode = AccessibilityNodeInfoCompat.obtain(info); super.onInitializeAccessibilityNodeInfo(host, superNode); copyNodeInfoNoChildren(info, superNode); superNode.recycle(); info.setClassName(SlidingPaneLayout.class.getName()); info.setSource(host); final ViewParent parent = ViewCompat.getParentForAccessibility(host); if (parent instanceof View) { info.setParent((View) parent); } // This is a best-approximation of addChildrenForAccessibility() // that accounts for filtering. final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == View.VISIBLE) { // Force importance to "yes" since we can't read the value. ViewCompat.setImportantForAccessibility( child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); info.addChild(child); } } } @Override public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { super.onInitializeAccessibilityEvent(host, event); event.setClassName(SlidingPaneLayout.class.getName()); } @Override public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, AccessibilityEvent event) { return super.onRequestSendAccessibilityEvent(host, child, event); } /** * This should really be in AccessibilityNodeInfoCompat, but there unfortunately * seem to be a few elements that are not easily cloneable using the underlying API. * Leave it private here as it's not general-purpose useful. */ private void copyNodeInfoNoChildren(AccessibilityNodeInfoCompat dest, AccessibilityNodeInfoCompat src) { final Rect rect = mTmpRect; src.getBoundsInParent(rect); dest.setBoundsInParent(rect); src.getBoundsInScreen(rect); dest.setBoundsInScreen(rect); dest.setVisibleToUser(src.isVisibleToUser()); dest.setPackageName(src.getPackageName()); dest.setClassName(src.getClassName()); dest.setContentDescription(src.getContentDescription()); dest.setEnabled(src.isEnabled()); dest.setClickable(src.isClickable()); dest.setFocusable(src.isFocusable()); dest.setFocused(src.isFocused()); dest.setAccessibilityFocused(src.isAccessibilityFocused()); dest.setSelected(src.isSelected()); dest.setLongClickable(src.isLongClickable()); dest.addAction(src.getActions()); dest.setMovementGranularities(src.getMovementGranularities()); } } private class DisableLayerRunnable implements Runnable { final View mChildView; @SuppressWarnings("unused") DisableLayerRunnable(View childView) { mChildView = childView; } @Override public void run() { if (mChildView.getParent() == SlidingPaneLayout.this) { ViewCompat.setLayerType(mChildView, ViewCompat.LAYER_TYPE_NONE, null); invalidateChildRegion(mChildView); } mPostedRunnables.remove(this); } } }
[ "zhangxinmeng@kuner.com.cn" ]
zhangxinmeng@kuner.com.cn
18cad04e8d03472c9ea2ef03ed3bd2c2533a5823
9e61cc18f5ac4f9fc700c7b471b6457a76b04e43
/DAZOMBES/src/com/Zombs/iodemo/pLAYE.java
c9ebcb9e2281e18ae7836d519a94452103e2942f
[]
no_license
THELEGENNNND27/MOSE
9938a7d199785b96b13c9600486f19d3b9fab23d
989d29748856cecbcea0893924fb0eea3aa14531
refs/heads/master
2021-01-01T04:48:54.323650
2017-07-14T16:54:25
2017-07-14T16:54:25
97,254,861
0
0
null
null
null
null
UTF-8
Java
false
false
1,478
java
package com.Zombs.iodemo; import java.awt.*; import java.util.ArrayList; /** * Created by John on 7/11/2017. */ public class pLAYE { Rectangle bounds; double vx, vy; int speed; int accel; public int x; public pLAYE(){ bounds = new Rectangle(20, 20, 10, 10); vx = 0; vy = 0; speed = 3; accel = 1; } public void draw(Graphics g){ g.setColor(Color.MAGENTA); g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height); } public void move(ArrayList<String> dirs){ for (int i = 0; i < dirs.size(); i++) { if(dirs.get(i).equals("up")){ vy -= accel; } if(dirs.get(i).equals("down")) { vy += accel; } if(dirs.get(i).equals("left")) { vx -= accel; } if(dirs.get(i).equals("right")) { vx += accel; } } if (vx > speed){ vx = speed; } if (vx < -speed){ vx = -speed; } if (vy > speed){ vy = speed; } if (vy < -speed){ vy = -speed; } bounds.x += (int) vx; bounds.y += (int) vy; vx *= 0.9; vy *= 0.9; } public Rectangle getBounds(){ return bounds; } public void hit() { } }
[ "noreply@github.com" ]
noreply@github.com
3755ec061fed1742a7ad890ae146f302291c84cb
be64341e8134e87abc76460554166636041961ef
/Framework/src/main/java/at/tugraz/ist/qs2021/messageboard/clientmessages/InitAck.java
9350be909610940715800f958df79e16db42a852
[]
no_license
lailaelsh/QS
b7f3c3c2d40cf8fc291da863e935608164f9a0d9
83d8d1e6b5fea132e973edaeb62848afe1c8c50f
refs/heads/master
2023-05-11T03:08:24.769585
2021-06-03T10:35:13
2021-06-03T10:35:13
353,461,780
0
0
null
null
null
null
UTF-8
Java
false
false
792
java
package at.tugraz.ist.qs2021.messageboard.clientmessages; import at.tugraz.ist.qs2021.actorsystem.SimulatedActor; /** * Message sent from worker to client to tell the client * that the communication initiation was successful */ public class InitAck extends ClientMessage { /** * The worker serving the client during this communication/session * this worker reference can be used to send messages to */ public final SimulatedActor worker; public InitAck(SimulatedActor worker, long communicationId) { super(communicationId); this.worker = worker; } @Override public int getDuration() { return 1; } @Override public String toString() { return "InitAck(" + worker + ", " + communicationId + ')'; } }
[ "laila.elshafie@student.tugraz.at" ]
laila.elshafie@student.tugraz.at
ee0ce3bfda3d162e6ee2b15d3a6b193adf89a460
23f4d78623458d375cf23b7017c142dd45c32481
/Core/orient-collab/src/com/orient/collab/util/JPDLTool.java
78fc36ea2533f94a5bffe17d9e1fe1a8f9ed0224
[]
no_license
lcr863254361/weibao_qd
4e2165efec704b81e1c0f57b319e24be0a1e4a54
6d12c52235b409708ff920111db3e6e157a712a6
refs/heads/master
2023-04-03T00:37:18.947986
2021-04-11T15:12:45
2021-04-11T15:12:45
356,436,350
0
0
null
null
null
null
UTF-8
Java
false
false
13,055
java
package com.orient.collab.util; import com.orient.collab.config.CollabConstants; import com.orient.flow.extend.activity.CounterSignActivity; import com.orient.jpdl.model.*; import com.orient.jpdl.model.Process; import com.orient.utils.CommonTools; import com.orient.workflow.bean.AssignUser; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.ValidationException; import java.io.IOException; import java.io.StringWriter; import java.lang.Object; import java.lang.String; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * jpdl tool used to create or update jpdl content from collab task * * @author Seraph * 2016-08-09 下午5:00 */ public class JPDLTool { public static final String MAIN_FLOW = "main"; static public JPDLTool getInstance(){ return new JPDLTool(); } private JPDLTool(){ } public String createJpdlContentFromCollabTasks(List<com.orient.collab.model.Task> collabTasks, String processName, String type) { //创建流程对象 Process process = new Process(); process.setName(processName); process.setCategory(type); ProcessChoice pc = new ProcessChoice(); process.setProcessChoice(pc); ProcessChoiceItem[] pcItemArr = new ProcessChoiceItem[collabTasks.size()+2]; ProcessChoiceItem pcItem = new ProcessChoiceItem(); ActivityGroup group = new ActivityGroup(); //开始节点 int x = 100; int y = 100; Start start = new Start(); start.setName("开始1"); start.setG(x+25 + "," + y +",92,52"); group.setStart(start); pcItem.setActivityGroup(group); pcItemArr[0]=pcItem; for(int i=0;i<collabTasks.size();i++){ //循环遍历 com.orient.collab.model.Task collabTask = collabTasks.get(i); y = y + 100; if(CollabConstants.TASK_TYPE_COUNTERSIGN.equals(collabTask.getType())){ Custom custom = getCumstom(collabTask, x, y); group = new ActivityGroup(); group.setCustom(custom); }else{ //普通任务 Task task = new Task(); task.setG(x + "," +y + ",92,52"); task.setName(collabTask.getName()); String assignee = CommonTools.Obj2String(collabTask.getPrincipal()); if(assignee.contains(AssignUser.DELIMITER)){ task.setCandidateUsers(assignee); }else{ task.setAssignee(assignee); } group = new ActivityGroup(); group.setTask(task); } pcItem = new ProcessChoiceItem(); pcItem.setActivityGroup(group); pcItemArr[1+i]=pcItem; } y = y + 100; //结束节点 End end = new End(); end.setName("结束1"); end.setG(x+25 + "," + y +",92,52"); pcItem = new ProcessChoiceItem(); group = new ActivityGroup(); group.setEnd(end); //组装 pcItem.setActivityGroup(group); pcItemArr[1+collabTasks.size()]=pcItem; pc.setProcessChoiceItem(pcItemArr); StringWriter sw = new StringWriter(); try { process.marshal(sw); sw.close(); } catch (MarshalException e) { e.printStackTrace(); } catch (ValidationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sw.toString(); } public String updateJpdlContentWithCollabTasks(Process process, List<com.orient.collab.model.Task> collabTasks){ Process realProcess = new Process(); realProcess.setName(process.getName()); realProcess.setCategory(process.getCategory()); //遍历数据库取出来的jpdl流程 ProcessChoice oriProcessChoice = process.getProcessChoice(); ProcessChoiceItem[] oriItems = oriProcessChoice.getProcessChoiceItem(); //过滤出分支 以及 合并 List<ProcessChoiceItem> otherItems = new ArrayList<ProcessChoiceItem>(); for(ProcessChoiceItem item : oriItems){ ActivityGroup activityGroup = item.getActivityGroup(); Object choiceValue = activityGroup.getChoiceValue(); if(choiceValue instanceof Fork || choiceValue instanceof Join || choiceValue instanceof Decision || choiceValue instanceof EndCancel || choiceValue instanceof EndError){ otherItems.add(item); } } ProcessChoice pc = new ProcessChoice(); ProcessChoiceItem[] pcItemArr = new ProcessChoiceItem[collabTasks.size()+2+otherItems.size()]; //装配 开始 以及 结束节点 for(ProcessChoiceItem item : oriItems){ ActivityGroup activityGroup = item.getActivityGroup(); Object choiceValue = activityGroup.getChoiceValue(); if(choiceValue instanceof Start) { pcItemArr[0] = item; }else if(choiceValue instanceof End) { pcItemArr[1+collabTasks.size()] = item; } } //装配特殊节点 for(int i=0;i<otherItems.size();i++){ ProcessChoiceItem item = otherItems.get(i); pcItemArr[2+collabTasks.size()+i] = item; } syncNode(collabTasks,oriItems,pcItemArr); pc.setProcessChoiceItem(pcItemArr); realProcess.setProcessChoice(pc); StringWriter sw = new StringWriter(); //返回结果 String retStr = ""; try { realProcess.marshal(sw); sw.close(); retStr = sw.toString(); } catch (MarshalException e) { e.printStackTrace(); } catch (ValidationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return retStr; } private void syncNode(List<com.orient.collab.model.Task> collabTasks, ProcessChoiceItem[] oriItems, ProcessChoiceItem[] pcItemArr) { //装配 任务 int i = 0; for(com.orient.collab.model.Task collabTask : collabTasks) { //任务名称 String taskName = collabTask.getName(); boolean choosen = false; //遍历已经存在的节点信息 for(ProcessChoiceItem item : oriItems) { ActivityGroup activityGroup = item.getActivityGroup(); Object choiceValue = activityGroup.getChoiceValue(); if(choiceValue instanceof Task) { Task oriTask = (Task)choiceValue; if(oriTask.getName().equals(taskName)) { choosen = true; ProcessChoiceItem tempPcItem = new ProcessChoiceItem(); ActivityGroup tempGroup = new ActivityGroup(); String assignee = CommonTools.Obj2String(collabTask.getPrincipal()); oriTask.setAssignee(assignee); tempGroup.setTask(oriTask); tempPcItem.setActivityGroup(tempGroup); pcItemArr[1+i] = tempPcItem; break; } } else if(choiceValue instanceof Custom){ Custom custom = (Custom) choiceValue; if(custom.getName().equals(taskName)) { choosen = true; ProcessChoiceItem tempPcItem = new ProcessChoiceItem(); ActivityGroup tempGroup = new ActivityGroup(); String assignee = CommonTools.Obj2String(collabTask.getPrincipal()); WireObjectTypeItem[] wireObjectTypeItems = custom.getWireObjectTypeItem(); for(WireObjectTypeItem wireObjectTypeItem : wireObjectTypeItems){ if(wireObjectTypeItem.getField().getName().equals("counterSignUsers")){ com.orient.jpdl.model.String counterSignUsersString = new com.orient.jpdl.model.String(); counterSignUsersString.setValue("1::::" + assignee); wireObjectTypeItem.getField().getWireObjectGroup().setString(counterSignUsersString); break; } } tempGroup.setCustom(custom); tempPcItem.setActivityGroup(tempGroup); pcItemArr[1+i] = tempPcItem; break; } } } if(!choosen) { Random rand = new Random(); int x = rand.nextInt(500); int y = rand.nextInt(500); //如果没有找到 则新增 ProcessChoiceItem tempPcItem = new ProcessChoiceItem(); ActivityGroup tempGroup = new ActivityGroup(); tempPcItem.setActivityGroup(tempGroup); if(CollabConstants.TASK_TYPE_COUNTERSIGN.equals(collabTask.getType())){ Custom custom = getCumstom(collabTask, x, y); tempGroup.setCustom(custom); }else{ //普通任务 Task task = new Task(); task.setG(x + "," +y + ",92,52"); task.setName(collabTask.getName()); String assignee = CommonTools.Obj2String(collabTask.getPrincipal()); if(assignee.contains(AssignUser.DELIMITER)){ task.setCandidateUsers(assignee); }else{ task.setAssignee(assignee); } tempGroup.setTask(task); } pcItemArr[1+i]=tempPcItem; } i++; } } private Custom getCumstom(com.orient.collab.model.Task collabTask, int x, int y){ Custom custom = new Custom(); custom.setName(collabTask.getName()); custom.setG(x + "," +y + ",92,52"); custom.setClazz(CounterSignActivity.class.getName()); WireObjectTypeItem counterSignUsersWire = new WireObjectTypeItem(); Field counterSignUsersField = new Field(); counterSignUsersField.setName("counterSignUsers"); WireObjectGroup counterSignUsersWireObjectGroup = new WireObjectGroup(); com.orient.jpdl.model.String counterSignUsersString = new com.orient.jpdl.model.String(); counterSignUsersString.setValue("1::::" + collabTask.getPrincipal()); counterSignUsersWireObjectGroup.setString(counterSignUsersString); counterSignUsersField.setWireObjectGroup(counterSignUsersWireObjectGroup); counterSignUsersWire.setField(counterSignUsersField); custom.addWireObjectTypeItem(counterSignUsersWire); WireObjectTypeItem strategyWire = new WireObjectTypeItem(); Field strategyField = new Field(); strategyField.setName("strategy"); WireObjectGroup strategyWireObjectGroup = new WireObjectGroup(); com.orient.jpdl.model.String strategyString = new com.orient.jpdl.model.String(); strategyString.setValue("100%"); strategyWireObjectGroup.setString(strategyString); strategyField.setWireObjectGroup(strategyWireObjectGroup); strategyWire.setField(strategyField); custom.addWireObjectTypeItem(strategyWire); WireObjectTypeItem passTrainWriter = new WireObjectTypeItem(); Field passTrainField = new Field(); passTrainField.setName("passTransiton"); WireObjectGroup passTrainWireObjectGroup = new WireObjectGroup(); com.orient.jpdl.model.String passTrainString = new com.orient.jpdl.model.String(); passTrainString.setValue(""); passTrainWireObjectGroup.setString(passTrainString); passTrainField.setWireObjectGroup(passTrainWireObjectGroup); passTrainWriter.setField(passTrainField); custom.addWireObjectTypeItem(passTrainWriter); WireObjectTypeItem noPassTransitonWriter = new WireObjectTypeItem(); Field noPassTransitonField = new Field(); noPassTransitonField.setName("noPassTransiton"); WireObjectGroup noPassTransitonWireObjectGroup = new WireObjectGroup(); com.orient.jpdl.model.String noPassTransitonString = new com.orient.jpdl.model.String(); noPassTransitonString.setValue(""); noPassTransitonWireObjectGroup.setString(noPassTransitonString); noPassTransitonField.setWireObjectGroup(noPassTransitonWireObjectGroup); noPassTransitonWriter.setField(noPassTransitonField); custom.addWireObjectTypeItem(noPassTransitonWriter); return custom; } }
[ "lcr18015367626" ]
lcr18015367626
03d0011e15d9ada697206d01ad16d9be630af2cc
fd68197d77397e943c658bb469b3650fa8618d7d
/BecomeAVolunteer/app/src/main/java/com/example/girishsharma/ApiInterface.java
eabfa280eb17abde6ef3682992a3104c57300cce
[]
no_license
NikhilBorkar123/Girish_sharma
49f52843540bf211bea45e2df07ee33e1709482a
ba269eb331646b8a0654843ea3a316ec64c59a4f
refs/heads/master
2021-07-05T19:30:04.970251
2020-10-02T08:09:24
2020-10-02T08:09:24
190,790,857
0
2
null
2020-10-02T08:09:26
2019-06-07T18:28:23
Java
UTF-8
Java
false
false
1,200
java
package com.example.girishsharma; import com.example.girishsharma.Modal.Response; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; import retrofit2.http.Path; public interface ApiInterface { @POST("becomeAVolunteer") @FormUrlEncoded Call<Response> sendDetails(@Field("volunteerID") String volID, @Field("AppUserID") String appID, @Field("fname") String fname, @Field("lname") String lname, @Field("profession") String prof, @Field("email") String email, @Field("phone") String phone, @Field("address1") String adr1, @Field("address2") String adr2, @Field("city") String city, @Field("state") String state, @Field("pin") String pin, @Field("CMSUserAuthenticationID") String cmID, @Field("picture") String Pic); }
[ "NikhilBorkar123" ]
NikhilBorkar123
8085a531b264ea7d17999014ae6b8caff0dbe3cf
f7e42b605ae0c8180bf0bfdfbcf4e020bf9c4a16
/2nd/Kadai0304.java
20b387ae831ad0174cd768e7a4d46297070357ea
[]
no_license
tadaren/Kadai
a4ee03621f7c590eeed2efbc6a0e3947a956596f
1cc7ed3592aca871142ae2aa2f03f2fbb38e6e9f
refs/heads/master
2020-05-21T16:27:13.770990
2018-02-02T12:52:49
2018-02-02T12:52:49
63,066,290
0
2
null
null
null
null
UTF-8
Java
false
false
2,786
java
import com.sun.istack.internal.NotNull; import java.util.Scanner; public class Kadai0304 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); //配列の数式を入力(係数 != 0) double[] in = new double[3]; for(int i = in.length-1; i >= 0; i--){ System.out.print("x^"+i+"の係数:"); in[i] = stdIn.nextDouble(); if(in[i] == 0){ i--; System.out.println("再入力してください"); } } //出力 printPolynomial(in); //初期の数式 in = deleteZero(in); //後ろの0を消去 double[] dedIn = differential(in); //数式を微分 printPolynomial(dedIn); //出力 double outX = -dedIn[0] / dedIn[1]; //微分した式からXを求める double outY = substitution(in, outX); //Xを代入しYを求める System.out.println("x = " + outX); //出力 System.out.println("y = " + outY); } //引数の数式にkを代入した結果の値を返す public static double substitution(double[] f1x, double k){ double out = 0; for(int i = f1x.length-1; i >= 0; i--){ double b = f1x[i]; for(int j = 0; j < i; j++){ b = b*k; } out += b; } return out; } //引数の配列の後ろに0があった場合消去する public static double[] deleteZero(double[] f2x){ int i = 0; for(int j = f2x.length-1; j >= 0; j--){ if(f2x[j] != 0) break; i++; } if(f2x.length == i) return new double[]{0}; else{ double[] out = new double[f2x.length-i]; for(int j = 0; j < out.length; j++){ out[j] = f2x[j]; } return out; } } //引数の数式を微分した式を返す public static double[] differential(double[] f2x){ double[] f2x2 = new double[f2x.length-1]; for(int j = f2x.length-1; j > 0; j--){ f2x2[j-1] = f2x[j]*j; } return f2x2; } //引数の配列を数式として出力する public static void printPolynomial(double[] f1x){ String out = null; for(int i = f1x.length-1; i >= 0; i--){ if(f1x[i] != 0){ if(out != null){ if(f1x[i] >= 0) out += " + "; else{ out += " - "; f1x[i] = -f1x[i]; } if(f1x[i] != 1) out += f1x[i]; else{ if(i == 0) out += f1x[i] + ""; else out += ""; } if(i == 1) out += "x"; else if(i != 0) out += "x^"+i; }else{ if(f1x[i] == -1) out = "-"; else if(f1x[i] != 1) out = f1x[i] + ""; else{ if(i == 0) out = f1x[i] + ""; else out = ""; } if(i == 1) out += "x"; else if(i != 0) out += "x^"+i; } } } if(out == null) System.out.println(0.0); else System.out.println(out); } }
[ "noreply@github.com" ]
noreply@github.com
856f422d6c22f0499da1c370e257bfd4961e0d01
f8e706de386aa5dea90a67f47fedf042e6664340
/DecoratorDesignPattern.java
ac36e126fc2418ba18f98cf49dc5657d34a8b475
[]
no_license
praveenkishor123/Java
ed292b911b1d68fff79c352ce39ef13e3ebdb4fc
e9cee97faaa4c4e4ad5aabe85a8a13cc24dfc818
refs/heads/master
2020-06-19T09:54:17.900216
2019-04-13T03:56:35
2019-04-13T03:56:35
74,912,082
1
0
null
null
null
null
UTF-8
Java
false
false
1,316
java
interface Cake { void flavour(); int getAmount(); } class BasicCake implements Cake { @Override public void flavour() { System.out.println("Basic Cake"); } @Override public int getAmount() { return 50; } } abstract class CakeDecorator implements Cake { private Cake cake; public CakeDecorator(Cake cake) { this.cake = cake; } @Override public void flavour() { cake.flavour(); } @Override public int getAmount() { return cake.getAmount(); } } class VanillaCake extends CakeDecorator { public VanillaCake(Cake cake) { super(cake); } @Override public void flavour() { super.flavour(); System.out.println("Adding Vanilla falvour"); } @Override public int getAmount() { return super.getAmount() + 10; } } class StrawberyCake extends CakeDecorator { public StrawberyCake(Cake cake) { super(cake); } @Override public void flavour() { super.flavour(); System.out.println("Adding Strawberry falvour"); } @Override public int getAmount() { return super.getAmount() + 10; } } public class DecoratorDesignPattern { public static void main(String[] args) { VanillaCake vanillaStrawberryCake = new VanillaCake(new StrawberyCake(new BasicCake())); vanillaStrawberryCake.flavour(); System.out.println(vanillaStrawberryCake.getAmount()); } }
[ "noreply@github.com" ]
noreply@github.com
10ee81d7a35b7b874661c1eb460d2d46801edfdc
7be6764f0d75d7aecdb173d9e91f3ab4ae995e83
/src/test/java/au/gov/dva/dvasopapi/tests/mocks/processingRules/BoundaryBetweenRhAndBoP.java
b77e46619f22c929f6400527d6053f9020a9ee31
[ "Apache-2.0" ]
permissive
SamMonaghan/dva-sop-api
1a79e5fa06177f9b403f0c07963f96dba10d803d
275de81a5f9b7fc3c0c74b108f6d3da4efa78a34
refs/heads/devtest
2020-05-25T07:43:21.173145
2017-03-27T09:12:14
2017-03-27T09:12:14
84,922,401
0
0
null
2017-03-14T08:07:54
2017-03-14T08:07:54
null
UTF-8
Java
false
false
1,819
java
package au.gov.dva.dvasopapi.tests.mocks.processingRules; import au.gov.dva.sopapi.dtos.EmploymentType; import au.gov.dva.sopapi.dtos.Rank; import au.gov.dva.sopapi.dtos.ServiceBranch; import au.gov.dva.sopapi.interfaces.model.Deployment; import au.gov.dva.sopapi.interfaces.model.Service; import au.gov.dva.sopapi.interfaces.model.ServiceHistory; import com.google.common.collect.ImmutableSet; import java.time.OffsetDateTime; import java.util.Optional; import static au.gov.dva.dvasopapi.tests.TestUtils.odtOf; public class BoundaryBetweenRhAndBoP implements ServiceHistory { @Override public OffsetDateTime getHireDate() { return odtOf(2004,7,20); } @Override public ImmutableSet<Service> getServices() { return ImmutableSet.of( new Service() { @Override public ServiceBranch getBranch() { return ServiceBranch.ARMY; } @Override public EmploymentType getEmploymentType() { return EmploymentType.CTFS; } @Override public Rank getRank() { return Rank.OtherRank; } @Override public OffsetDateTime getStartDate() { return odtOf(2004,7,1); } @Override public Optional<OffsetDateTime> getEndDate() { return Optional.of(odtOf(2004,6,30)); } @Override public ImmutableSet<Deployment> getDeployments() { return null; } } ); } }
[ "nick.miller@govlawtech.com.au" ]
nick.miller@govlawtech.com.au
783b6cb530dd8366d3ec1b8075858407db8a4987
1b2814a2be2f8395c3b81c6329c33fbfcf070a6f
/src/main/java/com/evandrosantos/cursomc/domain/Produto.java
f3f58fb1e3e83e692a13d475a30a5a38390ccb12
[]
no_license
egsevandrosantos/java-spring-boot-ionic-backend
9d842dce229e2a0b32cde3886aaa8f2170a21457
4a678c85ac716647109422d8b4d1a32f26681a4e
refs/heads/master
2022-02-09T00:41:53.237793
2019-07-06T13:54:20
2019-07-06T13:54:20
187,243,621
0
0
null
2022-01-21T23:24:50
2019-05-17T15:49:48
Java
UTF-8
Java
false
false
2,907
java
package com.evandrosantos.cursomc.domain; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnore; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*; import java.io.Serializable; import java.util.*; @Entity @EntityListeners(AuditingEntityListener.class) public class Produto implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String nome; private Double preco; @ManyToMany @JoinTable(name = "CATEGORIA_PRODUTO", joinColumns = @JoinColumn(name = "produto_id"), inverseJoinColumns = @JoinColumn(name = "categoria_id")) @JsonIgnore private List<Categoria> categorias = new ArrayList<>(); @OneToMany(mappedBy = "id.produto") @JsonIgnore private Set<ItemPedido> itens = new HashSet<>(); @Column(name = "created_at", nullable = false, updatable = false) @Temporal(TemporalType.TIMESTAMP) @CreatedDate private Date createdAt; @Column(name = "updated_at", nullable = false) @Temporal(TemporalType.TIMESTAMP) @LastModifiedDate private Date updatedAt; public Produto() { } public Produto(Integer id, String nome, Double preco) { setId(id); setNome(nome); setPreco(preco); } @JsonIgnore public List<Pedido> getPedidos() { List<Pedido> pedidos = new ArrayList<>(); for (ItemPedido x : itens) { pedidos.add(x.getPedido()); } return pedidos; } public Produto(String nome, Double preco) { this(null, nome, preco); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Double getPreco() { return preco; } public void setPreco(Double preco) { this.preco = preco; } public List<Categoria> getCategorias() { return categorias; } public void setCategorias(List<Categoria> categorias) { this.categorias = categorias; } public Set<ItemPedido> getItens() { return this.itens; } public void setItens(Set<ItemPedido> itens) { this.itens = itens; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Produto produto = (Produto) o; return Objects.equals(getId(), produto.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } }
[ "egs.evandro.santos@gmail.com" ]
egs.evandro.santos@gmail.com
3ce9c1d0df9643d7fe20ef522fd5f7378c49f4f8
1902f070f7953dd1d7817c30e518ab27b4efd1dd
/app/src/main/java/dylanbudgen/PassYourExams/Question/MultipleChoiceQuestion.java
51660110ddf6a0988e7d84f8c727029a9d979007
[]
no_license
dylanbudgen/PassYourExams-application
d256cb83e9eaf8cc3d95e49248ee9dc421f34957
37423156f38cbefe5535520a4fda4aea4b6e80d5
refs/heads/master
2021-03-16T08:36:46.720982
2019-07-23T21:38:10
2019-07-23T21:38:10
105,939,815
2
0
null
null
null
null
UTF-8
Java
false
false
1,242
java
package dylanbudgen.PassYourExams.Question; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; /** * Created by dylanbudgen on 18/10/2017. */ public class MultipleChoiceQuestion extends Question implements Serializable { protected String incorrectAnswer1; protected String incorrectAnswer2; protected String incorrectAnswer3; public MultipleChoiceQuestion(String question, String questionId, String questionType, String correctAnswer, String incorrectAnswer1, String incorrectAnswer2, String incorrectAnswer3) { super(question, questionId, questionType, correctAnswer); this.incorrectAnswer1 = incorrectAnswer1; this.incorrectAnswer2 = incorrectAnswer2; this.incorrectAnswer3 = incorrectAnswer3; } public ArrayList<String> getAnswers() { ArrayList<String> answers = new ArrayList<>(); answers.addAll(Arrays.asList(correctAnswer, incorrectAnswer1, incorrectAnswer2, incorrectAnswer2)); Collections.shuffle(answers); return answers; } public String getCorrectAnswer() { return correctAnswer; } }
[ "dylanbudgen@gmail.com" ]
dylanbudgen@gmail.com
3cc42b64feb6736ca0f597bdb99e580550223ec4
52e33c7c3e66b508a440508f2a4235f4f30ac7ff
/src/main/java/com/spring/recopay/datastore/EventStore.java
6d9ba91e0e1b3431e27947269fd4a18a2e61f37f
[]
no_license
Jangho4273/RecoPAY
c60d9d9ee706126d81f5e9b9370cb7206303f5db
9e6f7d7964155e8502e22fb6f83f6ef423157a32
refs/heads/master
2023-04-08T12:17:36.244371
2021-04-23T01:06:39
2021-04-23T01:06:39
353,229,086
0
0
null
null
null
null
UTF-8
Java
false
false
2,440
java
package com.spring.recopay.datastore; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Random; /** * CREATE TABLE Event_Board ( event_uid number NOT NULL, event_title * varchar2(200) NOT NULL, event_contents varchar2(2000) NOT NULL, event_img * varchar2(500) NULL, user_uid number NOT NULL, event_startdate date NULL, * event_enddate date NULL, event_isfinish char(1) NULL ); * * @author aflhzv * */ public class EventStore { public static void main(String[] args) { try { Connection conn = null; PreparedStatement pstmt = null; int totalcnt = 0; Class.forName(C.DRIVER); System.out.println("드라이버 클래스 로딩 성공"); conn = DriverManager.getConnection(C.URL, C.USER, C.PASSWD); System.out.println("DB Connection 성공"); System.out.println(); System.out.println("INSERT"); pstmt = conn.prepareStatement(C.SQL_EVENT_INSERT); for (int i = 0; i < C.EVENT_ROWS; i++) { pstmt.setString(1, "TestTitle" + i); pstmt.setString(2, "대충 할인 이벤트를 진행하고 있다는 내용" + i); pstmt.setString(3, C.EVENT_TEST_URL); pstmt.setString(4, getRandomDate("2021-03-01", "2021-04-01")); // 이벤트 시작 랜덤 날짜 pstmt.setString(5, getRandomDate("2021-04-04", "2021-05-05")); // 이벤트 끝 랜덤 날짜 pstmt.setString(6, "0"); // isfinish -> 0 : 이벤트 중, 1 : 이벤트 끝 totalcnt += pstmt.executeUpdate(); System.out.println("총 (" + totalcnt + "/" + C.EVENT_ROWS + ")개 행(row) INSERT 성공"); } } catch (Exception e) { e.printStackTrace(); } // try~catch end } private static String getRandomDate(String startDay, String endDay) { LocalDate fromDay = LocalDate.of(Integer.parseInt(startDay.substring(0, 4)), Integer.parseInt(startDay.substring(5, 7)), Integer.parseInt(startDay.substring(8, 10))); LocalDate toDay = LocalDate.of(Integer.parseInt(endDay.substring(0, 4)), Integer.parseInt(endDay.substring(5, 7)), Integer.parseInt(endDay.substring(8, 10))); LocalDate randDay = fromDay .plusDays((long) (Math.random() * 10000) % (toDay.toEpochDay() - fromDay.toEpochDay())); return randDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); } }
[ "aflhz@gmail.com" ]
aflhz@gmail.com
42853b6e53432966e9749e056d43bd67796425d9
03106258306bec0c6ae89a06f77c382cc4ec5a59
/src/main/java/se/kth/LogLineParser.java
add9a9f8999f8373d642d48c8314c55281e38679
[ "Apache-2.0" ]
permissive
smkniazi/hdfs-audit-log-analyzer
752953a637aef05a12b53a9f8ed9ed609e417068
435dd30bc2f7c1aa6cebcbfd9aba162724225dee
refs/heads/master
2021-01-17T12:54:19.854551
2016-06-13T10:25:34
2016-06-13T11:38:12
56,153,436
2
0
null
null
null
null
UTF-8
Java
false
false
1,220
java
package se.kth; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by salman on 5/2/16. */ public class LogLineParser { private static String getParameter(String str, String pattern, String paramName) { Pattern p = Pattern.compile(paramName + "=" + pattern); Matcher matcher = p.matcher(str); String value = null; if (matcher.find()) { value = matcher.group(0); value = value.substring((paramName + "=").length(), value.length()); } return value; } public static HdfsExecutedOperation parseHdfsAuditLogLine(final String line) { String cmd = getParameter(line, "[a-zA-Z]+", "cmd"); String src = getParameter(line, "\\S+", "src"); if (src == "null") { src = null; } String dst = getParameter(line, "\\S+", "dst"); if (dst == "null") { dst = null; } String allowedStr = getParameter(line, "[a-zA-Z]+", "allowed"); boolean allowed = Boolean.parseBoolean(allowedStr); if (cmd != null && src != null && ValidHdfsOperations.isValidOperation(cmd) && allowed) { return new HdfsExecutedOperation(ValidHdfsOperations.HdfsOperationName.valueOf(cmd), src, dst, allowed); } return null; } }
[ "salman@sics.se" ]
salman@sics.se
9bcff0ba422808dbb76e2367b7a49ac02e2d2567
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/eclipseswt_cluster/6468/tar_0.java
0fdb6a791289b43eeaf5af65bb1f10b60e8582dd
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
97,503
java
/******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.swt.widgets; import org.eclipse.swt.internal.carbon.OS; import org.eclipse.swt.internal.carbon.CGPoint; import org.eclipse.swt.internal.carbon.ControlFontStyleRec; import org.eclipse.swt.internal.carbon.HMHelpContentRec; import org.eclipse.swt.internal.carbon.Rect; import org.eclipse.swt.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.accessibility.Accessible; /** * Control is the abstract superclass of all windowed user interface classes. * <p> * <dl> * <dt><b>Styles:</b> * <dd>BORDER</dd> * <dd>LEFT_TO_RIGHT, RIGHT_TO_LEFT</dd> * <dt><b>Events:</b> * <dd>FocusIn, FocusOut, Help, KeyDown, KeyUp, MouseDoubleClick, MouseDown, MouseEnter, * MouseExit, MouseHover, MouseUp, MouseMove, Move, Paint, Resize, Traverse, * DragDetect, MenuDetect</dd> * </dl> * <p> * Only one of LEFT_TO_RIGHT or RIGHT_TO_LEFT may be specified. * </p><p> * IMPORTANT: This class is intended to be subclassed <em>only</em> * within the SWT implementation. * </p> */ public abstract class Control extends Widget implements Drawable { /** * the handle to the OS resource * (Warning: This field is platform dependent) * <p> * <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT * public API. It is marked public only so that it can be shared * within the packages provided by SWT. It is not available on all * platforms and should never be accessed from application code. * </p> */ public int handle; Composite parent; String toolTipText; Object layoutData; int drawCount, visibleRgn; Menu menu; float [] foreground, background; Font font; Cursor cursor; GCData gcs[]; Accessible accessible; Control () { /* Do nothing */ } /** * Constructs a new instance of this class given its parent * and a style value describing its behavior and appearance. * <p> * The style value is either one of the style constants defined in * class <code>SWT</code> which is applicable to instances of this * class, or must be built by <em>bitwise OR</em>'ing together * (that is, using the <code>int</code> "|" operator) two or more * of those <code>SWT</code> style constants. The class description * lists the style constants that are applicable to the class. * Style bits are also inherited from superclasses. * </p> * * @param parent a composite control which will be the parent of the new instance (cannot be null) * @param style the style of control to construct * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li> * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li> * </ul> * * @see SWT#BORDER * @see Widget#checkSubclass * @see Widget#getStyle */ public Control (Composite parent, int style) { super (parent, style); this.parent = parent; createWidget (); } /** * Adds the listener to the collection of listeners who will * be notified when the control is moved or resized, by sending * it one of the messages defined in the <code>ControlListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see ControlListener * @see #removeControlListener */ public void addControlListener(ControlListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Resize,typedListener); addListener (SWT.Move,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the control gains or loses focus, by sending * it one of the messages defined in the <code>FocusListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see FocusListener * @see #removeFocusListener */ public void addFocusListener(FocusListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener(SWT.FocusIn,typedListener); addListener(SWT.FocusOut,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when help events are generated for the control, * by sending it one of the messages defined in the * <code>HelpListener</code> interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see HelpListener * @see #removeHelpListener */ public void addHelpListener (HelpListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Help, typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when keys are pressed and released on the system keyboard, by sending * it one of the messages defined in the <code>KeyListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see KeyListener * @see #removeKeyListener */ public void addKeyListener(KeyListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener(SWT.KeyUp,typedListener); addListener(SWT.KeyDown,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when mouse buttons are pressed and released, by sending * it one of the messages defined in the <code>MouseListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseListener * @see #removeMouseListener */ public void addMouseListener(MouseListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener(SWT.MouseDown,typedListener); addListener(SWT.MouseUp,typedListener); addListener(SWT.MouseDoubleClick,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the mouse passes or hovers over controls, by sending * it one of the messages defined in the <code>MouseTrackListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseTrackListener * @see #removeMouseTrackListener */ public void addMouseTrackListener (MouseTrackListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.MouseEnter,typedListener); addListener (SWT.MouseExit,typedListener); addListener (SWT.MouseHover,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the mouse moves, by sending it one of the * messages defined in the <code>MouseMoveListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseMoveListener * @see #removeMouseMoveListener */ public void addMouseMoveListener(MouseMoveListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener(SWT.MouseMove,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the receiver needs to be painted, by sending it * one of the messages defined in the <code>PaintListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see PaintListener * @see #removePaintListener */ public void addPaintListener(PaintListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener(SWT.Paint,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when traversal events occur, by sending it * one of the messages defined in the <code>TraverseListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see TraverseListener * @see #removeTraverseListener */ public void addTraverseListener (TraverseListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Traverse,typedListener); } int colorProc (int inControl, int inMessage, int inDrawDepth, int inDrawInColor) { switch (inMessage) { case OS.kControlMsgApplyTextColor: { if (foreground != null) { OS.RGBForeColor (toRGBColor (foreground)); } else { OS.SetThemeTextColor ((short) OS.kThemeTextColorDialogActive, (short) inDrawDepth, inDrawInColor != 0); } return OS.noErr; } case OS.kControlMsgSetUpBackground: { float [] background = this.background != null ? this.background : getParentBackground (); if (background != null) { OS.RGBBackColor (toRGBColor (background)); } else { OS.SetThemeBackground ((short) OS.kThemeBrushDialogBackgroundActive, (short) inDrawDepth, inDrawInColor != 0); } return OS.noErr; } } return OS.eventNotHandledErr; } void checkBuffered () { style |= SWT.DOUBLE_BUFFERED; } /** * Returns the preferred size of the receiver. * <p> * The <em>preferred size</em> of a control is the size that it would * best be displayed at. The width hint and height hint arguments * allow the caller to ask a control questions such as "Given a particular * width, how high does the control need to be to show all of the contents?" * To indicate that the caller does not wish to constrain a particular * dimension, the constant <code>SWT.DEFAULT</code> is passed for the hint. * </p> * * @param wHint the width hint (can be <code>SWT.DEFAULT</code>) * @param hHint the height hint (can be <code>SWT.DEFAULT</code>) * @return the preferred size of the control * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Layout * @see #getBorderWidth * @see #getBounds * @see #getSize * @see #pack * @see "computeTrim, getClientArea for controls that implement them" */ public Point computeSize (int wHint, int hHint) { return computeSize (wHint, hHint, true); } /** * Returns the preferred size of the receiver. * <p> * The <em>preferred size</em> of a control is the size that it would * best be displayed at. The width hint and height hint arguments * allow the caller to ask a control questions such as "Given a particular * width, how high does the control need to be to show all of the contents?" * To indicate that the caller does not wish to constrain a particular * dimension, the constant <code>SWT.DEFAULT</code> is passed for the hint. * </p><p> * If the changed flag is <code>true</code>, it indicates that the receiver's * <em>contents</em> have changed, therefore any caches that a layout manager * containing the control may have been keeping need to be flushed. When the * control is resized, the changed flag will be <code>false</code>, so layout * manager caches can be retained. * </p> * * @param wHint the width hint (can be <code>SWT.DEFAULT</code>) * @param hHint the height hint (can be <code>SWT.DEFAULT</code>) * @param changed <code>true</code> if the control's contents have changed, and <code>false</code> otherwise * @return the preferred size of the control. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Layout * @see #getBorderWidth * @see #getBounds * @see #getSize * @see #pack * @see "computeTrim, getClientArea for controls that implement them" */ public Point computeSize (int wHint, int hHint, boolean changed) { checkWidget(); int width = DEFAULT_WIDTH; int height = DEFAULT_HEIGHT; if (wHint != SWT.DEFAULT) width = wHint; if (hHint != SWT.DEFAULT) height = hHint; int border = getBorderWidth (); width += border * 2; height += border * 2; return new Point (width, height); } Control computeTabGroup () { if (isTabGroup()) return this; return parent.computeTabGroup (); } Control[] computeTabList() { if (isTabGroup()) { if (getVisible() && getEnabled()) { return new Control[] {this}; } } return new Control[0]; } Control computeTabRoot () { Control[] tabList = parent._getTabList(); if (tabList != null) { int index = 0; while (index < tabList.length) { if (tabList [index] == this) break; index++; } if (index == tabList.length) { if (isTabGroup ()) return this; } } return parent.computeTabRoot (); } void createWidget () { checkOrientation (parent); super.createWidget (); checkBuffered (); setDefaultFont (); setZOrder (); } Color defaultBackground () { return display.getSystemColor (SWT.COLOR_WIDGET_BACKGROUND); } Font defaultFont () { byte [] family = new byte [256]; short [] size = new short [1]; byte [] style = new byte [1]; OS.GetThemeFont ((short) defaultThemeFont (), (short) OS.smSystemScript, family, size, style); short id = OS.FMGetFontFamilyFromName (family); int [] font = new int [1]; OS.FMGetFontFromFontFamilyInstance (id, style [0], font, null); return Font.carbon_new (display, font [0], id, style [0], size [0]); } Color defaultForeground () { return display.getSystemColor (SWT.COLOR_WIDGET_FOREGROUND); } int defaultThemeFont () { if (display.smallFonts) return OS.kThemeSmallSystemFont; return OS.kThemeSystemFont; } void deregister () { super.deregister (); display.removeWidget (handle); } void destroyWidget () { int theControl = topHandle (); releaseHandle (); if (theControl != 0) { OS.DisposeControl (theControl); } } boolean drawFocusRing () { return !display.noFocusRing || getShell ().parent != null; } boolean drawGripper (int x, int y, int width, int height) { return false; } void drawWidget (int control, int damageRgn, int visibleRgn, int theEvent) { if (control != handle) return; if (!hooks (SWT.Paint) && !filters (SWT.Paint)) return; /* Retrieve the damage rect */ Rect rect = new Rect (); OS.GetRegionBounds (visibleRgn, rect); Rect bounds = new Rect (); OS.GetControlBounds (handle, bounds); OS.OffsetRect (rect, (short) -bounds.left, (short) -bounds.top); /* Send paint event */ int [] port = new int [1]; OS.GetPort (port); GCData data = new GCData (); data.port = port [0]; data.paintEvent = theEvent; data.visibleRgn = visibleRgn; GC gc = GC.carbon_new (this, data); Event event = new Event (); event.gc = gc; event.x = rect.left; event.y = rect.top; event.width = rect.right - rect.left; event.height = rect.bottom - rect.top; sendEvent (SWT.Paint, event); event.gc = null; gc.dispose (); } void enableWidget (boolean enabled) { int topHandle = topHandle (); if (enabled) { OS.EnableControl (topHandle); } else { OS.DisableControl (topHandle); } } Cursor findCursor () { if (cursor != null) return cursor; return parent.findCursor (); } void fixFocus (Control focusControl) { Shell shell = getShell (); Control control = this; while ((control = control.parent) != null) { if (control.setFocus ()) return; if (control == shell) break; } shell.setSavedFocus (focusControl); int window = OS.GetControlOwner (handle); OS.ClearKeyboardFocus (window); } int focusHandle () { return handle; } /** * Forces the receiver to have the <em>keyboard focus</em>, causing * all keyboard events to be delivered to it. * * @return <code>true</code> if the control got focus, and <code>false</code> if it was unable to. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #setFocus */ public boolean forceFocus () { checkWidget(); if (display.focusEvent == SWT.FocusOut) return false; Decorations shell = menuShell (); shell.setSavedFocus (this); if (!isEnabled () || !isVisible ()/* || !isActive ()*/) return false; if (isFocusControl ()) return true; shell.setSavedFocus (null); shell.bringToTop (false); if (isDisposed ()) return false; int focusHandle = focusHandle (); int window = OS.GetControlOwner (focusHandle); OS.SetKeyboardFocus (window, focusHandle, (short) OS.kControlFocusNextPart); if (isDisposed ()) return false; shell.setSavedFocus (this); return hasFocus (); } /** * Returns the accessible object for the receiver. * If this is the first time this object is requested, * then the object is created and returned. * * @return the accessible object * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Accessible#addAccessibleListener * @see Accessible#addAccessibleControlListener * * @since 2.0 */ public Accessible getAccessible () { checkWidget (); if (accessible == null) { accessible = Accessible.internal_new_Accessible (this); } return accessible; } /** * Returns the receiver's background color. * * @return the background color * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Color getBackground () { checkWidget(); //NOT DONE - get default colors if (background == null) return defaultBackground (); return Color.carbon_new (display, background); } /** * Returns the receiver's border width. * * @return the border width * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getBorderWidth () { checkWidget(); return 0; } /** * Returns a rectangle describing the receiver's size and location * relative to its parent (or its display if its parent is null), * unless the receiver is a shell. In this case, the location is * relative to the display. * * @return the receiver's bounding rectangle * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Rectangle getBounds () { checkWidget(); Rect rect = getControlBounds (topHandle ()); return new Rectangle (rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); } int getDrawCount (int control) { if (!isTrimHandle (control) && drawCount > 0) return drawCount; return parent.getDrawCount (control); } /** * Returns <code>true</code> if the receiver is enabled, and * <code>false</code> otherwise. A disabled control is typically * not selectable from the user interface and draws with an * inactive or "grayed" look. * * @return the receiver's enabled state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #isEnabled */ public boolean getEnabled () { checkWidget(); return (state & DISABLED) == 0; } /** * Returns the font that the receiver will use to paint textual information. * * @return the receiver's font * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Font getFont () { checkWidget(); return font != null ? font : defaultFont (); } /** * Returns the foreground color that the receiver will use to draw. * * @return the receiver's foreground color * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Color getForeground () { checkWidget(); //NOT DONE - get default colors if (foreground == null) return defaultForeground (); return Color.carbon_new (display, foreground); } /** * Returns layout data which is associated with the receiver. * * @return the receiver's layout data * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Object getLayoutData () { checkWidget(); return layoutData; } /** * Returns a point describing the receiver's location relative * to its parent (or its display if its parent is null), unless * the receiver is a shell. In this case, the point is * relative to the display. * * @return the receiver's location * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Point getLocation () { checkWidget(); Rect rect = getControlBounds (topHandle ()); return new Point (rect.left, rect.top); } /** * Returns the receiver's pop up menu if it has one, or null * if it does not. All controls may optionally have a pop up * menu that is displayed when the user requests one for * the control. The sequence of key strokes, button presses * and/or button releases that are used to request a pop up * menu is platform specific. * * @return the receiver's menu * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Menu getMenu () { checkWidget(); return menu; } /** * Returns the receiver's monitor. * * @return the receiver's monitor * * @since 3.0 */ public Monitor getMonitor () { checkWidget(); Monitor [] monitors = display.getMonitors (); if (monitors.length == 1) return monitors [0]; int index = -1, value = -1; Rectangle bounds = getBounds (); if (this != getShell ()) { bounds = display.map (this.parent, null, bounds); } for (int i=0; i<monitors.length; i++) { Rectangle rect = bounds.intersection (monitors [i].getBounds ()); int area = rect.width * rect.height; if (area > 0 && area > value) { index = i; value = area; } } if (index >= 0) return monitors [index]; int centerX = bounds.x + bounds.width / 2, centerY = bounds.y + bounds.height / 2; for (int i=0; i<monitors.length; i++) { Rectangle rect = monitors [i].getBounds (); int x = centerX < rect.x ? rect.x - centerX : centerX > rect.x + rect.width ? centerX - rect.x - rect.width : 0; int y = centerY < rect.y ? rect.y - centerY : centerY > rect.y + rect.height ? centerY - rect.y - rect.height : 0; int distance = x * x + y * y; if (index == -1 || distance < value) { index = i; value = distance; } } return monitors [index]; } /** * Returns the receiver's parent, which must be a <code>Composite</code> * or null when the receiver is a shell that was created with null or * a display for a parent. * * @return the receiver's parent * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Composite getParent () { checkWidget(); return parent; } float [] getParentBackground () { return parent.background; } Control [] getPath () { int count = 0; Shell shell = getShell (); Control control = this; while (control != shell) { count++; control = control.parent; } control = this; Control [] result = new Control [count]; while (control != shell) { result [--count] = control; control = control.parent; } return result; } /** * Returns the receiver's shell. For all controls other than * shells, this simply returns the control's nearest ancestor * shell. Shells return themselves, even if they are children * of other shells. * * @return the receiver's shell * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #getParent */ public Shell getShell () { checkWidget(); return parent.getShell (); } /** * Returns a point describing the receiver's size. The * x coordinate of the result is the width of the receiver. * The y coordinate of the result is the height of the * receiver. * * @return the receiver's size * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Point getSize () { checkWidget(); Rect rect = getControlSize (topHandle ()); return new Point (rect.right - rect.left, rect.bottom - rect.top); } /** * Returns the receiver's tool tip text, or null if it has * not been set. * * @return the receiver's tool tip text * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public String getToolTipText () { checkWidget(); return toolTipText; } /** * Returns <code>true</code> if the receiver is visible, and * <code>false</code> otherwise. * <p> * If one of the receiver's ancestors is not visible or some * other condition makes the receiver not visible, this method * may still indicate that it is considered visible even though * it may not actually be showing. * </p> * * @return the receiver's visibility state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean getVisible () { checkWidget(); return (state & HIDDEN) == 0; } int getVisibleRegion (int control, boolean clipChildren) { if (!clipChildren) return super.getVisibleRegion (control, clipChildren); if (visibleRgn == 0) { visibleRgn = OS.NewRgn (); calculateVisibleRegion (control, visibleRgn, clipChildren); } int result = OS.NewRgn (); OS.CopyRgn (visibleRgn, result); return result; } boolean hasFocus () { return this == display.getFocusControl (); } int helpProc (int inControl, int inGlobalMouse, int inRequest, int outContentProvided, int ioHelpContent) { switch (inRequest) { case OS.kHMSupplyContent: { int [] contentProvided = new int [] {OS.kHMContentNotProvidedDontPropagate}; if (toolTipText != null && toolTipText.length () != 0) { char [] buffer = new char [toolTipText.length ()]; toolTipText.getChars (0, buffer.length, buffer, 0); int length = fixMnemonic (buffer); if (display.helpString != 0) OS.CFRelease (display.helpString); display.helpString = OS.CFStringCreateWithCharacters (OS.kCFAllocatorDefault, buffer, length); HMHelpContentRec helpContent = new HMHelpContentRec (); OS.memcpy (helpContent, ioHelpContent, HMHelpContentRec.sizeof); helpContent.version = OS.kMacHelpVersion; /* * Feature in the Macintosh. Despite the fact that the Mac * provides 23 different types of alignment for the help text, * it does not allow the text to be positioned at the current * mouse position. The fix is to center the text in a rectangle * that surrounds the original position of the mouse. As the * mouse is moved, this rectangle is grown to include the new * location of the mouse. The help text is then centered by * the Mac in the new rectangle that was carefully constructed * such that the help text will stay in the same position. */ int cursorHeight = 16; helpContent.tagSide = (short) OS.kHMAbsoluteCenterAligned; int x = (short) (inGlobalMouse & 0xFFFF); int y = (short) (inGlobalMouse >> 16); if (display.helpControl != this) { display.lastHelpX = x + cursorHeight / 2; display.lastHelpY = y + cursorHeight + cursorHeight / 2; } int jitter = 4; int deltaX = Math.abs (display.lastHelpX - x) + jitter; int deltaY = Math.abs (display.lastHelpY - y) + jitter; x = display.lastHelpX - deltaX; y = display.lastHelpY - deltaY; int width = deltaX * 2; int height = deltaY * 2; display.helpControl = this; helpContent.absHotRect_left = (short) x; helpContent.absHotRect_top = (short) y; helpContent.absHotRect_right = (short) (x + width); helpContent.absHotRect_bottom = (short) (y + height); helpContent.content0_contentType = OS.kHMCFStringContent; helpContent.content0_tagCFString = display.helpString; helpContent.content1_contentType = OS.kHMCFStringContent; helpContent.content1_tagCFString = display.helpString; OS.memcpy (ioHelpContent, helpContent, HMHelpContentRec.sizeof); contentProvided [0] = OS.kHMContentProvided; } OS.memcpy (outContentProvided, contentProvided, 4); break; } case OS.kHMDisposeContent: { if (display.helpString != 0) OS.CFRelease (display.helpString); display.helpString = 0; break; } } return OS.noErr; } void hookEvents () { super.hookEvents (); int controlProc = display.controlProc; int [] mask = new int [] { OS.kEventClassControl, OS.kEventControlActivate, OS.kEventClassControl, OS.kEventControlApplyBackground, OS.kEventClassControl, OS.kEventControlBoundsChanged, OS.kEventClassControl, OS.kEventControlClick, OS.kEventClassControl, OS.kEventControlContextualMenuClick, OS.kEventClassControl, OS.kEventControlDeactivate, OS.kEventClassControl, OS.kEventControlDraw, OS.kEventClassControl, OS.kEventControlHit, OS.kEventClassControl, OS.kEventControlSetCursor, OS.kEventClassControl, OS.kEventControlSetFocusPart, OS.kEventClassControl, OS.kEventControlTrack, }; int controlTarget = OS.GetControlEventTarget (handle); OS.InstallEventHandler (controlTarget, controlProc, mask.length / 2, mask, handle, null); int helpProc = display.helpProc; OS.HMInstallControlContentCallback (handle, helpProc); int colorProc = display.colorProc; OS.SetControlColorProc (handle, colorProc); } /** * Invokes platform specific functionality to allocate a new GC handle. * <p> * <b>IMPORTANT:</b> This method is <em>not</em> part of the public * API for <code>Control</code>. It is marked public only so that it * can be shared within the packages provided by SWT. It is not * available on all platforms, and should never be called from * application code. * </p> * * @param data the platform specific GC data * @return the platform specific GC handle */ public int internal_new_GC (GCData data) { checkWidget(); int port = data != null ? data.port : 0; if (port == 0) { int window = OS.GetControlOwner (handle); port = OS.GetWindowPort (window); } int [] buffer = new int [1]; OS.CreateCGContextForPort (port, buffer); int context = buffer [0]; if (context == 0) SWT.error (SWT.ERROR_NO_HANDLES); int visibleRgn = 0; if (data != null && data.paintEvent != 0) { visibleRgn = data.visibleRgn; } else { if (getDrawCount (handle) > 0) { visibleRgn = OS.NewRgn (); } else { visibleRgn = getVisibleRegion (handle, true); } } Rect rect = new Rect (); Rect portRect = new Rect (); OS.GetControlBounds (handle, rect); OS.GetPortBounds (port, portRect); OS.ClipCGContextToRegion (context, portRect, visibleRgn); int portHeight = portRect.bottom - portRect.top; OS.CGContextScaleCTM (context, 1, -1); OS.CGContextTranslateCTM (context, rect.left, -portHeight + rect.top); if (data != null) { int mask = SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT; if ((data.style & mask) == 0) { data.style |= style & (mask | SWT.MIRRORED); } data.device = display; data.thread = display.thread; data.background = background != null ? background : defaultBackground ().handle; data.foreground = foreground != null ? foreground : defaultForeground ().handle; data.font = font != null ? font : defaultFont (); data.visibleRgn = visibleRgn; data.control = handle; data.portRect = portRect; data.controlRect = rect; if (data.paintEvent == 0) { if (gcs == null) gcs = new GCData [4]; int index = 0; while (index < gcs.length && gcs [index] != null) index++; if (index == gcs.length) { GCData [] newGCs = new GCData [gcs.length + 4]; System.arraycopy (gcs, 0, newGCs, 0, gcs.length); gcs = newGCs; } gcs [index] = data; } } return context; } /** * Invokes platform specific functionality to dispose a GC handle. * <p> * <b>IMPORTANT:</b> This method is <em>not</em> part of the public * API for <code>Control</code>. It is marked public only so that it * can be shared within the packages provided by SWT. It is not * available on all platforms, and should never be called from * application code. * </p> * * @param hDC the platform specific GC handle * @param data the platform specific GC data */ public void internal_dispose_GC (int context, GCData data) { checkWidget (); if (data != null) { if (data.paintEvent == 0) { if (data.visibleRgn != 0) { OS.DisposeRgn (data.visibleRgn); data.visibleRgn = 0; } int index = 0; while (index < gcs.length && gcs [index] != data) index++; if (index < gcs.length) { gcs [index] = null; index = 0; while (index < gcs.length && gcs [index] == null) index++; if (index == gcs.length) gcs = null; } } } /* * This code is intentionaly commented. Use CGContextSynchronize * instead of CGContextFlush to improve performance. */ // OS.CGContextFlush (context); OS.CGContextSynchronize (context); OS.CGContextRelease (context); } void invalidateChildrenVisibleRegion (int control) { } void invalidateVisibleRegion (int control) { int index = 0; Control[] siblings = parent._getChildren (); while (index < siblings.length && siblings [index] != this) index++; for (int i=index; i<siblings.length; i++) { Control sibling = siblings [i]; sibling.resetVisibleRegion (control); sibling.invalidateChildrenVisibleRegion (control); } parent.resetVisibleRegion (control); } void invalWindowRgn (int window, int rgn) { parent.invalWindowRgn (window, rgn); } /** * Returns <code>true</code> if the receiver is enabled and all * ancestors up to and including the receiver's nearest ancestor * shell are enabled. Otherwise, <code>false</code> is returned. * A disabled control is typically not selectable from the user * interface and draws with an inactive or "grayed" look. * * @return the receiver's enabled state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #getEnabled */ public boolean isEnabled () { checkWidget(); return getEnabled () && parent.isEnabled (); } boolean isEnabledCursor () { return isEnabled (); } boolean isEnabledModal () { //NOT DONE - fails for multiple APP MODAL shells Shell [] shells = display.getShells (); for (int i = 0; i < shells.length; i++) { Shell modal = shells [i]; if (modal != this && modal.isVisible ()) { if ((modal.style & SWT.PRIMARY_MODAL) != 0) { Shell shell = getShell (); if (modal.parent == shell) { return false; } } int bits = SWT.APPLICATION_MODAL | SWT.SYSTEM_MODAL; if ((modal.style & bits) != 0) { Control control = this; while (control != null) { if (control == modal) break; control = control.parent; } if (control != modal) return false; } } } return true; } boolean isFocusAncestor (Control control) { while (control != null && control != this) { control = control.parent; } return control == this; } /** * Returns <code>true</code> if the receiver has the user-interface * focus, and <code>false</code> otherwise. * * @return the receiver's focus state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean isFocusControl () { checkWidget(); return hasFocus (); } /** * Returns <code>true</code> if the underlying operating * system supports this reparenting, otherwise <code>false</code> * * @return <code>true</code> if the widget can be reparented, otherwise <code>false</code> * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean isReparentable () { checkWidget(); return false; } boolean isShowing () { /* * This is not complete. Need to check if the * widget is obscurred by a parent or sibling. */ if (!isVisible ()) return false; Control control = this; while (control != null) { Point size = control.getSize (); if (size.x == 0 || size.y == 0) { return false; } control = control.parent; } return true; } boolean isTabGroup () { Control [] tabList = parent._getTabList (); if (tabList != null) { for (int i=0; i<tabList.length; i++) { if (tabList [i] == this) return true; } } int code = traversalCode (0, 0); if ((code & (SWT.TRAVERSE_ARROW_PREVIOUS | SWT.TRAVERSE_ARROW_NEXT)) != 0) return false; return (code & (SWT.TRAVERSE_TAB_PREVIOUS | SWT.TRAVERSE_TAB_NEXT)) != 0; } boolean isTabItem () { Control [] tabList = parent._getTabList (); if (tabList != null) { for (int i=0; i<tabList.length; i++) { if (tabList [i] == this) return false; } } int code = traversalCode (0, 0); return (code & (SWT.TRAVERSE_ARROW_PREVIOUS | SWT.TRAVERSE_ARROW_NEXT)) != 0; } /** * Returns <code>true</code> if the receiver is visible and all * ancestors up to and including the receiver's nearest ancestor * shell are visible. Otherwise, <code>false</code> is returned. * * @return the receiver's visibility state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #getVisible */ public boolean isVisible () { checkWidget(); return OS.IsControlVisible (topHandle ()); } Decorations menuShell () { return parent.menuShell (); } int kEventControlContextualMenuClick (int nextHandler, int theEvent, int userData) { int sizeof = org.eclipse.swt.internal.carbon.Point.sizeof; org.eclipse.swt.internal.carbon.Point pt = new org.eclipse.swt.internal.carbon.Point (); OS.GetEventParameter (theEvent, OS.kEventParamMouseLocation, OS.typeQDPoint, null, sizeof, null, pt); Rect rect = new Rect (); int window = OS.GetControlOwner (handle); OS.GetWindowBounds (window, (short) OS.kWindowContentRgn, rect); int x = pt.h + rect.left; int y = pt.v + rect.top; Event event = new Event (); event.x = x; event.y = y; sendEvent (SWT.MenuDetect, event); if (event.doit) { if (menu != null && !menu.isDisposed ()) { if (event.x != x || event.y != y) { menu.setLocation (event.x, event.y); } menu.setVisible (true); } } return OS.eventNotHandledErr; } int kEventControlSetCursor (int nextHandler, int theEvent, int userData) { if (!isEnabledCursor ()) return OS.noErr; Cursor cursor = null; if (isEnabledModal ()) { if ((cursor = findCursor ()) != null) display.setCursor (cursor.handle); } return cursor != null ? OS.noErr : OS.eventNotHandledErr; } int kEventControlSetFocusPart (int nextHandler, int theEvent, int userData) { display.focusCombo = null; if (!display.ignoreFocus) { short [] part = new short [1]; OS.GetEventParameter (theEvent, OS.kEventParamControlPart, OS.typeControlPartCode, null, 2, null, part); sendFocusEvent (part [0] != OS.kControlFocusNoPart ? SWT.FocusIn : SWT.FocusOut, false); // widget could be disposed at this point if (isDisposed ()) return OS.noErr; } return OS.eventNotHandledErr; } int kEventControlTrack (int nextHandler, int theEvent, int userData) { // if (isEnabledModal ()) sendMouseEvent (SWT.MouseMove, theEvent); return OS.eventNotHandledErr; } int kEventMouseDown (int nextHandler, int theEvent, int userData) { Shell shell = getShell (); short [] button = new short [1]; OS.GetEventParameter (theEvent, OS.kEventParamMouseButton, OS.typeMouseButton, null, 2, null, button); int [] clickCount = new int [1]; OS.GetEventParameter (theEvent, OS.kEventParamClickCount, OS.typeUInt32, null, 4, null, clickCount); sendMouseEvent (SWT.MouseDown, button [0], 0, 0, false, theEvent); if (clickCount [0] == 2) sendMouseEvent (SWT.MouseDoubleClick, button [0], 0, 0, false, theEvent); if ((state & GRAB) != 0) display.grabControl = this; /* * It is possible that the shell may be * disposed at this point. If this happens * don't send the activate and deactivate * events. */ if (!shell.isDisposed ()) { shell.setActiveControl (this); } if (hooks (SWT.DragDetect)) { org.eclipse.swt.internal.carbon.Point pt = new org.eclipse.swt.internal.carbon.Point (); int sizeof = org.eclipse.swt.internal.carbon.Point.sizeof; OS.GetEventParameter (theEvent, OS.kEventParamMouseLocation, OS.typeQDPoint, null, sizeof, null, pt); display.dragMouseStart = pt; display.dragging = false; } return OS.eventNotHandledErr; } int kEventMouseDragged (int nextHandler, int theEvent, int userData) { if ((state & CANVAS) == 0) { if (isEnabledModal ()) sendMouseEvent (SWT.MouseMove, (short) 0, 0, 0, false, theEvent); display.dragDetect (this); } return OS.eventNotHandledErr; } int kEventMouseMoved (int nextHandler, int theEvent, int userData) { if (isEnabledModal ()) sendMouseEvent (SWT.MouseMove, (short) 0, 0, 0, false, theEvent); return OS.eventNotHandledErr; } int kEventMouseUp (int nextHandler, int theEvent, int userData) { short [] button = new short [1]; OS.GetEventParameter (theEvent, OS.kEventParamMouseButton, OS.typeMouseButton, null, 2, null, button); sendMouseEvent (SWT.MouseUp, button [0], 0, 0, false, theEvent); return OS.eventNotHandledErr; } int kEventMouseWheelMoved (int nextHandler, int theEvent, int userData) { if ((state & IGNORE_WHEEL) != 0) return OS.eventNotHandledErr; short [] wheelAxis = new short [1]; OS.GetEventParameter (theEvent, OS.kEventParamMouseWheelAxis, OS.typeMouseWheelAxis, null, 2, null, wheelAxis); int [] wheelDelta = new int [1]; OS.GetEventParameter (theEvent, OS.kEventParamMouseWheelDelta, OS.typeSInt32, null, 4, null, wheelDelta); Shell shell = getShell (); Control control = this; while (control != null) { if (!control.sendMouseEvent (SWT.MouseWheel, (short) 0, wheelDelta [0], SWT.SCROLL_LINE, true, theEvent)) { break; } if (control.sendMouseWheel (wheelAxis [0], wheelDelta [0])) { break; } if (control == this) { /* * Feature in the Macintosh. For some reason, the kEventMouseWheelMoved * event is sent twice to each application handler with the same mouse wheel * data. The fix is to set an ignore flag before calling the next handler * in the handler chain. */ state |= IGNORE_WHEEL; int result = OS.CallNextEventHandler(nextHandler, theEvent); state &= ~IGNORE_WHEEL; if (result == OS.noErr) break; } if (control == shell) break; control = control.parent; } return OS.noErr; } int kEventTextInputUnicodeForKeyEvent (int nextHandler, int theEvent, int userData) { int [] keyboardEvent = new int [1]; OS.GetEventParameter (theEvent, OS.kEventParamTextInputSendKeyboardEvent, OS.typeEventRef, null, keyboardEvent.length * 4, null, keyboardEvent); int [] keyCode = new int [1]; OS.GetEventParameter (keyboardEvent [0], OS.kEventParamKeyCode, OS.typeUInt32, null, keyCode.length * 4, null, keyCode); if (translateTraversal (keyCode [0], keyboardEvent [0])) return OS.noErr; if (keyCode [0] == 114) { /* Help */ Control control = this; while (control != null) { if (control.hooks (SWT.Help)) { control.postEvent (SWT.Help); break; } control = control.parent; } } if (!sendKeyEvent (SWT.KeyDown, keyboardEvent [0])) return OS.noErr; return OS.eventNotHandledErr; } void markLayout (boolean changed, boolean all) { /* Do nothing */ } /** * Moves the receiver above the specified control in the * drawing order. If the argument is null, then the receiver * is moved to the top of the drawing order. The control at * the top of the drawing order will not be covered by other * controls even if they occupy intersecting areas. * * @param control the sibling control (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the control has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Control#moveBelow * @see Composite#getChildren */ public void moveAbove (Control control) { checkWidget(); if (control != null) { if (control.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); if (parent != control.parent) return; } setZOrder (control, true); } /** * Moves the receiver below the specified control in the * drawing order. If the argument is null, then the receiver * is moved to the bottom of the drawing order. The control at * the bottom of the drawing order will be covered by all other * controls which occupy intersecting areas. * * @param control the sibling control (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the control has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Control#moveAbove * @see Composite#getChildren */ public void moveBelow (Control control) { checkWidget(); if (control != null) { if (control.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); if (parent != control.parent) return; } setZOrder (control, false); } /** * Causes the receiver to be resized to its preferred size. * For a composite, this involves computing the preferred size * from its layout, if there is one. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #computeSize */ public void pack () { checkWidget(); pack (true); } /** * Causes the receiver to be resized to its preferred size. * For a composite, this involves computing the preferred size * from its layout, if there is one. * <p> * If the changed flag is <code>true</code>, it indicates that the receiver's * <em>contents</em> have changed, therefore any caches that a layout manager * containing the control may have been keeping need to be flushed. When the * control is resized, the changed flag will be <code>false</code>, so layout * manager caches can be retained. * </p> * * @param changed whether or not the receiver's contents have changed * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #computeSize */ public void pack (boolean changed) { checkWidget(); setSize (computeSize (SWT.DEFAULT, SWT.DEFAULT, changed)); } /** * Causes the entire bounds of the receiver to be marked * as needing to be redrawn. The next time a paint request * is processed, the control will be completely painted, * including the background. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #update * @see PaintListener * @see SWT#Paint * @see SWT#NO_BACKGROUND * @see SWT#NO_REDRAW_RESIZE * @see SWT#NO_MERGE_PAINTS */ public void redraw () { checkWidget(); redrawWidget (handle, false); } /** * Causes the rectangular area of the receiver specified by * the arguments to be marked as needing to be redrawn. * The next time a paint request is processed, that area of * the receiver will be painted, including the background. * If the <code>all</code> flag is <code>true</code>, any * children of the receiver which intersect with the specified * area will also paint their intersecting areas. If the * <code>all</code> flag is <code>false</code>, the children * will not be painted. * * @param x the x coordinate of the area to draw * @param y the y coordinate of the area to draw * @param width the width of the area to draw * @param height the height of the area to draw * @param all <code>true</code> if children should redraw, and <code>false</code> otherwise * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #update * @see PaintListener * @see SWT#Paint * @see SWT#NO_BACKGROUND * @see SWT#NO_REDRAW_RESIZE * @see SWT#NO_MERGE_PAINTS */ public void redraw (int x, int y, int width, int height, boolean all) { checkWidget (); redrawWidget (handle, x, y, width, height, all); } void register () { super.register (); display.addWidget (handle, this); } void releaseChild () { setVisible (topHandle (), false); parent.removeControl (this); } void releaseHandle () { super.releaseHandle (); handle = 0; } void releaseWidget () { super.releaseWidget (); if (menu != null && !menu.isDisposed ()) { menu.dispose (); } if (visibleRgn != 0) OS.DisposeRgn (visibleRgn); visibleRgn = 0; menu = null; parent = null; layoutData = null; } /** * Removes the listener from the collection of listeners who will * be notified when the control is moved or resized. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see ControlListener * @see #addControlListener */ public void removeControlListener (ControlListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.Move, listener); eventTable.unhook (SWT.Resize, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the control gains or loses focus. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see FocusListener * @see #addFocusListener */ public void removeFocusListener(FocusListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook(SWT.FocusIn, listener); eventTable.unhook(SWT.FocusOut, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the help events are generated for the control. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see HelpListener * @see #addHelpListener */ public void removeHelpListener (HelpListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.Help, listener); } /** * Removes the listener from the collection of listeners who will * be notified when keys are pressed and released on the system keyboard. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see KeyListener * @see #addKeyListener */ public void removeKeyListener(KeyListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook(SWT.KeyUp, listener); eventTable.unhook(SWT.KeyDown, listener); } /** * Removes the listener from the collection of listeners who will * be notified when mouse buttons are pressed and released. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseListener * @see #addMouseListener */ public void removeMouseListener(MouseListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook(SWT.MouseDown, listener); eventTable.unhook(SWT.MouseUp, listener); eventTable.unhook(SWT.MouseDoubleClick, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the mouse moves. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseMoveListener * @see #addMouseMoveListener */ public void removeMouseMoveListener(MouseMoveListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook(SWT.MouseMove, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the mouse passes or hovers over controls. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseTrackListener * @see #addMouseTrackListener */ public void removeMouseTrackListener(MouseTrackListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.MouseEnter, listener); eventTable.unhook (SWT.MouseExit, listener); eventTable.unhook (SWT.MouseHover, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the receiver needs to be painted. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see PaintListener * @see #addPaintListener */ public void removePaintListener(PaintListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook(SWT.Paint, listener); } /** * Removes the listener from the collection of listeners who will * be notified when traversal events occur. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see TraverseListener * @see #addTraverseListener */ public void removeTraverseListener(TraverseListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.Traverse, listener); } void resetVisibleRegion (int control) { if (visibleRgn != 0) { OS.DisposeRgn (visibleRgn); visibleRgn = 0; } if (gcs != null) { int visibleRgn = getVisibleRegion (handle, true); for (int i=0; i<gcs.length; i++) { GCData data = gcs [i]; if (data != null) { data.updateClip = true; OS.CopyRgn (visibleRgn, data.visibleRgn); } } OS.DisposeRgn (visibleRgn); } } void sendFocusEvent (int type, boolean post) { Display display = this.display; Shell shell = getShell (); /* * Feature in the Macintosh. GetKeyboardFocus() returns NULL during * kEventControlSetFocusPart if the focus part is not kControlFocusNoPart. * The fix is to remember the focus control and return it during * kEventControlSetFocusPart. */ display.focusControl = this; display.focusEvent = type; if (post) { postEvent (type); } else { sendEvent (type); } /* * It is possible that the shell may be * disposed at this point. If this happens * don't send the activate and deactivate * events. */ if (!shell.isDisposed ()) { switch (type) { case SWT.FocusIn: shell.setActiveControl (this); break; case SWT.FocusOut: if (shell != display.getActiveShell ()) { shell.setActiveControl (null); } break; } } display.focusEvent = SWT.None; display.focusControl = null; } boolean sendMouseEvent (int type, short button, int count, int detail, boolean send, int theEvent) { if (!hooks (type) && !filters (type)) return true; int sizeof = org.eclipse.swt.internal.carbon.Point.sizeof; org.eclipse.swt.internal.carbon.Point pt = new org.eclipse.swt.internal.carbon.Point (); OS.GetEventParameter (theEvent, OS.kEventParamMouseLocation, OS.typeQDPoint, null, sizeof, null, pt); Rect rect = new Rect (); int window = OS.GetControlOwner (handle); OS.GetWindowBounds (window, (short) OS.kWindowContentRgn, rect); int x = pt.h - rect.left; int y = pt.v - rect.top; OS.GetControlBounds (handle, rect); x -= rect.left; y -= rect.top; int [] chord = new int [1]; OS.GetEventParameter (theEvent, OS.kEventParamMouseChord, OS.typeUInt32, null, 4, null, chord); int [] modifiers = new int [1]; OS.GetEventParameter (theEvent, OS.kEventParamKeyModifiers, OS.typeUInt32, null, 4, null, modifiers); return sendMouseEvent (type, button, count, detail, chord [0], (short) x, (short) y, modifiers [0], send); } boolean sendMouseEvent (int type, short button, int chord, short x, short y, int modifiers, boolean send) { if (!hooks (type) && !filters (type)) return true; return sendMouseEvent (type, button, 0, 0, chord, x, y, modifiers, send); } boolean sendMouseEvent (int type, short button, int count, int detail, int chord, short x, short y, int modifiers, boolean send) { Event event = new Event (); switch (button) { case 1: event.button = 1; break; case 2: event.button = 3; break; case 3: event.button = 2; break; case 4: event.button = 4; break; case 5: event.button = 5; break; } event.x = x; event.y = y; event.count = count; event.detail = detail; setInputState (event, type, chord, modifiers); sendEvent (type, event, send); return event.doit; } boolean sendMouseWheel (short wheelAxis, int wheelDelta) { return false; } /** * Sets the receiver's background color to the color specified * by the argument, or to the default system color for the control * if the argument is null. * * @param color the new color (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setBackground (Color color) { checkWidget(); if (color != null) { if (color.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); } background = color != null ? color.handle : null; setBackground (background); redrawWidget (handle, false); } void setBackground (float [] color) { setBackground (handle, color); } void setBackground (int control, float [] color) { ControlFontStyleRec fontStyle = new ControlFontStyleRec (); OS.GetControlData (control, (short) OS.kControlEntireControl, OS.kControlFontStyleTag, ControlFontStyleRec.sizeof, fontStyle, null); if (color != null) { fontStyle.backColor_red = (short) (color [0] * 0xffff); fontStyle.backColor_green = (short) (color [1] * 0xffff); fontStyle.backColor_blue = (short) (color [2] * 0xffff); fontStyle.flags |= OS.kControlUseBackColorMask; } else { fontStyle.flags &= ~OS.kControlUseBackColorMask; } OS.SetControlFontStyle (control, fontStyle); } /** * Sets the receiver's size and location to the rectangular * area specified by the arguments. The <code>x</code> and * <code>y</code> arguments are relative to the receiver's * parent (or its display if its parent is null), unless * the receiver is a shell. In this case, the <code>x</code> * and <code>y</code> arguments are relative to the display. * <p> * Note: Attempting to set the width or height of the * receiver to a negative number will cause that * value to be set to zero instead. * </p> * * @param x the new x coordinate for the receiver * @param y the new y coordinate for the receiver * @param width the new width for the receiver * @param height the new height for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setBounds (int x, int y, int width, int height) { checkWidget(); setBounds (x, y, Math.max (0, width), Math.max (0, height), true, true, true); } int setBounds (int x, int y, int width, int height, boolean move, boolean resize, boolean events) { return setBounds (topHandle (), x, y, width, height, move, resize, events); } /** * Sets the receiver's size and location to the rectangular * area specified by the argument. The <code>x</code> and * <code>y</code> fields of the rectangle are relative to * the receiver's parent (or its display if its parent is null). * <p> * Note: Attempting to set the width or height of the * receiver to a negative number will cause that * value to be set to zero instead. * </p> * * @param rect the new bounds for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setBounds (Rectangle rect) { if (rect == null) error (SWT.ERROR_NULL_ARGUMENT); setBounds (rect.x, rect.y, rect.width, rect.height); } /** * If the argument is <code>true</code>, causes the receiver to have * all mouse events delivered to it until the method is called with * <code>false</code> as the argument. * * @param capture <code>true</code> to capture the mouse, and <code>false</code> to release it * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setCapture (boolean capture) { checkWidget(); } /** * Sets the receiver's cursor to the cursor specified by the * argument, or to the default cursor for that kind of control * if the argument is null. * <p> * When the mouse pointer passes over a control its appearance * is changed to match the control's cursor. * </p> * * @param cursor the new cursor (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setCursor (Cursor cursor) { checkWidget(); if (cursor != null && cursor.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); this.cursor = cursor; if (!isEnabled ()) return; org.eclipse.swt.internal.carbon.Point where = new org.eclipse.swt.internal.carbon.Point (); OS.GetGlobalMouse (where); int [] theWindow = new int [1]; if (display.grabControl == this) { theWindow [0] = OS.GetControlOwner (handle); } else { if (OS.FindWindow (where, theWindow) != OS.inContent) return; if (theWindow [0] == 0) return; } Rect rect = new Rect (); OS.GetWindowBounds (theWindow [0], (short) OS.kWindowContentRgn, rect); int [] theControl = new int [1]; if (display.grabControl == this) { theControl [0] = handle; } else { CGPoint inPoint = new CGPoint (); inPoint.x = where.h - rect.left; inPoint.y = where.v - rect.top; int [] theRoot = new int [1]; OS.GetRootControl (theWindow [0], theRoot); OS.HIViewGetSubviewHit (theRoot [0], inPoint, true, theControl); int cursorControl = theControl [0]; while (theControl [0] != 0 && theControl [0] != handle) { OS.GetSuperControl (theControl [0], theControl); } if (theControl [0] == 0) return; theControl [0] = cursorControl; do { Widget widget = display.getWidget (theControl [0]); if (widget != null) { if (widget instanceof Control) { Control control = (Control) widget; if (control.isEnabled ()) break; } } OS.GetSuperControl (theControl [0], theControl); } while (theControl [0] != 0); if (theControl [0] == 0) { theControl [0] = theRoot [0]; Widget widget = display.getWidget (theControl [0]); if (widget != null && widget instanceof Control) { Control control = (Control) widget; theControl [0] = control.handle; } } } where.h -= rect.left; where.v -= rect.top; int modifiers = OS.GetCurrentEventKeyModifiers (); boolean [] cursorWasSet = new boolean [1]; OS.HandleControlSetCursor (theControl [0], where, (short) modifiers, cursorWasSet); if (!cursorWasSet [0]) OS.SetThemeCursor (OS.kThemeArrowCursor); } void setDefaultFont () { if (display.smallFonts) setFontStyle (defaultFont ()); } /** * Enables the receiver if the argument is <code>true</code>, * and disables it otherwise. A disabled control is typically * not selectable from the user interface and draws with an * inactive or "grayed" look. * * @param enabled the new enabled state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setEnabled (boolean enabled) { checkWidget(); if (((state & DISABLED) == 0) == enabled) return; Control control = null; boolean fixFocus = false; if (!enabled) { if (display.focusEvent != SWT.FocusOut) { control = display.getFocusControl (); fixFocus = isFocusAncestor (control); } } if (enabled) { state &= ~DISABLED; } else { state |= DISABLED; } enableWidget (enabled); if (fixFocus) fixFocus (control); } /** * Causes the receiver to have the <em>keyboard focus</em>, * such that all keyboard events will be delivered to it. Focus * reassignment will respect applicable platform constraints. * * @return <code>true</code> if the control got focus, and <code>false</code> if it was unable to. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #forceFocus */ public boolean setFocus () { checkWidget(); if ((style & SWT.NO_FOCUS) != 0) return false; return forceFocus (); } /** * Sets the font that the receiver will use to paint textual information * to the font specified by the argument, or to the default font for that * kind of control if the argument is null. * * @param font the new font (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setFont (Font font) { checkWidget(); if (font != null) { if (font.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); } this.font = font; setFontStyle (display.smallFonts ? (font != null ? font : defaultFont ()) : font); redrawWidget (handle, false); } void setFontStyle (Font font) { setFontStyle (handle, font); } void setFontStyle (int control, Font font) { ControlFontStyleRec fontStyle = new ControlFontStyleRec (); OS.GetControlData (control, (short) OS.kControlEntireControl, OS.kControlFontStyleTag, ControlFontStyleRec.sizeof, fontStyle, null); fontStyle.flags &= ~(OS.kControlUseFontMask | OS.kControlUseSizeMask | OS.kControlUseFaceMask | OS.kControlUseThemeFontIDMask); if (font != null) { fontStyle.flags |= OS.kControlUseFontMask | OS.kControlUseSizeMask | OS.kControlUseFaceMask; fontStyle.font = font.id; fontStyle.style = font.style; fontStyle.size = font.size; } OS.SetControlFontStyle (control, fontStyle); } /** * Sets the receiver's foreground color to the color specified * by the argument, or to the default system color for the control * if the argument is null. * * @param color the new color (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setForeground (Color color) { checkWidget(); if (color != null) { if (color.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); } foreground = color != null ? color.handle : null; setForeground (foreground); redrawWidget (handle, false); } void setForeground (float [] color) { setForeground (handle, color); } void setForeground (int control, float [] color) { ControlFontStyleRec fontStyle = new ControlFontStyleRec (); OS.GetControlData (control, (short) OS.kControlEntireControl, OS.kControlFontStyleTag, ControlFontStyleRec.sizeof, fontStyle, null); if (color != null) { fontStyle.foreColor_red = (short) (color [0] * 0xffff); fontStyle.foreColor_green = (short) (color [1] * 0xffff); fontStyle.foreColor_blue = (short) (color [2] * 0xffff); fontStyle.flags |= OS.kControlUseForeColorMask; } else { fontStyle.flags &= ~OS.kControlUseForeColorMask; } OS.SetControlFontStyle (control, fontStyle); } /** * Sets the layout data associated with the receiver to the argument. * * @param layoutData the new layout data for the receiver. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setLayoutData (Object layoutData) { checkWidget(); this.layoutData = layoutData; } /** * Sets the receiver's location to the point specified by * the arguments which are relative to the receiver's * parent (or its display if its parent is null), unless * the receiver is a shell. In this case, the point is * relative to the display. * * @param x the new x coordinate for the receiver * @param y the new y coordinate for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setLocation (int x, int y) { checkWidget(); setBounds (x, y, 0, 0, true, false, true); } /** * Sets the receiver's location to the point specified by * the arguments which are relative to the receiver's * parent (or its display if its parent is null), unless * the receiver is a shell. In this case, the point is * relative to the display. * * @param location the new location for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setLocation (Point location) { if (location == null) error (SWT.ERROR_NULL_ARGUMENT); setLocation (location.x, location.y); } /** * Sets the receiver's pop up menu to the argument. * All controls may optionally have a pop up * menu that is displayed when the user requests one for * the control. The sequence of key strokes, button presses * and/or button releases that are used to request a pop up * menu is platform specific. * * @param menu the new pop up menu * * @exception IllegalArgumentException <ul> * <li>ERROR_MENU_NOT_POP_UP - the menu is not a pop up menu</li> * <li>ERROR_INVALID_PARENT - if the menu is not in the same widget tree</li> * <li>ERROR_INVALID_ARGUMENT - if the menu has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setMenu (Menu menu) { checkWidget(); if (menu != null) { if (menu.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); if ((menu.style & SWT.POP_UP) == 0) { error (SWT.ERROR_MENU_NOT_POP_UP); } if (menu.parent != menuShell ()) { error (SWT.ERROR_INVALID_PARENT); } } this.menu = menu; } /** * Changes the parent of the widget to be the one provided if * the underlying operating system supports this feature. * Answers <code>true</code> if the parent is successfully changed. * * @param parent the new parent for the control. * @return <code>true</code> if the parent is changed and <code>false</code> otherwise. * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean setParent (Composite parent) { checkWidget(); if (parent.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); return false; } /** * If the argument is <code>false</code>, causes subsequent drawing * operations in the receiver to be ignored. No drawing of any kind * can occur in the receiver until the flag is set to true. * Graphics operations that occurred while the flag was * <code>false</code> are lost. When the flag is set to <code>true</code>, * the entire widget is marked as needing to be redrawn. Nested calls * to this method are stacked. * <p> * Note: This operation is a hint and may not be supported on some * platforms or for some widgets. * </p> * * @param redraw the new redraw state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #redraw * @see #update */ public void setRedraw (boolean redraw) { checkWidget(); if (redraw) { if (--drawCount == 0) { invalidateVisibleRegion (handle); redrawWidget (handle, true); } } else { if (drawCount == 0) { invalidateVisibleRegion (handle); } drawCount++; } } boolean setRadioSelection (boolean value){ return false; } /** * Sets the receiver's size to the point specified by the arguments. * <p> * Note: Attempting to set the width or height of the * receiver to a negative number will cause that * value to be set to zero instead. * </p> * * @param width the new width for the receiver * @param height the new height for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setSize (int width, int height) { checkWidget(); setBounds (0, 0, Math.max (0, width), Math.max (0, height), false, true, true); } /** * Sets the receiver's size to the point specified by the argument. * <p> * Note: Attempting to set the width or height of the * receiver to a negative number will cause them to be * set to zero instead. * </p> * * @param size the new size for the receiver * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setSize (Point size) { if (size == null) error (SWT.ERROR_NULL_ARGUMENT); setSize (size.x, size.y); } boolean setTabGroupFocus () { return setTabItemFocus (); } boolean setTabItemFocus () { if (!isShowing ()) return false; return forceFocus (); } /** * Sets the receiver's tool tip text to the argument, which * may be null indicating that no tool tip text should be shown. * * @param string the new tool tip text (or null) * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setToolTipText (String string) { checkWidget(); toolTipText = string; } /** * Marks the receiver as visible if the argument is <code>true</code>, * and marks it invisible otherwise. * <p> * If one of the receiver's ancestors is not visible or some * other condition makes the receiver not visible, marking * it visible may not actually cause it to be displayed. * </p> * * @param visible the new visibility state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setVisible (boolean visible) { checkWidget(); if (visible) { if ((state & HIDDEN) == 0) return; state &= ~HIDDEN; } else { if ((state & HIDDEN) != 0) return; state |= HIDDEN; } if (visible) { /* * It is possible (but unlikely), that application * code could have disposed the widget in the show * event. If this happens, just return. */ sendEvent (SWT.Show); if (isDisposed ()) return; } /* * Feature in the Macintosh. If the receiver has focus, hiding * the receiver causes no control to have focus. Also, the focus * needs to be cleared from any TXNObject so that it stops blinking * the caret. The fix is to assign focus to the first ancestor * control that takes focus. If no control will take focus, clear * the focus control. */ Control control = null; boolean fixFocus = false; if (!visible) { if (display.focusEvent != SWT.FocusOut) { control = display.getFocusControl (); fixFocus = isFocusAncestor (control); } } setVisible (topHandle (), visible); if (!visible) { /* * It is possible (but unlikely), that application * code could have disposed the widget in the show * event. If this happens, just return. */ sendEvent (SWT.Hide); if (isDisposed ()) return; } if (fixFocus) fixFocus (control); } void setZOrder () { int topHandle = topHandle (); int parentHandle = parent.handle; OS.HIViewAddSubview (parentHandle, topHandle); //OS.EmbedControl (topHandle, parentHandle); /* Place the child at (0, 0) in the parent */ Rect parentRect = new Rect (); OS.GetControlBounds (parentHandle, parentRect); Rect inset = getInset (); Rect newBounds = new Rect (); newBounds.left = (short) (parentRect.left + inset.left); newBounds.top = (short) (parentRect.top + inset.top); newBounds.right = (short) (newBounds.left - inset.right - inset.left); newBounds.bottom = (short) (newBounds.top - inset.bottom - inset.top); if (newBounds.bottom < newBounds.top) newBounds.bottom = newBounds.top; if (newBounds.right < newBounds.left) newBounds.right = newBounds.left; OS.SetControlBounds (topHandle, newBounds); } void setZOrder (Control control, boolean above) { int otherControl = control == null ? 0 : control.topHandle (); setZOrder (topHandle (), otherControl, above); } void sort (int [] items) { /* Shell Sort from K&R, pg 108 */ int length = items.length; for (int gap=length/2; gap>0; gap/=2) { for (int i=gap; i<length; i++) { for (int j=i-gap; j>=0; j-=gap) { if (items [j] <= items [j + gap]) { int swap = items [j]; items [j] = items [j + gap]; items [j + gap] = swap; } } } } } /** * Returns a point which is the result of converting the * argument, which is specified in display relative coordinates, * to coordinates relative to the receiver. * <p> * @param x the x coordinate to be translated * @param y the y coordinate to be translated * @return the translated coordinates * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 2.1 */ public Point toControl (int x, int y) { checkWidget(); Rect rect = new Rect (); int window = OS.GetControlOwner (handle); OS.GetWindowBounds (window, (short) OS.kWindowContentRgn, rect); x -= rect.left; y -= rect.top; OS.GetControlBounds (handle, rect); return new Point (x - rect.left, y - rect.top); } /** * Returns a point which is the result of converting the * argument, which is specified in display relative coordinates, * to coordinates relative to the receiver. * <p> * @param point the point to be translated (must not be null) * @return the translated coordinates * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Point toControl (Point point) { checkWidget(); if (point == null) error (SWT.ERROR_NULL_ARGUMENT); return toControl (point.x, point.y); } /** * Returns a point which is the result of converting the * argument, which is specified in coordinates relative to * the receiver, to display relative coordinates. * <p> * @param x the x coordinate to be translated * @param y the y coordinate to be translated * @return the translated coordinates * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 2.1 */ public Point toDisplay (int x, int y) { checkWidget(); Rect rect = new Rect (); OS.GetControlBounds (handle, rect); x += rect.left; y += rect.top; int window = OS.GetControlOwner (handle); OS.GetWindowBounds (window, (short) OS.kWindowContentRgn, rect); return new Point (x + rect.left, y + rect.top); } /** * Returns a point which is the result of converting the * argument, which is specified in coordinates relative to * the receiver, to display relative coordinates. * <p> * @param point the point to be translated (must not be null) * @return the translated coordinates * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Point toDisplay (Point point) { checkWidget(); if (point == null) error (SWT.ERROR_NULL_ARGUMENT); return toDisplay (point.x, point.y); } int topHandle () { return handle; } boolean translateTraversal (int key, int theEvent) { int detail = SWT.TRAVERSE_NONE; int code = traversalCode (key, theEvent); boolean all = false; switch (key) { case 53: /* Esc */ { all = true; detail = SWT.TRAVERSE_ESCAPE; break; } case 36: /* Return */ { all = true; detail = SWT.TRAVERSE_RETURN; break; } case 48: /* Tab */ { int [] modifiers = new int [1]; OS.GetEventParameter (theEvent, OS.kEventParamKeyModifiers, OS.typeUInt32, null, 4, null, modifiers); boolean next = (modifiers [0] & OS.shiftKey) == 0; detail = next ? SWT.TRAVERSE_TAB_NEXT : SWT.TRAVERSE_TAB_PREVIOUS; break; } case 126: /* Up arrow */ case 123: /* Left arrow */ case 125: /* Down arrow */ case 124: /* Right arrow */ { boolean next = key == 125 /* Down arrow */ || key == 124 /* Right arrow */; detail = next ? SWT.TRAVERSE_ARROW_NEXT : SWT.TRAVERSE_ARROW_PREVIOUS; break; } case 116: /* Page up */ case 121: /* Page down */ { all = true; int [] modifiers = new int [1]; OS.GetEventParameter (theEvent, OS.kEventParamKeyModifiers, OS.typeUInt32, null, 4, null, modifiers); if ((modifiers [0] & OS.controlKey) == 0) return false; detail = key == 121 /* Page down */ ? SWT.TRAVERSE_PAGE_NEXT : SWT.TRAVERSE_PAGE_PREVIOUS; break; } default: return false; } Event event = new Event (); event.doit = (code & detail) != 0; event.detail = detail; if (!setKeyState (event, SWT.Traverse, theEvent)) return false; Shell shell = getShell (); Control control = this; do { if (control.traverse (event)) return true; if (!event.doit && control.hooks (SWT.Traverse)) { return false; } if (control == shell) return false; control = control.parent; } while (all && control != null); return false; } int traversalCode (int key, int theEvent) { int code = SWT.TRAVERSE_RETURN | SWT.TRAVERSE_TAB_NEXT | SWT.TRAVERSE_TAB_PREVIOUS; Shell shell = getShell (); if (shell.parent != null) code |= SWT.TRAVERSE_ESCAPE; return code; } boolean traverseMnemonic (char key) { return false; } /** * Based on the argument, perform one of the expected platform * traversal action. The argument should be one of the constants: * <code>SWT.TRAVERSE_ESCAPE</code>, <code>SWT.TRAVERSE_RETURN</code>, * <code>SWT.TRAVERSE_TAB_NEXT</code>, <code>SWT.TRAVERSE_TAB_PREVIOUS</code>, * <code>SWT.TRAVERSE_ARROW_NEXT</code> and <code>SWT.TRAVERSE_ARROW_PREVIOUS</code>. * * @param traversal the type of traversal * @return true if the traversal succeeded * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean traverse (int traversal) { checkWidget(); Event event = new Event (); event.doit = true; event.detail = traversal; return traverse (event); } boolean traverse (Event event) { sendEvent (SWT.Traverse, event); if (isDisposed ()) return true; if (!event.doit) return false; switch (event.detail) { case SWT.TRAVERSE_NONE: return true; case SWT.TRAVERSE_ESCAPE: return traverseEscape (); case SWT.TRAVERSE_RETURN: return traverseReturn (); case SWT.TRAVERSE_TAB_NEXT: return traverseGroup (true); case SWT.TRAVERSE_TAB_PREVIOUS: return traverseGroup (false); case SWT.TRAVERSE_ARROW_NEXT: return traverseItem (true); case SWT.TRAVERSE_ARROW_PREVIOUS: return traverseItem (false); case SWT.TRAVERSE_MNEMONIC: return traverseMnemonic (event); case SWT.TRAVERSE_PAGE_NEXT: return traversePage (true); case SWT.TRAVERSE_PAGE_PREVIOUS: return traversePage (false); } return false; } boolean traverseEscape () { return false; } boolean traverseGroup (boolean next) { Control root = computeTabRoot (); Control group = computeTabGroup (); Control [] list = root.computeTabList (); int length = list.length; int index = 0; while (index < length) { if (list [index] == group) break; index++; } /* * It is possible (but unlikely), that application * code could have disposed the widget in focus in * or out events. Ensure that a disposed widget is * not accessed. */ if (index == length) return false; int start = index, offset = (next) ? 1 : -1; while ((index = ((index + offset + length) % length)) != start) { Control control = list [index]; if (!control.isDisposed () && control.setTabGroupFocus ()) { return true; } } if (group.isDisposed ()) return false; return group.setTabGroupFocus (); } boolean traverseItem (boolean next) { Control [] children = parent._getChildren (); int length = children.length; int index = 0; while (index < length) { if (children [index] == this) break; index++; } /* * It is possible (but unlikely), that application * code could have disposed the widget in focus in * or out events. Ensure that a disposed widget is * not accessed. */ if (index == length) return false; int start = index, offset = (next) ? 1 : -1; while ((index = (index + offset + length) % length) != start) { Control child = children [index]; if (!child.isDisposed () && child.isTabItem ()) { if (child.setTabItemFocus ()) return true; } } return false; } boolean traverseReturn () { return false; } boolean traversePage (boolean next) { return false; } boolean traverseMnemonic (Event event) { return false; } /** * Forces all outstanding paint requests for the widget * to be processed before this method returns. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #redraw * @see PaintListener * @see SWT#Paint */ public void update () { checkWidget(); update (false); } void update (boolean all) { // checkWidget(); if (!isDrawing (handle)) return; int window = OS.GetControlOwner (handle); int port = OS.GetWindowPort (window); int portRgn = OS.NewRgn (); OS.GetPortVisibleRegion (port, portRgn); if (!OS.EmptyRgn (portRgn)) { int updateRgn = OS.NewRgn (); OS.GetWindowRegion (window, (short)OS.kWindowUpdateRgn, updateRgn); if (!OS.EmptyRgn (updateRgn)) { Rect rect = new Rect (); OS.GetWindowBounds (window, (short) OS.kWindowContentRgn, rect); OS.OffsetRgn (updateRgn, (short)-rect.left, (short)-rect.top); OS.SectRgn (portRgn, updateRgn, updateRgn); if (!OS.EmptyRgn (updateRgn)) { int visibleRgn = getVisibleRegion (handle, !all); if (!OS.EmptyRgn (visibleRgn)) { OS.SectRgn (updateRgn, visibleRgn, visibleRgn); if (!OS.EmptyRgn (visibleRgn)) { int [] currentPort = new int[1]; OS.GetPort (currentPort); OS.SetPort (port); OS.BeginUpdate (window); OS.DiffRgn (updateRgn, visibleRgn, updateRgn); invalWindowRgn (window, updateRgn); OS.UpdateControls (window, visibleRgn); OS.EndUpdate (window); OS.SetPort (currentPort [0]); } } OS.DisposeRgn (visibleRgn); } } OS.DisposeRgn (updateRgn); } OS.DisposeRgn (portRgn); } void updateLayout (boolean all) { /* Do nothing */ } }
[ "375833274@qq.com" ]
375833274@qq.com
5a74f318c93a5963bd4b176c34ded9d2276a86ba
6ef038fbe1b8888f995860b34b214fa14fd21b63
/src/com/byer/neuralnetcheckers/main/TestAndGraphCheckersNet.java
3cd9e5588d70755c651c25182229ad431174c717
[]
no_license
duanebyer/NeuralNetCheckers
4931d4cc126bbb1de78b22990dd07a62e3bbe482
83200c68e1f88d82d7ac1cae9dd825c8eed74f7d
refs/heads/master
2021-01-19T00:18:48.275076
2015-07-06T13:59:55
2015-07-06T13:59:55
38,271,956
0
0
null
null
null
null
UTF-8
Java
false
false
7,039
java
package com.byer.neuralnetcheckers.main; import com.asemahle.neuralnet.NeuralNet; import com.byer.checkers.Game; import com.byer.checkers.HumanPlayer; import com.byer.checkers.StupidCheckersPlayer; import com.byer.neuralnetcheckers.Function; import com.byer.neuralnetcheckers.NeuralNetPlayer; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; /** * * @author Duane Byer */ public class TestAndGraphCheckersNet { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); System.out.println("Enter the filename (for saving the collected data):"); String filename = scanner.nextLine(); System.out.println("Enter the number of the first generation to be tested:"); int startGen = scanner.nextInt(); System.out.println("Enter the number of the final generation to be tested:"); int endGen = scanner.nextInt(); System.out.println("Enter the number of generations to increment between tests:"); int increment = scanner.nextInt(); System.out.println("Enter the number of games each generation winner should play against the stupidBot:"); int numGames = scanner.nextInt(); scanner.close(); JFrame frame = new JFrame("Graphs"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel lbl = new JLabel(); frame.getContentPane().add(lbl, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); ArrayList<Double> winsVSLosses = new ArrayList<Double>(); NeuralNetPlayer netPlayer = null; for (int i = startGen; i <= endGen; i += increment){ String fileName = "generation" + i + ".nn"; NeuralNet[] nets = null; while (true) { try { nets = NeuralNet.loadFromFile(fileName, EvolveCheckersNet.ACTIVATION_FUNCTION); break; } catch(IOException e) {/*Wait for the file to be created*/ } catch(IndexOutOfBoundsException e) {/*This error happens sometimes but it's okay*/ } } int netNumber = 0; int stupidBotWins = 0; int neuralBotWins = 0; netPlayer = new NeuralNetPlayer(nets[netNumber]); for (int j = 0; j < numGames; j++) { Game game = new Game(new StupidCheckersPlayer(), netPlayer, EvolveCheckersNet.TURN_LIMIT); while (true) { //game.getBoard().print(new PrintWriter(System.out)); Game.Status result = game.takeNextTurn(); if (result == Game.Status.BlackWin) { //System.out.println("Neural net wins!"); neuralBotWins += 1; break; } if (result == Game.Status.WhiteWin) { //System.out.println("Human wins!"); stupidBotWins += 1; break; } if (result == Game.Status.Tie) { //System.out.println("Tie!"); break; } } } System.out.println("Generation" + i + ".nn | Neural: " + neuralBotWins + " | Random: " + stupidBotWins + " | N/R = " + (double)neuralBotWins/(double)stupidBotWins); winsVSLosses.add((double)neuralBotWins/(double)stupidBotWins); lbl.setIcon(draw(winsVSLosses, lbl.getWidth(), lbl.getHeight())); outputToFile(filename, winsVSLosses); } System.out.println("DONE!"); } public static void outputToFile(String filename, List<Double> winsVSLosses) throws UnsupportedEncodingException, FileNotFoundException, IOException { //output winsVSLosses to file try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("filename.txt"), "utf-8"))) { writer.write("POPULATION_SIZE = " + EvolveCheckersNet.POPULATION_SIZE); writer.write("NUM_HIDDEN_LAYERS = " + EvolveCheckersNet.NUM_HIDDEN_LAYERS); writer.write("NEURON_PER_LAYER = " + EvolveCheckersNet.NEURONS_PER_LAYER); writer.write("CULL_RATE = " + EvolveCheckersNet.CULL_RATE); writer.write("WEIGHT_MUTATION_RATE = " + EvolveCheckersNet.WEIGHT_MUTATION_RATE); writer.write("BIAS_MUTATION_RATE = " + EvolveCheckersNet.BIAS_MUTATION_RATE); for (Double d : winsVSLosses) { writer.write(d.toString()); } } } public static ImageIcon draw(List<Double> points, int width, int height){ if (width <= 0) width = 1; if (height <= 0) height = 1; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); if (points.size() < 2){ //nothing to draw if one point or fewer return new ImageIcon(image); } double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; for (Double d : points) { if (d < min){ min = d; } if (d > max){ max = d; } } Graphics2D g2 = image.createGraphics(); g2.setColor(Color.WHITE); g2.fillRect(0, 0, width, height); g2.setColor(Color.BLACK); g2.drawString("Max: " + max, 10, 10); g2.drawString("Min: " + min, 10, 22); AffineTransform tform = AffineTransform.getTranslateInstance( 0, image.getHeight()); tform.scale( 1, -1); g2.setTransform(tform); g2.setColor(Color.BLACK); double spacing = (double) width / (double) (points.size() - 1); int drawX1 = 0; int drawX2 = drawX1 + (int)spacing; for (int i = 0; i < points.size() - 1; i++) { int drawY1 = (int) (((points.get(i) - min) / (max - min)) * height); int drawY2 = (int) (((points.get(i+1) - min) / (max - min)) * height); g2.drawLine(drawX1, drawY1, drawX2, drawY2); drawX1 = drawX2; drawX2 = (int) (spacing * (i + 2)); } g2.dispose(); return new ImageIcon(image); } }
[ "aidan.mahler13@gmail.com" ]
aidan.mahler13@gmail.com
a2cc549fc587d802c186553d0ebc1976cf081d69
85f1ae44061a35af66eb68fd2b7cf6ce4a898228
/src/com/exchangeinfomanager/systemconfigration/CurDataBase.java
390869004edaf3c7a5de33ae704ad52639b0f2b4
[]
no_license
zimakaimenba/exchange
b04bd08d1a93156d54d536924a7db6bb51a0742f
0aacebdcfcc45d10e6b911864e7a62eead99e00f
refs/heads/master
2021-12-24T11:36:00.657363
2018-01-07T07:16:10
2018-01-07T07:16:10
95,062,133
2
0
null
null
null
null
UTF-8
Java
false
false
4,108
java
package com.exchangeinfomanager.systemconfigration; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JTextField; import javax.swing.LayoutStyle.ComponentPlacement; import net.miginfocom.swing.MigLayout; import javax.swing.JComboBox; import javax.swing.DefaultComboBoxModel; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class CurDataBase extends JPanel { /** * Create the panel. */ public CurDataBase (String sourcename) { addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent arg0) { } }); initializeGui (); tfldname.setText(sourcename); setLayout(new MigLayout("", "[72px][238px,grow]", "[24px][][30px][][][25px][31px]")); label = new JLabel("\u6570\u636E\u5E93\u7C7B\u578B"); add(label, "cell 0 1,alignx trailing"); comboBox = new JComboBox(); comboBox.setModel(new DefaultComboBoxModel(new String[] {"Access", "MySql", "SQL Server", "FoxPro"})); add(comboBox, "cell 1 1,growx"); add(lblNewLabel_1, "cell 0 2,alignx left,aligny center"); add(lblNewLabel, "cell 0 0,alignx right,aligny center"); lblAccess = new JLabel("access: \u6570\u636E\u5E93\u6587\u4EF6\u5168\u8DEF\u5F84+\u6587\u4EF6\u540D"); add(lblAccess, "cell 1 3"); lblMysql = new JLabel("Mysql: \u4F8B\uFF1Alocalhost:3306/stockinfomanagementtest"); add(lblMysql, "cell 1 4"); add(lblNewLabel_2, "cell 0 5,alignx left,aligny center"); add(lblNewLabel_3, "cell 0 6,alignx left,aligny center"); add(tfldpswd, "cell 1 6,alignx left,growy"); add(tflduser, "cell 1 5,alignx left,growy"); add(tfldname, "cell 1 0,alignx center,growy"); add(tflddbconstr, "cell 1 2,grow"); // datype = ""; // dbconstr = ""; // user = ""; // password = ""; curuseddbs = false; } // private String datype; // private String dbconstr; // private String user; // private String password; private boolean curuseddbs; public void setCurDatabaseType (String type) { comboBox.setSelectedItem(type); } public String getCurDatabaseType () { return comboBox.getSelectedItem().toString(); } public void setPassWord(String trim) { tfldpswd.setText( trim); } public String getPassWord() { return tfldpswd.getText(); } public void setUser(String trim) { tflduser.setText(trim); } public String getUser() { return tflduser.getText(); } public void setDataBaseConStr(String text) { tflddbconstr.setText(text); } public String getDataBaseConStr() { return toUNIXpath(tflddbconstr.getText()); } // public void setCurDataBaseName(String trim) // { // this.datype = trim; // } public String getCurDataBaseName() { return tfldname.getText(); } public void setCurrentSelectedDbs (boolean curuseddbs) { this.curuseddbs = curuseddbs; } public boolean getCurrentSelectedDbs () { return this.curuseddbs; } private String toUNIXpath(String filePath) { return filePath.replace('\\', '/'); } private JTextField tfldname; private JTextField tflddbconstr; private JTextField tflduser; private JTextField tfldpswd; private JLabel lblNewLabel_1; private JLabel lblNewLabel; private JLabel lblNewLabel_2; private JLabel lblNewLabel_3; private JLabel label; private JComboBox comboBox; private JLabel lblAccess; private JLabel lblMysql; private void initializeGui() { lblNewLabel = new JLabel("\u6570\u636E\u5E93\u6E90\u540D"); tfldname = new JTextField(); tfldname.setColumns(10); lblNewLabel_1 = new JLabel("\u6570\u636E\u5E93\u8FDE\u63A5\u5B57"); tflddbconstr = new JTextField(); tflddbconstr.setColumns(10); lblNewLabel_2 = new JLabel("\u7528\u6237\u540D"); tflduser = new JTextField(); tflduser.setColumns(10); lblNewLabel_3 = new JLabel("\u5BC6\u7801"); tfldpswd = new JTextField(); tfldpswd.setColumns(10); this.setFocusable(true); } }
[ "justjustjustjust@hotmail.com" ]
justjustjustjust@hotmail.com
f59fb92da5fbd389812845fc24da6c0baaaf44ec
74b47b895b2f739612371f871c7f940502e7165b
/aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/LoggingInfoMarshaller.java
6a83e417f38ea6087c18e5677ffaa9f8a3041fb7
[ "Apache-2.0" ]
permissive
baganda07/aws-sdk-java
fe1958ed679cd95b4c48f971393bf03eb5512799
f19bdb30177106b5d6394223a40a382b87adf742
refs/heads/master
2022-11-09T21:55:43.857201
2022-10-24T21:08:19
2022-10-24T21:08:19
221,028,223
0
0
Apache-2.0
2019-11-11T16:57:12
2019-11-11T16:57:11
null
UTF-8
Java
false
false
2,576
java
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.simplesystemsmanagement.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.simplesystemsmanagement.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * LoggingInfoMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class LoggingInfoMarshaller { private static final MarshallingInfo<String> S3BUCKETNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("S3BucketName").build(); private static final MarshallingInfo<String> S3KEYPREFIX_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("S3KeyPrefix").build(); private static final MarshallingInfo<String> S3REGION_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("S3Region").build(); private static final LoggingInfoMarshaller instance = new LoggingInfoMarshaller(); public static LoggingInfoMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(LoggingInfo loggingInfo, ProtocolMarshaller protocolMarshaller) { if (loggingInfo == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(loggingInfo.getS3BucketName(), S3BUCKETNAME_BINDING); protocolMarshaller.marshall(loggingInfo.getS3KeyPrefix(), S3KEYPREFIX_BINDING); protocolMarshaller.marshall(loggingInfo.getS3Region(), S3REGION_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
[ "" ]
8d40c8b878abbb9a387d0ccbf82f3dcf80fee057
eb9f655206c43c12b497c667ba56a0d358b6bc3a
/java/java-tests/testData/refactoring/introduceVariable/PutInLambdaBody.java
3d54e3b886464cbe8299500c8276037d283bbdef
[ "Apache-2.0" ]
permissive
JetBrains/intellij-community
2ed226e200ecc17c037dcddd4a006de56cd43941
05dbd4575d01a213f3f4d69aa4968473f2536142
refs/heads/master
2023-09-03T17:06:37.560889
2023-09-03T11:51:00
2023-09-03T12:12:27
2,489,216
16,288
6,635
Apache-2.0
2023-09-12T07:41:58
2011-09-30T13:33:05
null
UTF-8
Java
false
false
224
java
class Foo { interface I<T> { T m(Object op); } interface J<T> { int m(T o); } void f(J r) {} void f(I<String> r) {} { f((Object a) -> <selection>1</selection>); } }
[ "anna.kozlova@jetbrains.com" ]
anna.kozlova@jetbrains.com
b0ed6e3652415d6e4fd5a40a725427d4930b0d27
96592c26f0b0a54483e386b2072b5a4452096839
/src/main/java/stockservice/Portofilo.java
96c14b7964dd9b79606e80104ed4a4320fd212aa
[]
no_license
zhuchkoff/practise
60d8dd4bb6a2445f6e74ec67c112b58634bc726a
72b4af01c22f004109aef4a1aa58c6af52d20002
refs/heads/master
2020-03-22T12:14:13.706735
2018-07-07T19:06:48
2018-07-07T19:06:48
140,026,638
0
0
null
null
null
null
UTF-8
Java
false
false
644
java
package stockservice; import java.util.List; public class Portofilo { private StockService stockService; private List<Stock> stockList; public StockService getStockService() { return stockService; } void setStockService(StockService stockService) { this.stockService = stockService; } public List<Stock> getStockList() { return stockList; } void setStockList(List<Stock> stockList) { this.stockList = stockList; } double getMarketValue() { double result = 0.0F; for (Stock stock : stockList) { result += stockService.getPrice(stock) * stock.getAmount(); } return result; } }
[ "vadim.joutchkov@gmail.com" ]
vadim.joutchkov@gmail.com
a6d6dc219d214a3c3d267dba754cf094b6b6e725
9a7d620a052897927f849be783b0da3d16e1df3a
/app/src/main/java/com/wyu/iwork/interfaces/ContactIView.java
c09e0773aef342fcb9528455d430dfbd843d4607
[]
no_license
radtek/shangzhan
b44fafb7d294c76bb366a801787e93dbd6dea11b
3381103eb0b6371956caaabee17b145f4a28f433
refs/heads/master
2021-12-15T17:55:43.235567
2017-09-05T11:58:25
2017-09-05T11:58:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
179
java
package com.wyu.iwork.interfaces; /** * @author HuaJian Jiang. * Date 2017/1/3. */ public interface ContactIView<T> extends IView { void onLoadFinished(T data); }
[ "2587294424@qq.com" ]
2587294424@qq.com
38355c2db8b34a1b0566a025394b53d97380d3e1
52769277dfd1ab069a7e6f0010e994a3f984f915
/src/main/java/com/ycj/vip_manage/common/ToolsUtil.java
a390f03f479849d488e2a19f6db29fbd67c47a40
[ "Unlicense" ]
permissive
AbnerEarl/Consumption-Query-System-for-Maven-SpringMVC-Spring-Mybatis-MySql
d9b6d7a43f422d3e7647e4d9850c5e94ee1efbb9
56a8ee84c76667495cf4691a9d1e0e1d3caa3f95
refs/heads/master
2023-08-24T23:51:35.159466
2018-03-28T02:07:56
2018-03-28T02:07:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
275
java
package com.ycj.vip_manage.common; /** * PROJECT_NAME:vip_look * PACKAGE_NAME:com.ycj.vip_manage.common * USER:Frank * DATE:2018/3/20 * TIME:15:00 * DAY_NAME_FULL:星期二 * DESCRIPTION:On the description and function of the document **/ public class ToolsUtil { }
[ "1320259466@qq.com" ]
1320259466@qq.com
5c77f512d7238c56eab60cbc2ed47ee3e3969243
88a62b1b38495cdf9bae017c9b4ed898edfb06e2
/java_jungsuk3e_src_20170601/workspace/ch07/src/PolyArgumentTest3.java
a3ce292e3e98d159609d8003d0c1afbf65f5a53b
[]
no_license
talkin24/java_jungsuk
902df011cfdddd9e2ad77656e18f0fad934362fa
5ea9d9a33f9e77d1b5f0cf05f9df20afd0e696a4
refs/heads/master
2023-06-29T11:23:45.749584
2021-07-29T15:05:30
2021-07-29T15:05:30
366,378,195
0
0
null
null
null
null
UHC
Java
false
false
2,829
java
import java.util.*; // Vector클래스를 사용하기 위해서 추가해 주었다. class Product3 { int price; // 제품의 가격 int bonusPoint; // 제품구매 시 제공하는 보너스점수 Product3(int price) { this.price = price; bonusPoint =(int)(price/10.0); } Product3() { price = 0; bonusPoint = 0; } } class Tv5 extends Product3 { Tv5() { super(100); } public String toString() { return "Tv"; } } class Computer3 extends Product3 { Computer3() { super(200); } public String toString() { return "Computer"; } } class Audio3 extends Product3 { Audio3() { super(50); } public String toString() { return "Audio"; } } class Buyer3 { // 고객, 물건을 사는 사람 int money = 1000; // 소유금액 int bonusPoint = 0; // 보너스점수 Vector item = new Vector(); // 구입한 제품을 저장하는데 사용될 Vector객체 void buy(Product3 p) { if(money < p.price) { System.out.println("잔액이 부족하여 물건을 살수 없습니다."); return; } money -= p.price; // 가진 돈에서 구입한 제품의 가격을 뺀다. bonusPoint += p.bonusPoint; // 제품의 보너스 점수를 추가한다. item.add(p); // 구입한 제품을 Vector에 저장한다. System.out.println(p + "을/를 구입하셨습니다."); } void refund(Product3 p) { // 구입한 제품을 환불한다. if(item.remove(p)) { // 제품을 Vector에서 제거한다. money += p.price; bonusPoint -= p.bonusPoint; System.out.println(p + "을/를 반품하셨습니다."); } else { // 제거에 실패한 경우 System.out.println("구입하신 제품 중 해당 제품이 없습니다."); } } void summary() { // 구매한 물품에 대한 정보를 요약해서 보여준다. int sum = 0; // 구입한 물품의 가격합계 String itemList =""; // 구입한 물품목록 if(item.isEmpty()) { // Vector가 비어있는지 확인한다. System.out.println("구입하신 제품이 없습니다."); return; } // 반복문을 이용해서 구입한 물품의 총 가격과 목록을 만든다. for(int i=0; i<item.size();i++) { Product p = (Product)item.get(i); sum += p.price; itemList += (i==0) ? "" + p : ", " + p; } System.out.println("구입하신 물품의 총금액은 " + sum + "만원입니다."); System.out.println("구입하신 제품은 " + itemList + "입니다."); } } class PolyArgumentTest3 { public static void main(String args[]) { Buyer3 b = new Buyer3(); Tv5 tv = new Tv5(); Computer3 com = new Computer3(); Audio3 audio = new Audio3(); b.buy(tv); b.buy(com); b.buy(audio); b.summary(); System.out.println(); b.refund(com); b.summary(); } }
[ "cresc5talkin@gmail.com" ]
cresc5talkin@gmail.com
2bbe4553c573e2aeb5c3c8928d55ce4e10ea0313
93c5070ba702732c7f007ac7b89889e3342a4526
/src/test/java/servico/TesteFiltroLances.java
21b02f97817b45ef6558caba9271d9f758760e9d
[ "MIT" ]
permissive
rjungsevero/testesUnitarios
a7c91b799e0f0f2e60cde17c4157c8d8cd732953
1890cc80ffce89eed2a01bd5157eaba4de5d0bed
refs/heads/master
2021-06-27T22:05:00.029510
2021-06-19T20:58:31
2021-06-19T20:58:31
233,684,713
1
0
MIT
2020-10-13T18:49:21
2020-01-13T20:16:05
Java
UTF-8
Java
false
false
3,216
java
package servico; import builder.CriadorDeLeilao; import dominio.Lance; import dominio.Leilao; import dominio.Usuario; import org.junit.BeforeClass; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static builder.LeilaoMatcher.temUmLance; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItem; import static org.junit.Assert.assertThat; public class TesteFiltroLances { private static Usuario joao; private static FiltroLances filtro; private static List<Lance> resultado; @BeforeClass public static void setUp() { joao = new Usuario("Joao"); filtro = new FiltroLances(); resultado = new ArrayList<>(); } @Test public void testFiltroLance() { resultado = filtro.filtra(Arrays.asList( new Lance(joao, 2000), new Lance(joao, 1000), new Lance(joao, 5000), new Lance(joao, 800))); assertThat(resultado.size(), equalTo(1)); assertThat(resultado, hasItem(new Lance(joao, 2000))); } @Test public void testSelecionaLanceMaior5000() { resultado = filtro.filtra(Arrays.asList( new Lance(joao, 900), new Lance(joao, 1000), new Lance(joao, 6000), new Lance(joao, 800))); assertThat(resultado.size(), equalTo(1)); assertThat(resultado, hasItem(new Lance(joao, 6000))); } @Test public void testEliminaLanceMenor500() { resultado = filtro.filtra(Arrays.asList( new Lance(joao, 300), new Lance(joao, 200), new Lance(joao, 50), new Lance(joao, 275))); assertThat(resultado.size(), equalTo(0)); } @Test public void testEliminaLanceEntre700E1000() { resultado = filtro.filtra(Arrays.asList( new Lance(joao, 800), new Lance(joao, 900), new Lance(joao, 750), new Lance(joao, 995))); assertThat(resultado.size(), equalTo(0)); } @Test public void testEliminaLanceEntre3000E5000() { resultado = filtro.filtra(Arrays.asList( new Lance(joao, 4000), new Lance(joao, 3500), new Lance(joao, 4550), new Lance(joao, 3995))); assertThat(resultado.size(), equalTo(0)); } @Test(expected = IllegalArgumentException.class) public void testLanceComValorNegativoOuIgualAZero() { resultado = filtro.filtra(Arrays.asList( new Lance(joao, 1000), new Lance(joao, -50), new Lance(joao, 4550), new Lance(joao, 3995))); } @Test public void deveReceberUmLance() { Leilao leilao = new CriadorDeLeilao().para("Macbook Pro 15").constroi(); assertThat(leilao.getLances().size(), equalTo(0)); Lance lance = new Lance(new Usuario("Steve Jobs"), 2000); leilao.propoe(lance); assertThat(leilao.getLances().size(), equalTo(1)); assertThat(leilao, temUmLance(lance)); } }
[ "raul.severo@dbserver.com.br" ]
raul.severo@dbserver.com.br
11d23205485e68081966768edfccc386b7785cca
d85eea278f53c2d60197a0b479c074b5a52bdf1e
/Services/msk-seller/src/main/java/com/msk/seller/logic/ISLSellerRsLogic.java
db1a88224b293bdc5386b14b90abd76a7fc723f4
[]
no_license
YuanChenM/xcdv1.5
baeaab6e566236d0f3e170ceae186b6d2999c989
77bf0e90102f5704fe186140e1792396b7ade91d
refs/heads/master
2021-05-26T04:51:12.441499
2017-08-14T03:06:07
2017-08-14T03:06:07
100,221,981
1
2
null
null
null
null
UTF-8
Java
false
false
13,242
java
package com.msk.seller.logic; import com.hoperun.core.bean.BaseParam; import com.hoperun.core.exception.BusinessException; import com.hoperun.core.utils.DateTimeUtil; import com.hoperun.core.utils.StringUtil; import com.hoperun.core.utils.ValidatorUtils; import com.hoperun.jdbc.mybatis.BaseDao; import com.msk.bs.bean.IBS2101115Param; import com.msk.common.base.BaseLogic; import com.msk.common.bean.RsRequest; import com.msk.common.logic.CommonLogic; import com.msk.core.entity.BsBasicInfo; import com.msk.core.entity.SlAccount; import com.msk.core.entity.SlSeller; import com.msk.core.entity.SlSellerHis; import com.msk.district.bean.CityBean; import com.msk.district.bean.DistrictBean; import com.msk.district.bean.ProvinceBean; import com.msk.seller.bean.ISLSellerRsParam; import com.msk.seller.bean.ISLSellerRsResult; import com.msk.seller.utils.ISLRestUtil; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by zhang_chi on 2016/8/3. */ @Service public class ISLSellerRsLogic extends BaseLogic { interface SqlId { String SQL_ID_UPDATE_SLACCOUNT = "updateSlAccount"; String SQL_ID_UPDATE_SLSELLER = "updateSlSeller"; String SQL_ID_SAVE_SELLER = "saveSeller"; } @Autowired @Override public void setBaseDao(BaseDao baseDao) { super.setBaseDao(baseDao); } @Autowired private SL241103001Logic sl241103001Logic; @Autowired private SLAccountLogic slAccountLogic; @Autowired private SL24110102Logic sl24110102Logic; @Autowired private CommonLogic commonLogic; /** * 必须项check * * @param slAccount * @param slSeller */ private void RequiredCheck(SlAccount slAccount, SlSeller slSeller) { // 创建必须项校验的对象 HashMap<String, Object> checkObj = new HashMap<String, Object>(); if (null == slAccount && null == slSeller) { checkObj.put("卖家信息", null); } // 处理 sl_account if (null != slAccount) { checkObj.put("卖家账号", slAccount.getSlAccount()); checkObj.put("手机号", slAccount.getSlTel()); } // 处理 sl_Seller if (null != slSeller) { // if (null != slSeller.getSlCode()) { checkObj.put("卖家账号", slSeller.getSlAccount()); // if (null != slSeller.getCityCode()) { // checkObj.put("卖家分类", slSeller.getSlMainClass()); // checkObj.put("地区编码", slSeller.getCityCode()); // checkObj.put("生产国籍", slSeller.getSlConFlg()); // } // } else { // checkObj.put("卖家账号", slSeller.getSlAccount()); // checkObj.put("卖家分类", slSeller.getSlMainClass()); // checkObj.put("地区编码", slSeller.getCityCode()); // checkObj.put("生产国籍", slSeller.getSlConFlg()); // } } // 必须项校验 ValidatorUtils.validatorRequired(checkObj); } /** * 新增或修改卖家基本信息 * * @param param * @return */ @Transactional public ISLSellerRsResult dealSlSellerData(RsRequest<ISLSellerRsParam> param) { ISLSellerRsResult islSellerRsResult = new ISLSellerRsResult(); SlAccount slAccount = param.getParam().getSlAccount(); SlSeller slSeller = param.getParam().getSlSeller(); // 必须项check RequiredCheck(slAccount, slSeller); IBS2101115Param ibs2101115Param = new IBS2101115Param(); // 处理 sl_account if (null != slAccount) { Map<String, Object> maps = dealSlAccount(slAccount); Integer slAccountCount = (Integer) maps.get("slAccountCount"); // 影响行数 islSellerRsResult.setSlAccountCount(slAccountCount); // 准备接口数据 BeanUtils.copyProperties(slAccount, ibs2101115Param); String operationFlg = (String) maps.get("operationFlg"); ibs2101115Param.setOperationFlg(operationFlg); } // 处理 sl_Seller if (null != slSeller) { Map<String, Object> maps = dealSlSeller(slSeller); Integer slSellerCount = (Integer) maps.get("slSellerCount"); // 影响行数 islSellerRsResult.setSlSellerCount(slSellerCount); SlSeller slSellerR = (SlSeller) maps.get("slSeller"); String operationFlg = (String) maps.get("operationFlg"); // 准备接口数据 BsBasicInfo bsBasicInfo = new BsBasicInfo(); BeanUtils.copyProperties(slSellerR, bsBasicInfo); ibs2101115Param.setBsBasicInfo(bsBasicInfo); ibs2101115Param.setOperationFlg(operationFlg); String slCode = (String) maps.get("slCode"); islSellerRsResult.setSlCode(slCode); } // 调接口处理 boolean flag = ISLRestUtil.syncBuyerInfo(ibs2101115Param); // 更新失败 if (!flag) { throw new BusinessException("买手新增或变更失败"); } return islSellerRsResult; } /** * 处理 sl_account * * @param slAccount * @return */ @Transactional private Map<String, Object> dealSlAccount(SlAccount slAccount) { Map<String, Object> maps = new HashMap<String, Object>(); Integer slAccountCount = 0; String account = slAccount.getSlAccount(); slAccount.setCrtTime(DateTimeUtil.getCustomerDate()); slAccount.setUpdTime(DateTimeUtil.getCustomerDate()); //判断这个账户是否已经存在,拿数据去后台查询数据库查询账号信息 SlAccount EntitySql = this.sl241103001Logic.slAccountEntity(account); if (null != EntitySql) { // 更新sl_account slAccountCount = slAccountLogic.modify(SqlId.SQL_ID_UPDATE_SLACCOUNT, slAccount); maps.put("operationFlg", "2"); } else { // 新增sl_account slAccountCount = sl241103001Logic.save(slAccount); maps.put("operationFlg", "1"); } maps.put("slAccountCount", slAccountCount); return maps; } /** * 处理 sl_Seller * * @param slSeller * @return */ @Transactional private Map<String, Object> dealSlSeller(SlSeller slSeller) { Map<String, Object> maps = new HashMap<String, Object>(); Integer slSellerCount = 0; String slCode = slSeller.getSlCode(); slSeller.setCrtTime(DateTimeUtil.getCustomerDate()); slSeller.setUpdTime(DateTimeUtil.getCustomerDate()); String codeDis = this.sl241103001Logic.findAccount(slSeller.getSlMainClass().toString(), slSeller.getCityCode(), slSeller.getSlConFlg()); // 更新sl_Seller if (!StringUtil.isNullOrEmpty(slCode)) { // slCodeDis变更新增历史表 if (!StringUtil.isNullOrEmpty(slSeller.getSlCodeDis())) { /**查询该卖家编码下的slseller信息*/ SlSellerHis slSellerHis = sl24110102Logic.findSlSellerBySlCode(slCode); if (null != slSellerHis) { Long hisId = this.commonLogic.maxId("SL_SELLER_HIS", "HIS_ID"); slSellerHis.setHisId(hisId); this.sl24110102Logic.saveHis(slSellerHis); } } slSeller = dealSlSellerCodes(slSeller); // 获取SL_CODE_DIS 新增则直接前逻辑获取编码 修改通过该出获取最新的编码 2017/3/23修改卖家编码生成 if(codeDis == null || "".equals(codeDis)){ BaseParam base = new BaseParam(); base.setFilter("cityCode", slSeller.getCityCode()); base.setFilter("slMainClass", StringUtil.toSafeString(slSeller.getSlMainClass())); base.setFilter("slConFlg", slSeller.getSlConFlg()); SlSeller seller = sl24110102Logic.findOne("queryMax", base); if(seller != null){ slSeller.setSlCodeDis(seller.getSlCodeDis()); }else{ slSeller.setSlCodeDis(codeDis); } } slSeller.setCrtTime(DateTimeUtil.getCustomerDate()); slSeller.setUpdTime(DateTimeUtil.getCustomerDate()); slSellerCount = super.modify(SqlId.SQL_ID_UPDATE_SLSELLER, slSeller); maps.put("operationFlg", "2"); maps.put("slCode",slCode); } // 新增sl_Seller else { BaseParam baseparam = new BaseParam(); baseparam.getFilterMap().put("slAccount", slSeller.getSlAccount()); SlSeller slSellerD = slAccountLogic.findOne(baseparam); if (null == slSellerD) { slSeller = dealSlSellerCodes(slSeller); slSellerCount = sl241103001Logic.save(SqlId.SQL_ID_SAVE_SELLER, slSeller); SlSeller slSellerDB = slAccountLogic.findOne(baseparam); slSeller.setSlCode(slSellerDB.getSlCode()); maps.put("slCode",slSellerDB.getSlCode()); maps.put("operationFlg", "1"); } else { maps.put("slCode",slSellerD.getSlCode()); slSeller.setSlCode(slSellerD.getSlCode()); // slCodeDis变更新增历史表 if (!StringUtil.isNullOrEmpty(slSeller.getSlCodeDis())) { /**查询该卖家编码下的slseller信息*/ SlSellerHis slSellerHis = sl24110102Logic.findSlSellerBySlCode(slSeller.getSlCode()); if (null != slSellerHis) { Long hisId = this.commonLogic.maxId("SL_SELLER_HIS", "HIS_ID"); slSellerHis.setHisId(hisId); this.sl24110102Logic.saveHis(slSellerHis); } } slSeller = dealSlSellerCodes(slSeller); slSeller.setSlCodeDis(codeDis); slSellerCount = super.modify(SqlId.SQL_ID_UPDATE_SLSELLER, slSeller); maps.put("operationFlg", "2"); } } maps.put("slSellerCount", slSellerCount); maps.put("slSeller", slSeller); return maps; } /** * 对 省,市区,地区,卖家显示编码 处理 * * @param slSeller * @return */ @Transactional(readOnly = true) private SlSeller dealSlSellerCodes(SlSeller slSeller) { // 处理 省编码 String provinceCode = slSeller.getProvinceCode(); if (!StringUtil.isNullOrEmpty(provinceCode)) { ProvinceBean province = sl241103001Logic.findProvince(provinceCode); slSeller.setProvinceName(province.getProvinceName()); slSeller.setAreaCode(province.getAreaCode()); slSeller.setAreaName(province.getAreaName()); } // 处理 地区(含地级市) String cityCode = slSeller.getCityCode(); if (!StringUtil.isNullOrEmpty(cityCode)) { CityBean city = sl241103001Logic.findCity(cityCode); slSeller.setCityName(city.getCityName()); slSeller.setLgcsAreaCode(city.getLgcsAreaCode()); slSeller.setLgcsAreaName(city.getLgcsAreaName()); // 处理 区(含县级市、县、区) String districtCode = slSeller.getDistrictCode(); if (!StringUtil.isNullOrEmpty(districtCode)) { DistrictBean district = sl241103001Logic.findDistrict(cityCode, districtCode); slSeller.setDistrictName(district.getDistrictName()); } // // 处理 codeDis // String codeDis = this.sl241103001Logic.findAccount(slSeller.getSlMainClass().toString(), cityCode, slSeller.getSlConFlg()); // slSeller.setSlCodeDis(codeDis); } return slSeller; } /** * 根据卖家编码批量查询卖家信息 * * @param rsParam * @return */ @Transactional(readOnly = true) public ISLSellerRsResult queryISLSellerRsResult(ISLSellerRsParam rsParam) { ISLSellerRsResult islSellerRsResult = new ISLSellerRsResult(); if (null != rsParam) { List<String> sellCodeList = rsParam.getSellCodeList(); if (CollectionUtils.isNotEmpty(sellCodeList)) { BaseParam baseParam = new BaseParam(); baseParam.setFilterObject("sellCodeList", sellCodeList); List<ISLSellerRsResult> islSellerRsResultList = super.findList(baseParam); if (CollectionUtils.isNotEmpty(islSellerRsResultList)) { islSellerRsResult.setIslSellerRsResultList(islSellerRsResultList); } } } return islSellerRsResult; } }
[ "yuan_chen1@hoperun.com" ]
yuan_chen1@hoperun.com
1a71980504d3ef03979cc57e3f238b3c244dd15b
6865fbb02ac8f1cbbea2b0633dbbbae37c54b81d
/Hello.java
5c16b85e2e003c3bb772050d5baf6adcfcc78d28
[]
no_license
SarkisDonabedian/java
aa50b911c84833f60034cb35a5f8bfd1eb4d2c04
9367c85b5ba824272f29a3910b576b09d3371d21
refs/heads/master
2023-05-06T10:56:50.903861
2021-05-29T18:50:07
2021-05-29T18:50:07
372,048,172
0
0
null
null
null
null
UTF-8
Java
false
false
117
java
public class Hello{ public static void main(String[] args){ System.out.println("Hello World..."); } }
[ "75737789+SarkisDonabedian@users.noreply.github.com" ]
75737789+SarkisDonabedian@users.noreply.github.com
215d34a731a971087bcb25a17a62ef903f919bfe
6548071dd79fbba52263cb5adf81f544a0469e6e
/src/Chapter9/QuestionSeven.java
7d3409d9388dbd40b664c8b1e1d0fd3d5ad5e16b
[]
no_license
seangitacc/Assignment2
dd933a478b12907431ef02b96e42b4e55cd88450
25680f47a558e5f2865dde0ca4b77f8f11a81e9a
refs/heads/master
2021-08-14T07:00:37.884255
2017-11-14T22:25:40
2017-11-14T22:25:40
110,752,744
0
0
null
null
null
null
UTF-8
Java
false
false
1,765
java
package Chapter9; import java.util.Date; public class QuestionSeven { public static void main(String[] args) { //Create account and test methods Account a1 = new Account(1122, 20000); a1.setAnnualInterestRate(4.5); a1.withdraw(2500); a1.deposit(3000); System.out.println(a1.getBalance()); System.out.println(a1.getMonthlyInterest()); System.out.println(a1.getDateCreated()); } } class Account{ private int id = 0; private double balance = 0; private double annualInterestRate = 0; private Date dateCreated; public Account(){ } public Account(int id, double balance){ this.id = id; this.balance = balance; dateCreated = new Date(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public double getAnnualInterestRate() { return annualInterestRate; } public void setAnnualInterestRate(double annualInterestRate) { this.annualInterestRate = annualInterestRate; } public Date getDateCreated() { return dateCreated; } //Need to find the monthly interest rate from the given annual one public double getMonthlyInterestRate(){ return (annualInterestRate / 100) / 12; } public double getMonthlyInterest(){ return balance * getMonthlyInterestRate(); } public void withdraw(double number){ this.balance = balance - number; } public void deposit(double number){ this.balance = balance + number; } }
[ "seanmailacc@gmail.com" ]
seanmailacc@gmail.com
014030f5121d50d0eca3192520632d62ce92c21e
d168ebf206fb9c97f49cbea1d6f8c52e0e2c2cd1
/src/facade/Dog.java
0c59f11314c979af2541d589c56d32d3537b2d0d
[]
no_license
hungnhungit/design-patterns
4c3ec17e430c2545f7629ecf23d6fb606db7320d
b81756b2fff8e54e92e052ece414054c8c916edb
refs/heads/master
2020-03-30T01:09:21.265288
2018-09-27T09:26:28
2018-09-27T09:26:28
150,562,168
0
0
null
null
null
null
UTF-8
Java
false
false
126
java
package facade; public class Dog implements IAnimal{ @Override public void eat() { System.out.println("Eat Dog"); } }
[ "hungnhung123@gmail.com" ]
hungnhung123@gmail.com
3b9bafc26aeebf6f5340785045720bdd10c07f14
18988ca78eed777f7ff0c2536b2ab7837570fa10
/LeetCoding Challenge/src/december/MaximumDepthofBinaryTree.java
7f4c76910ba020fa16cc90851f7f4106617d6fdf
[]
no_license
tns94/Leetcode
7f30cdd3c8d6dcaa202f8b55ec0e94656f6ca8b0
9fdbeb399b3e99c748ad700501a9369ad49a5112
refs/heads/master
2023-08-25T13:40:20.619049
2021-10-16T15:27:24
2021-10-16T15:27:24
276,686,474
0
0
null
null
null
null
UTF-8
Java
false
false
522
java
package december; import utils.TreeNode; /* https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/569/week-1-december-1st-december-7th/3551/ */ public class MaximumDepthofBinaryTree { int max=0; public int maxDepth(TreeNode root) { dfs(root,1); return max; } void dfs(TreeNode root,int level){ if(root==null) { max=Math.max(max,level); return; } dfs(root.left,level+1); dfs(root.right,level+1); } }
[ "tarun10994@gmail.com" ]
tarun10994@gmail.com
b914594f79408d0a3611cbfd90b941602bd05181
66220fbb2b7d99755860cecb02d2e02f946e0f23
/src/net/sourceforge/plantuml/font/PSystemListFontsFactory.java
5ce1eea5530522c8fe266c8c71abf3fed9f9a00f
[ "MIT" ]
permissive
isabella232/plantuml-mit
27e7c73143241cb13b577203673e3882292e686e
63b2bdb853174c170f304bc56f97294969a87774
refs/heads/master
2022-11-09T00:41:48.471405
2020-06-28T12:42:10
2020-06-28T12:42:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,453
java
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * Licensed under The MIT License (Massachusetts Institute of Technology License) * * See http://opensource.org/licenses/MIT * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.font; import net.sourceforge.plantuml.AbstractPSystem; import net.sourceforge.plantuml.StringUtils; import net.sourceforge.plantuml.command.PSystemSingleLineFactory; public class PSystemListFontsFactory extends PSystemSingleLineFactory { @Override protected AbstractPSystem executeLine(String line) { final String lineLower = StringUtils.goLowerCase(line); if (lineLower.equals("listfont") || lineLower.equals("listfonts") || lineLower.startsWith("listfont ") || lineLower.startsWith("listfonts ")) { final int idx = line.indexOf(' '); return new PSystemListFonts(idx == -1 ? "This is a test" : StringUtils.trin(line.substring(idx))); } return null; } }
[ "plantuml@gmail.com" ]
plantuml@gmail.com
67f769b9165a249da596010429e5df431f67b40c
e6ef66c1b9a6801f1023d9192debc9acdcf787f1
/src/com/fh/controller/app/appuser/IntAppuserController.java
a6b11ed18add9f6e20773bc54660f38580408b29
[ "MIT" ]
permissive
afa007/zxtd
80b0c3deac3d06cf8d040cba8e404a1d75e30c0d
c7210a15ac73f13721155edd17dfd70a02679da6
refs/heads/master
2021-01-24T21:19:15.303143
2016-01-18T13:56:43
2016-01-18T13:56:43
49,758,206
0
0
null
2016-01-16T03:52:29
2016-01-16T03:52:29
null
UTF-8
Java
false
false
4,006
java
package com.fh.controller.app.appuser; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.crypto.hash.SimpleHash; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.fh.controller.base.BaseController; import com.fh.entity.system.User; import com.fh.service.system.appuser.AppuserService; import com.fh.util.AppUtil; import com.fh.util.Const; import com.fh.util.DateUtil; import com.fh.util.MD5; import com.fh.util.PageData; import com.fh.util.Tools; import com.google.gson.Gson; /** * 会员-接口类 * * 相关参数协议: 00 请求失败 01 请求成功 02 返回空值 03 请求协议参数不完整 04 用户名或密码错误 05 FKEY验证失败 */ @Controller @RequestMapping(value = "/appuser") public class IntAppuserController extends BaseController { @Resource(name = "appuserService") private AppuserService appuserService; /** * APP用户登录 */ @RequestMapping(value = "/login") @ResponseBody public Object loginAppuser() { logBefore(logger, "APP用户登录"); Map<String, Object> map = new HashMap<String, Object>(); PageData pd = new PageData(); pd = this.getPageData(); String result = "00"; Gson gson = new Gson(); logger.info("pd:" + gson.toJson(pd)); try { String USERNAME = pd.getString("USERNAME"); if (Tools.checkKey(USERNAME, pd.getString("FKEY"))) { // 检验请求key值是否合法 if (AppUtil.checkParam("login", pd)) { // 检查参数 String PASSWORD = pd.getString("PASSWORD"); String passwd = MD5.md5(PASSWORD); // 密码加密 pd.put("PASSWORD", passwd); System.out.println("USERNAME:" + pd.getString("USERNAME") + ",PASSWORD:" + pd.getString("PASSWORD")); pd = appuserService.getUserByNameAndPwd(pd); if (pd != null) { // 更新登录信息 pd.put("LAST_LOGIN", DateUtil.getTime().toString()); appuserService.updateLastLogin(pd); // shiro加入身份验证 Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken( USERNAME, PASSWORD); try { subject.login(token); } catch (AuthenticationException e) { result = "02"; // 身份验证失败 } pd = appuserService.findByUId(pd); map.put("pd", pd); result = (null == pd) ? "02" : "00"; // 02用户名密码校验成功,读取客户信息失败 } else { result = "01"; // 用户名或者密码错 } } else { result = "04"; // 参数缺失 } } else { result = "05"; // FKEY值校验失败 } } catch (Exception e) { logger.error(e.toString(), e); } finally { map.put("result", result); logAfter(logger); } return AppUtil.returnObject(new PageData(), map); } /** * 根据用户名获取会员信息 */ @RequestMapping(value = "/getAppuserByUm") @ResponseBody public Object getAppuserByUsernmae() { logBefore(logger, "根据用户名获取会员信息"); Map<String, Object> map = new HashMap<String, Object>(); PageData pd = new PageData(); pd = this.getPageData(); String result = "00"; try { if (Tools.checkKey("USERNAME", pd.getString("FKEY"))) { // 检验请求key值是否合法 if (AppUtil.checkParam("getAppuserByUsernmae", pd)) { // 检查参数 pd = appuserService.findByUId(pd); map.put("pd", pd); result = (null == pd) ? "02" : "00"; } else { result = "03"; } } else { result = "05"; } } catch (Exception e) { logger.error(e.toString(), e); } finally { map.put("result", result); logAfter(logger); } return AppUtil.returnObject(new PageData(), map); } }
[ "yankaili2006@gmail.com" ]
yankaili2006@gmail.com
b718fd5ea4a126103e8c1888b5bc7345e65f52b7
81b96ca92ea792b32c72be8aadfc53efb9df1312
/src/com/syntax/class18/Dog.java
7fd76d0bd3f2dfcb55531bca5e6dae3e13709bff
[]
no_license
Elizabeth8353/Intelij-Batch-10
1d21c8094050430cd176c9218a59aeb9544f0ae3
e7d8004eee5a3f201eb053c842ec888ebac3161f
refs/heads/main
2023-08-24T03:47:21.629009
2021-10-23T04:22:31
2021-10-23T04:22:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
995
java
package com.syntax.class18; public class Dog { String name; int age; double height; double weight; String breed; String color; static int noOfLegs=4; Dog(){ name="sammy"; age=5; height=5.0; weight=5.1; color="white"; } Dog(String dogName,int dogAge, double dogHeight,double dogWeight,String dogBreed,String dogColor){ name=dogName; age=dogAge; height=dogHeight; weight=dogWeight; color=dogColor; } Dog (String dogName){ name=dogName; age=10; weight=10; height=10; breed="none"; color="None"; } Dog(String dogName,int dogAge, double dogHeight){ name=dogName; age=10; weight=10; height=10; breed="none"; color="None"; } void printDogInfo(){ System.out.println("Name "+name+" Age "+age+" Height "+height+" Breed "+breed+" Color"+ color); } }
[ "evaldivieso6@gmail.com" ]
evaldivieso6@gmail.com
0079675fb73a3c8b7c45af48f3e43d74474c8455
1f19aec2ecfd756934898cf0ad2758ee18d9eca2
/u-1/u-11/u-11-f8431.java
5988ab6b1a3cd749be94c751aabeb95572ff6f2a
[]
no_license
apertureatf/perftest
f6c6e69efad59265197f43af5072aa7af8393a34
584257a0c1ada22e5486052c11395858a87b20d5
refs/heads/master
2020-06-07T17:52:51.172890
2019-06-21T18:53:01
2019-06-21T18:53:01
193,039,805
0
0
null
null
null
null
UTF-8
Java
false
false
105
java
mastercard 5555555555554444 4012888888881881 4222222222222 378282246310005 6011111111111117 503025695621
[ "jenkins@khan.paloaltonetworks.local" ]
jenkins@khan.paloaltonetworks.local
e3e7a562c14cf229783bc49c30f1b36852f97dd6
067f50f8c2001f864aee0e30d66cc95e4a81be89
/src/Java_8_Stream.java
f430c0f5dccbdf27aaaf804f2b61d5a250927f1c
[]
no_license
singhsonu778/Java-8-Features
2478308172b94defeb5b0059fd1af613e61bb480
51b36443860789e1d6c32a6dc334efe4b1b00ded
refs/heads/master
2021-01-10T03:51:42.554252
2016-08-31T17:43:20
2016-08-31T17:43:20
50,413,704
0
0
null
null
null
null
UTF-8
Java
false
false
1,551
java
import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.stream.Collectors; public class Java_8_Stream { public static void main(String args[]) { List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl"); strings.forEach(System.out::println); // filter //count long count = strings.stream().filter(string -> string.isEmpty()).count(); System.out.println("Empty Strings count: " + count); count = strings.stream().filter(string -> string.length() == 3).count(); System.out.println("Strings of length 3: " + count); List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList()); System.out.println("Filtered List: " + filtered); String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", ")); System.out.println("Merged String: " + mergedString); List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); System.out.println("Numbers : " + numbers); // map strings.stream().map(String::toUpperCase).forEach(System.out::println); // distinct Object squaresList = numbers.stream().map(i -> i * i).distinct().collect(Collectors.toList()); System.out.println("Squares List: " + squaresList); System.out.println("Random Numbers: "); Random random = new Random(); // sort random.ints().limit(10).sorted().forEach(System.out::println); /* sorted only create a sorted view of the stream without manipulating the ordering of the backed collection */ } }
[ "singhsonu778@gmail.com" ]
singhsonu778@gmail.com
24607ea722b18001aea11b94356f29a170d8afdc
6bd255f7f9c999adac654ba062964222a522934a
/src/main/java/com/ztgeo/general/service/chenbin/FileHandleService.java
68cf012886e817e24f71abf8e089fcf295c654b3
[]
no_license
chenbinJ/one-rec-tzys
9f2a51175142949a3056bff6805ea116b099fd06
32272d49d6e0e664b255767ee982142051b705d9
refs/heads/master
2022-12-10T23:54:31.447868
2020-12-08T07:31:35
2020-12-08T07:31:35
215,182,318
0
0
null
2022-12-06T00:43:37
2019-10-15T01:53:59
JavaScript
UTF-8
Java
false
false
415
java
package com.ztgeo.general.service.chenbin; import com.ztgeo.general.entity.service_data.pub_data.SJ_Fjfile; import org.springframework.core.io.InputStreamResource; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; public interface FileHandleService { SJ_Fjfile uploadServiceFile(MultipartFile file); SJ_Fjfile getDownloadFileFromFtp(String fileId); }
[ "1358369360@qq.com" ]
1358369360@qq.com
4ffcd0c8fadb7838f3c0620c8ca86fea4999be35
c3824a459747ecac397ada3e8f0c5fe564f62c63
/Netty/src/main/java/com/github/decoder/NettyLengthFieldDecoder.java
7434046a30b8d6e44addc86c14ba64fc38150991
[]
no_license
andochiwa/Netty
720b5addc9e7f6c2e9dbcc0c42ca0638611bb0cc
2b1cae5ea8ba628f5ecbf9a5a6e4f229853caee9
refs/heads/master
2023-06-02T01:02:24.920504
2021-06-17T17:48:18
2021-06-17T17:48:18
374,077,759
0
0
null
null
null
null
UTF-8
Java
false
false
1,595
java
package com.github.decoder; import com.github.util.Utils; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; /** * @author HAN * @version 1.0 * @create 06-17-6:07 */ public class NettyLengthFieldDecoder { public static void main(String[] args){ EmbeddedChannel channel = new EmbeddedChannel( /* maxFrameLength: 发送的数据帧的最大长度 lengthFieldOffset: 数据帧中发送的长度的下标位置 lengthFieldLength: 发送的长度的字节数 lengthAdjustment: 发送额外内容的字节数 initialBytesToStrip: 接收到的发送数据包,去掉前initialBytesToStrip位(例如可以把长度位去掉) */ new LengthFieldBasedFrameDecoder( 1024, 0, 4, 2, 4)); ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(); send(buf, "hello"); send(buf, "hi"); channel.writeInbound(buf); ByteBuf readInbound; while ((readInbound = channel.readInbound()) != null) { Utils.log(readInbound); } } private static void send(ByteBuf buffer, String content) { byte[] bytes = content.getBytes(); // 实际内容 int length = bytes.length; // 实际内容长度 buffer.writeInt(length); buffer.writeBytes("1:".getBytes()); // 额外内容 buffer.writeBytes(bytes); } }
[ "a1066079469@gmail.com" ]
a1066079469@gmail.com
182ffff336f9b8a1fe60b0714ebfc7fdc78e510c
b3365765fd85db951ef2d449b1e0042a3de5e019
/LocationLab/src/course/labs/locationlab/PlaceDownloaderTask.java
5d363484e7b01bd78be538ebd79818328d607fa5
[]
no_license
damota80/coursera-android-2
20696ae5dd63da74136d9ff020703a2e75575b2d
b2f81c0fe7dc2aebcec82913b3778eb15039f9ca
refs/heads/master
2020-04-06T06:52:06.865554
2014-03-11T14:26:38
2014-03-11T14:26:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,817
java
package course.labs.locationlab; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Location; import android.os.AsyncTask; import android.util.Log; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class PlaceDownloaderTask extends AsyncTask<Location, Void, PlaceRecord> { // put your www.geonames.org account name here. private static String USERNAME = "btibi"; private HttpURLConnection mHttpUrl; private WeakReference<PlaceViewActivity> mParent; public PlaceDownloaderTask(PlaceViewActivity parent) { super(); mParent = new WeakReference<PlaceViewActivity>(parent); } @Override protected PlaceRecord doInBackground(Location... location) { PlaceRecord place = getPlaceFromURL(generateURL(USERNAME, location[0])); if ("" != place.getCountryName()) { place.setLocation(location[0]); place.setFlagBitmap(getFlagFromURL(place.getFlagUrl())); } else { place = null; } return place; } @Override protected void onPostExecute(PlaceRecord result) { if (null != result && null != mParent.get()) { mParent.get().addNewPlace(result); } } private PlaceRecord getPlaceFromURL(String... params) { String result = null; BufferedReader in = null; try { URL url = new URL(params[0]); mHttpUrl = (HttpURLConnection) url.openConnection(); in = new BufferedReader(new InputStreamReader( mHttpUrl.getInputStream())); StringBuffer sb = new StringBuffer(""); String line = ""; while ((line = in.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } catch (MalformedURLException e) { } catch (IOException e) { } finally { try { if (null != in) { in.close(); } } catch (IOException e) { e.printStackTrace(); } mHttpUrl.disconnect(); } return placeDataFromXml(result); } private Bitmap getFlagFromURL(String flagUrl) { InputStream in = null; try { URL url = new URL(flagUrl); mHttpUrl = (HttpURLConnection) url.openConnection(); in = mHttpUrl.getInputStream(); return BitmapFactory.decodeStream(in); } catch (MalformedURLException e) { Log.e("DEBUG",e.toString()); } catch (IOException e) { Log.e("DEBUG",e.toString()); } finally { try { if (null != in) { in.close(); } } catch (IOException e) { e.printStackTrace(); } mHttpUrl.disconnect(); } return BitmapFactory.decodeResource(mParent.get().getResources(), R.drawable.stub); } private static PlaceRecord placeDataFromXml(String xmlString) { DocumentBuilder builder; String countryName = ""; String countryCode = ""; String placeName = ""; String elevation = ""; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader( xmlString))); NodeList list = document.getDocumentElement().getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node curr = list.item(i); NodeList list2 = curr.getChildNodes(); for (int j = 0; j < list2.getLength(); j++) { Node curr2 = list2.item(j); if (curr2.getNodeName() != null) { if (curr2.getNodeName().equals("countryName")) { countryName = curr2.getTextContent(); } else if (curr2.getNodeName().equals("countryCode")) { countryCode = curr2.getTextContent(); } else if (curr2.getNodeName().equals("name")) { placeName = curr2.getTextContent(); } else if (curr2.getNodeName().equals("elevation")) { elevation = curr2.getTextContent(); } } } } } catch (DOMException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return new PlaceRecord( generateFlagURL(countryCode.toLowerCase()), countryName, placeName, elevation); } private static String generateURL(String username, Location location) { return "http://www.geonames.org/findNearbyPlaceName?username=" + username + "&style=full&lat=" + location.getLatitude() + "&lng=" + location.getLongitude(); } private static String generateFlagURL(String countryCode) { return "http://www.geonames.org/flags/x/" + countryCode + ".gif"; } }
[ "btibi@vipmail.hu" ]
btibi@vipmail.hu
35b1d593e3300840b95aa90c9a0e93934d7563ea
0d082dc178fa005325ee3c99fb0c07800b7d8bb0
/user/src/main/java/com/microservice/api/user/controller/UserController.java
9cab4b2cc5b97f76a50cbcb87fce7b1e018cbea4
[]
no_license
khuramshah89/microservice-with-spring-cloud
c11d6e7bcff76eb20992512ee506cfc3ba720b4f
a1c0fab1f1649c7011f7c7e4cbfa307b5c413dcc
refs/heads/master
2023-05-14T09:46:00.743163
2021-06-12T12:46:11
2021-06-12T12:53:43
362,794,411
0
0
null
2021-05-19T19:22:21
2021-04-29T11:31:24
Java
UTF-8
Java
false
false
616
java
package com.microservice.api.user.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") public class UserController { @Autowired Environment environment; @GetMapping("/check") public String getUser(){ return "user controller working at "+environment.getProperty("local.server.port"); } }
[ "khuram.shehzad@confiz.local" ]
khuram.shehzad@confiz.local
27408f7b9dc5e88a756d665769361310633a3d9f
f84edef58d738b02912f32d44e088aabe321eb60
/IBJts/samples/Java/TestJavaClient/OrderDlg.java
52e4326b89339a34ccf6995263aa438ef14697f0
[]
no_license
matanbakshi/ib-portfolio-manager
afea62e5597be03ce4c3e3250d0bd61c6481c720
8d17ffd25738ae9f124f0be53c4c844ba64fd0ad
refs/heads/master
2021-10-21T05:50:43.893552
2019-04-16T06:08:35
2019-04-16T06:08:35
165,415,616
2
1
null
null
null
null
UTF-8
Java
false
false
26,154
java
/* Copyright (C) 2018 Interactive Brokers LLC. All rights reserved. This code is subject to the terms * and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */ package TestJavaClient; import java.awt.BorderLayout; import java.awt.Component; import java.awt.GridBagConstraints; import java.util.*; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import com.ib.client.Contract; import com.ib.client.DeltaNeutralContract; import com.ib.client.MarketDataType; import com.ib.client.Order; import com.ib.client.TagValue; import apidemo.AdjustedPanel; import apidemo.ConditionsPanel; import apidemo.OnOKPanel; import apidemo.PegBenchPanel; public class OrderDlg extends JDialog { private static final String ALL_GENERIC_TICK_TAGS = "100,101,104,105,106,107,165,221,225,233,236,258,293,294,295,318"; private static final int OPERATION_INSERT = 0; private static final int OPERATION_UPDATE = 1; private static final int OPERATION_DELETE = 2; private static final int SIDE_ASK = 0; private static final int SIDE_BID = 1; public boolean m_rc; private int m_id; public int m_marketDepthRows; private Contract m_contract = new Contract(); public Order m_order = new Order(); public DeltaNeutralContract m_deltaNeutralContract = new DeltaNeutralContract(); public int m_exerciseAction; public int m_exerciseQuantity; public int m_override; public int m_marketDataType; private String m_optionsDlgTitle; private List<TagValue> m_options = new ArrayList<>(); private JTextField m_Id = new JTextField( "0"); private JTextField m_conId = new JTextField(); private JTextField m_symbol = new JTextField( "QQQQ"); private JTextField m_secType = new JTextField( "STK"); private JTextField m_lastTradeDateOrContractMonth = new JTextField(); private JTextField m_strike = new JTextField( "0"); private JTextField m_right = new JTextField(); private JTextField m_multiplier = new JTextField(""); private JTextField m_exchange = new JTextField( "SMART"); private JTextField m_primaryExch = new JTextField( "ISLAND" ); private JTextField m_currency = new JTextField("USD"); private JTextField m_localSymbol = new JTextField(); private JTextField m_tradingClass = new JTextField(); private JTextField m_includeExpired = new JTextField("0"); private JTextField m_secIdType = new JTextField(); private JTextField m_secId = new JTextField(); private JTextField m_action = new JTextField( "BUY"); private JTextField m_totalQuantity = new JTextField( "10"); private JTextField m_orderType = new JTextField( "LMT"); private JTextField m_lmtPrice = new JTextField( "40"); private JTextField m_auxPrice = new JTextField( "0"); private JTextField m_goodAfterTime = new JTextField(); private JTextField m_goodTillDate = new JTextField(); private JTextField m_cashQty = new JTextField(); private JTextField m_marketDepthRowTextField = new JTextField( "20"); private JCheckBox m_smartDepth = new JCheckBox("SMART Depth", true); private JTextField m_genericTicksTextField = new JTextField(ALL_GENERIC_TICK_TAGS); private JCheckBox m_snapshotMktDataTextField = new JCheckBox("Snapshot", false); private JCheckBox m_regSnapshotMktDataTextField = new JCheckBox("Regulatory Snapshot", false); private JTextField m_exerciseActionTextField = new JTextField("1"); private JTextField m_exerciseQuantityTextField = new JTextField("1"); private JTextField m_overrideTextField = new JTextField("0"); private JComboBox<String> m_marketDataTypeCombo = new JComboBox<>(MarketDataType.getFields()); private JButton m_sharesAlloc = new JButton("FA Allocation Info..."); private JButton m_comboLegs = new JButton( "Combo Legs"); private JButton m_btnDeltaNeutralContract = new JButton( "Delta Neutral"); private JButton m_btnAlgoParams = new JButton( "Algo Params"); private JButton m_btnSmartComboRoutingParams = new JButton( "Smart Combo Routing Params"); private JButton m_btnOptions = new JButton( "Options"); private JButton m_btnConditions = new JButton("Conditions"); private JButton m_btnPeg2Bench = new JButton("Pegged to benchmark"); private JButton m_btnAdjStop = new JButton("Adjustable stops"); private JButton m_btnHistoricalData = new JButton("Historical Data Query"); private HistoricalDataDlg m_historicalDataDlg = new HistoricalDataDlg(this); private JButton m_ok = new JButton( "OK"); private JButton m_cancel = new JButton( "Cancel"); private SampleFrame m_parent; private String m_faGroup; private String m_faProfile; private String m_faMethod; private String m_faPercentage; public String m_genericTicks; public boolean m_snapshotMktData; public boolean m_reqSnapshotMktData; private static final int COL1_WIDTH = 30 ; private static final int COL2_WIDTH = 100 - COL1_WIDTH ; public void faGroup(String s) { m_faGroup = s;} public void faProfile(String s) { m_faProfile = s;} public void faMethod(String s) { m_faMethod = s;} public void faPercentage(String s) { m_faPercentage = s; } OrderDlg( SampleFrame owner) { super( owner, true); m_parent = owner; setTitle( "Sample"); java.awt.GridBagConstraints gbc = new java.awt.GridBagConstraints() ; gbc.fill = GridBagConstraints.BOTH ; gbc.anchor = GridBagConstraints.CENTER ; gbc.weighty = 100 ; gbc.fill = GridBagConstraints.BOTH ; gbc.gridheight = 1 ; // create id panel IBGridBagPanel pId = new IBGridBagPanel(); pId.setBorder( BorderFactory.createTitledBorder( "Message Id") ); pId.addGBComponent(new JLabel( "Id"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE) ; pId.addGBComponent(m_Id, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER) ; // create contract panel IBGridBagPanel pContractDetails = new IBGridBagPanel(); pContractDetails.setBorder( BorderFactory.createTitledBorder( "Contract Info") ); pContractDetails.addGBComponent(new JLabel( "Contract Id"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_conId, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pContractDetails.addGBComponent(new JLabel( "Symbol"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_symbol, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pContractDetails.addGBComponent(new JLabel( "Security Type"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_secType, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pContractDetails.addGBComponent(new JLabel( "Last trade date or contract month"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_lastTradeDateOrContractMonth, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pContractDetails.addGBComponent(new JLabel( "Strike"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_strike, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pContractDetails.addGBComponent(new JLabel( "Put/Call"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_right, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pContractDetails.addGBComponent(new JLabel( "Option Multiplier"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_multiplier, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pContractDetails.addGBComponent(new JLabel( "Exchange"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_exchange, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pContractDetails.addGBComponent(new JLabel( "Primary Exchange"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_primaryExch, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pContractDetails.addGBComponent(new JLabel( "Currency"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_currency, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pContractDetails.addGBComponent(new JLabel( "Local Symbol"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_localSymbol, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pContractDetails.addGBComponent(new JLabel( "Trading Class"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_tradingClass, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pContractDetails.addGBComponent(new JLabel( "Include Expired"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_includeExpired, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pContractDetails.addGBComponent(new JLabel( "Sec Id Type"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_secIdType, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pContractDetails.addGBComponent(new JLabel( "Sec Id"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pContractDetails.addGBComponent(m_secId, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); // create order panel IBGridBagPanel pOrderDetails = new IBGridBagPanel(); pOrderDetails.setBorder( BorderFactory.createTitledBorder( "Order Info") ); pOrderDetails.addGBComponent(new JLabel( "Action"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pOrderDetails.addGBComponent(m_action, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pOrderDetails.addGBComponent(new JLabel( "Total Order Size"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pOrderDetails.addGBComponent(m_totalQuantity, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pOrderDetails.addGBComponent(new JLabel( "Order Type"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pOrderDetails.addGBComponent(m_orderType, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pOrderDetails.addGBComponent(new JLabel( "Lmt Price / Option Price / Stop Price / Volatility"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pOrderDetails.addGBComponent(m_lmtPrice, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pOrderDetails.addGBComponent(new JLabel( "Aux Price / Underlying Price"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pOrderDetails.addGBComponent(m_auxPrice, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pOrderDetails.addGBComponent(new JLabel( "Good After Time"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pOrderDetails.addGBComponent(m_goodAfterTime, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pOrderDetails.addGBComponent(new JLabel( "Good Till Date"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pOrderDetails.addGBComponent(m_goodTillDate, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); pOrderDetails.addGBComponent(new JLabel( "Cash Quantity"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE ); pOrderDetails.addGBComponent(m_cashQty, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER); // create marketDepth panel IBGridBagPanel pMarketDepth = new IBGridBagPanel(); pMarketDepth.setBorder( BorderFactory.createTitledBorder( "Market Depth") ); pMarketDepth.addGBComponent(new JLabel( "Number of Rows"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE) ; pMarketDepth.addGBComponent(m_marketDepthRowTextField, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER) ; pMarketDepth.addGBComponent(m_smartDepth, gbc, COL1_WIDTH, GridBagConstraints.RELATIVE); // create marketData panel IBGridBagPanel pMarketData = new IBGridBagPanel(); pMarketData.setBorder( BorderFactory.createTitledBorder( "Market Data") ); pMarketData.addGBComponent(new JLabel( "Generic Tick Tags"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE) ; pMarketData.addGBComponent(m_genericTicksTextField, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER) ; pMarketData.addGBComponent(m_snapshotMktDataTextField, gbc, COL1_WIDTH, GridBagConstraints.RELATIVE) ; pMarketData.addGBComponent(m_regSnapshotMktDataTextField, gbc, COL1_WIDTH, GridBagConstraints.RELATIVE) ; // create options exercise panel IBGridBagPanel pOptionsExercise= new IBGridBagPanel(); pOptionsExercise.setBorder( BorderFactory.createTitledBorder( "Options Exercise") ); pOptionsExercise.addGBComponent(new JLabel( "Action (1 or 2)"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE) ; pOptionsExercise.addGBComponent(m_exerciseActionTextField, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER) ; pOptionsExercise.addGBComponent(new JLabel( "Number of Contracts"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE) ; pOptionsExercise.addGBComponent(m_exerciseQuantityTextField, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER) ; pOptionsExercise.addGBComponent(new JLabel( "Override (0 or 1)"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE) ; pOptionsExercise.addGBComponent(m_overrideTextField, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER) ; // create marketDataType panel IBGridBagPanel pMarketDataType = new IBGridBagPanel(); pMarketDataType.setBorder( BorderFactory.createTitledBorder( "Market Data Type") ); pMarketDataType.addGBComponent(new JLabel( "Market Data Type"), gbc, COL1_WIDTH, GridBagConstraints.RELATIVE) ; pMarketDataType.addGBComponent(m_marketDataTypeCombo, gbc, COL2_WIDTH, GridBagConstraints.REMAINDER) ; // create mid Panel JPanel pMidPanel = new JPanel(); pMidPanel.setLayout( new BoxLayout( pMidPanel, BoxLayout.Y_AXIS) ); pMidPanel.add( pContractDetails, BorderLayout.CENTER); pMidPanel.add( pOrderDetails, BorderLayout.CENTER); pMidPanel.add( pMarketDepth, BorderLayout.CENTER); pMidPanel.add( pMarketData, BorderLayout.CENTER); pMidPanel.add( pOptionsExercise, BorderLayout.CENTER); pMidPanel.add( pMarketDataType, BorderLayout.CENTER); // create order button panel JPanel pOrderButtonPanel = new JPanel(); pOrderButtonPanel.add( m_sharesAlloc); pOrderButtonPanel.add( m_comboLegs); pOrderButtonPanel.add( m_btnDeltaNeutralContract); pOrderButtonPanel.add( m_btnAlgoParams); pOrderButtonPanel.add( m_btnSmartComboRoutingParams); pMidPanel.add( pOrderButtonPanel, BorderLayout.CENTER); JPanel pOrderButtonPanel2 = new JPanel(); pOrderButtonPanel2.add(m_btnOptions); pOrderButtonPanel2.add(m_btnConditions); pOrderButtonPanel2.add(m_btnPeg2Bench); pOrderButtonPanel2.add(m_btnAdjStop); pOrderButtonPanel2.add(m_btnHistoricalData); pMidPanel.add(pOrderButtonPanel2, BorderLayout.CENTER); // create button panel JPanel buttonPanel = new JPanel(); buttonPanel.add(m_ok); buttonPanel.add(m_cancel); // create action listeners m_btnHistoricalData.addActionListener(e -> onHistoricalData()); m_btnPeg2Bench.addActionListener(e -> onBtnPeg2Bench()); m_btnAdjStop.addActionListener(e -> onBtnAdjStop()); m_btnConditions.addActionListener(e -> onBtnConditions()); m_sharesAlloc.addActionListener(e -> onSharesAlloc()); m_comboLegs.addActionListener(e -> onAddComboLegs()); m_btnDeltaNeutralContract.addActionListener(e -> onBtnDeltaNeutralContract()); m_btnAlgoParams.addActionListener(e -> onBtnAlgoParams()); m_btnSmartComboRoutingParams.addActionListener(e -> onBtnSmartComboRoutingParams()); m_btnOptions.addActionListener(e -> onBtnOptions()); m_ok.addActionListener(e -> onOk()); m_cancel.addActionListener(e -> onCancel()); // create top panel JPanel topPanel = new JPanel(); topPanel.setLayout( new BoxLayout( topPanel, BoxLayout.Y_AXIS) ); topPanel.add( pId); topPanel.add( pMidPanel); // create dlg box getContentPane().add( topPanel, BorderLayout.CENTER); getContentPane().add( buttonPanel, BorderLayout.SOUTH); JScrollPane scroller = new JScrollPane(topPanel); this.add( scroller, BorderLayout.CENTER); pack(); } private void onHistoricalData() { m_historicalDataDlg.setVisible(true); } void onBtnAdjStop() { showModalPanelDialog(param -> new AdjustedPanel((JDialog)param, m_order)); } void onBtnPeg2Bench() { showModalPanelDialog(param -> new PegBenchPanel((JDialog)param, m_order, contract -> { try { return m_parent.lookupContract(contract); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new ArrayList<>(); })); } void onBtnConditions() { showModalPanelDialog(param -> new ConditionsPanel((JDialog)param, m_order, contract -> { try { return m_parent.lookupContract(contract); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new ArrayList<>(); })); } interface CallableWithParam { Object call(Object param); } private void showModalPanelDialog(CallableWithParam panelCreator) { JDialog dialog = new JDialog(); OnOKPanel panel = (OnOKPanel)panelCreator.call(dialog); dialog.add(panel); dialog.pack(); dialog.setModal(true); dialog.setVisible(true); panel.onOK(); } private static String pad( int val) { return val < 10 ? "0" + val : "" + val; } void onSharesAlloc() { if ( !m_parent.m_bIsFAAccount ) { return; } FAAllocationInfoDlg dlg = new FAAllocationInfoDlg(this); // show the combo leg dialog dlg.setVisible(true); } void onAddComboLegs() { ComboLegDlg comboLegDlg = new ComboLegDlg( m_contract.comboLegs(), m_order.orderComboLegs(), m_exchange.getText(), this); // show the combo leg dialog comboLegDlg.setVisible( true); } void onBtnDeltaNeutralContract() { DeltaNeutralContractDlg deltaNeutralContractDlg = new DeltaNeutralContractDlg(m_deltaNeutralContract, this); // show delta neutral dialog deltaNeutralContractDlg.setVisible( true); if (deltaNeutralContractDlg.ok()) { m_contract.deltaNeutralContract(m_deltaNeutralContract); } else if (deltaNeutralContractDlg.reset()) { m_contract.deltaNeutralContract(null); } } void onBtnAlgoParams() { AlgoParamsDlg algoParamsDlg = new AlgoParamsDlg(m_order, this); // show delta neutral dialog algoParamsDlg.setVisible( true); } void onBtnSmartComboRoutingParams() { SmartComboRoutingParamsDlg smartComboRoutingParamsDlg = new SmartComboRoutingParamsDlg("Smart Combo Routing Params", m_order.smartComboRoutingParams(), this); // show smart combo routing params dialog smartComboRoutingParamsDlg.setVisible( true); } void onBtnOptions() { SmartComboRoutingParamsDlg smartComboRoutingParamsDlg = new SmartComboRoutingParamsDlg(m_optionsDlgTitle, m_options, this); // show smart combo routing params dialog smartComboRoutingParamsDlg.setVisible( true); m_options = smartComboRoutingParamsDlg.smartComboRoutingParams(); } void onOk() { m_rc = false; try { // set id m_id = Integer.parseInt( m_Id.getText() ); // set contract fields m_contract.conid(ParseInt(m_conId.getText(), 0)); m_contract.symbol(m_symbol.getText()); m_contract.secType(m_secType.getText()); m_contract.lastTradeDateOrContractMonth(m_lastTradeDateOrContractMonth.getText()); m_contract.strike(ParseDouble(m_strike.getText(), 0.0)); m_contract.right(m_right.getText()); m_contract.multiplier(m_multiplier.getText()); m_contract.exchange(m_exchange.getText()); m_contract.primaryExch(m_primaryExch.getText()); m_contract.currency(m_currency.getText()); m_contract.localSymbol(m_localSymbol.getText()); m_contract.tradingClass(m_tradingClass.getText()); try { int includeExpired = Integer.parseInt(m_includeExpired.getText()); m_contract.includeExpired(includeExpired == 1); } catch (NumberFormatException ex) { m_contract.includeExpired(false); } m_contract.secIdType(m_secIdType.getText()); m_contract.secId(m_secId.getText()); // set order fields m_order.action(m_action.getText()); m_order.totalQuantity(Double.parseDouble( m_totalQuantity.getText() )); m_order.orderType(m_orderType.getText()); m_order.lmtPrice(parseStringToMaxDouble( m_lmtPrice.getText())); m_order.auxPrice(parseStringToMaxDouble( m_auxPrice.getText())); m_order.goodAfterTime(m_goodAfterTime.getText()); m_order.goodTillDate(m_goodTillDate.getText()); m_order.cashQty(parseStringToMaxDouble( m_cashQty.getText() )); m_order.faGroup(m_faGroup); m_order.faProfile(m_faProfile); m_order.faMethod(m_faMethod); m_order.faPercentage(m_faPercentage); // set historical data fields m_exerciseAction = Integer.parseInt( m_exerciseActionTextField.getText() ); m_exerciseQuantity = Integer.parseInt( m_exerciseQuantityTextField.getText() ); m_override = Integer.parseInt( m_overrideTextField.getText() ); // set market depth rows m_marketDepthRows = Integer.parseInt( m_marketDepthRowTextField.getText() ); m_genericTicks = m_genericTicksTextField.getText(); m_snapshotMktData = m_snapshotMktDataTextField.isSelected(); m_reqSnapshotMktData = m_regSnapshotMktDataTextField.isSelected(); m_marketDataType = m_marketDataTypeCombo.getSelectedIndex() + 1; } catch( Exception e) { Main.inform( this, "Error - " + e); return; } m_rc = true; setVisible( false); } void onCancel() { m_rc = false; setVisible( false); } @Override public void setVisible(boolean b) { if (b) { m_rc = false; } super.setVisible(b); } void setIdAtLeast( int id) { try { // set id field to at least id int curId = Integer.parseInt( m_Id.getText() ); if( curId < id) { m_Id.setText( String.valueOf( id) ); } } catch( Exception e) { Main.inform( this, "Error - " + e); } } private static int ParseInt(String text, int defValue) { try { return Integer.parseInt(text); } catch (NumberFormatException e) { return defValue; } } private static double ParseDouble(String text, double defValue) { try { return Double.parseDouble(text); } catch (NumberFormatException e) { return defValue; } } private static double parseStringToMaxDouble(String value) { if (value.trim().length() == 0) { return Double.MAX_VALUE; } return Double.parseDouble(value); } void init(String btnText, boolean btnEnabled, String dlgTitle, List<TagValue> options) { init(btnText, btnEnabled); m_options = options; m_optionsDlgTitle = dlgTitle; pack(); } void init(String btnText, boolean btnEnabled) { m_btnOptions.setText(btnText); m_btnOptions.setEnabled(btnEnabled); } List<TagValue> options() { return m_options; } public boolean ignoreSize() { return m_historicalDataDlg.ignoreSize(); } public int numberOfTicks() { return m_historicalDataDlg.numberOfTicks(); } public String startDateTime() { return m_historicalDataDlg.startTime(); } String backfillEndTime() { return m_historicalDataDlg.backfillEndTime(); } String backfillDuration() { return m_historicalDataDlg.backfillDuration(); } String barSizeSetting() { return m_historicalDataDlg.barSizeSetting(); } int useRTH() { return m_historicalDataDlg.useRTH() ? 1 : 0; } int formatDate() { return m_historicalDataDlg.formatDate(); } String whatToShow() { return m_historicalDataDlg.whatToshow(); } boolean keepUpToDate() { return m_historicalDataDlg.keepUpToDate(); } public Contract contract() { return m_contract; } public int id() { return m_id; } String tickByTickType() { return m_historicalDataDlg.tickByTickType(); } boolean isSmartDepth() { return m_smartDepth.isSelected(); } }
[ "matan.bakshi@gmail.com" ]
matan.bakshi@gmail.com
be919b6deb19f7367e24fa7d7d9ad468ef1b612f
b3852b10819bb06f65fbe9130ed379b4ddbe254f
/newrmov.all/src/main/java/cn/bonoon/controllers/newrural/AdministrationRuralEditorNoCore.java
b0e15bd7cbaba0cf9d948ebacf25cac088783b1e
[]
no_license
wap5259177/Project_Fruit_Slayer
19fc4d9f31179ff90d9ecb58db0a78abfd1fbf71
e02d0f3271bda1be682dc111dafd44b84925e9af
refs/heads/master
2020-12-03T00:42:27.508468
2017-08-04T09:06:41
2017-08-04T09:06:50
96,066,028
0
1
null
null
null
null
UTF-8
Java
false
false
1,164
java
package cn.bonoon.controllers.newrural; import cn.bonoon.kernel.annotations.Transform; import cn.bonoon.kernel.web.EmbedType; import cn.bonoon.kernel.web.annotations.DialogDefaultButton; import cn.bonoon.kernel.web.annotations.WithDialog; import cn.bonoon.kernel.web.annotations.form.FormEditor; import cn.bonoon.kernel.web.annotations.form.HasFile; import cn.bonoon.kernel.web.annotations.form.InsertCell; @Transform @InsertCell(value = "applicant/administrationrural-uncore-editor.vm", type = EmbedType.PARSE) @DialogDefaultButton(buttonName = "暂存(未确认)", functionBody = "_checkNumber();", otherButtonName = "确认", otherParameterName = "applicant-submit", otherParameterValue = "true", otherFunctionBody = "if(!confirm('确认后示范片区信息才可以提交,是否确认?')){return false;}_checkNumber();") @WithDialog(initializer = AdministrationRuralEditorInitializerNoCore.class) @FormEditor(width = 620) @HasFile public class AdministrationRuralEditorNoCore extends AdministrationRuralDetailNoCore { /** * */ private static final long serialVersionUID = -498874489390952739L; /** * */ }
[ "1426256791@qq.com" ]
1426256791@qq.com
ad96229a0fad47e92a390e3dd9256f417b4fb90c
3ff80b2b9357f5d30406b5e8b0ee5920dfb940ad
/JavawebDemo/src/com/hsz/web/servlet/DelUserServlet.java
c6d89c90b9d6319acb2ed2ba161840db3d2b6983
[]
no_license
hu102354/javaweb
e822d119cdf234898a3992c415d5723049c6bfc9
11284b36b8de89d52a8bd280a83ce184b8288183
refs/heads/master
2022-04-22T06:05:30.454781
2020-04-17T10:09:53
2020-04-17T10:09:53
255,612,005
1
0
null
null
null
null
UTF-8
Java
false
false
1,070
java
package com.hsz.web.servlet; import com.hsz.service.UserService; import com.hsz.service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/delUserServlet") public class DelUserServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取id String id = request.getParameter("id"); //调用service删除 UserService service = new UserServiceImpl(); service.deleteUser(id); //跳转到查询所有Servlet response.sendRedirect(request.getContextPath()+"/findUserByPageServlet"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
[ "noreply@github.com" ]
noreply@github.com
463b3503413ae43f484c6f79123214462227ba02
863b37cdd2d42b6a376dee3ed9151d4ca4306aa4
/src/main/java/exchanges/Binance.java
66b5e576b012f018d71a72d143ed373e11776c8c
[]
no_license
Wandeson/DW
85263995110e29f72ebdef23c9cd8a02f53a9b2d
0d8f632359b44647f1ad4548d7ab08854418a372
refs/heads/master
2020-03-21T06:30:30.743257
2018-06-21T21:49:43
2018-06-21T21:49:43
138,224,952
0
0
null
null
null
null
UTF-8
Java
false
false
1,622
java
package exchanges; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; import enuns.EnumExchange; import model.Cotacao; import model.Exchange; import model.Moeda; import reflection.ExchangeAnnotation; import webService.ConsumerThread; import webService.ExchangeInterface; @ExchangeAnnotation public class Binance extends Exchange implements ExchangeInterface { private static final long serialVersionUID = 1L; private ConsumerThread consumidor; private ObjectMapper mapper; private String cotacao; public Binance() { super(); enumExchange = EnumExchange.BINANCE; mapper = new ObjectMapper(); consumidor = new ConsumerThread("https://api.binance.com/api/v3/ticker/price", 5000, null); consumidor.start(); } public ConsumerThread getConsumidor() { return consumidor; } public void setConsumidor(ConsumerThread consumidor) { this.consumidor = consumidor; } @Override public void convertJsonTicker() { try { cotacao = consumidor.getCotacoes(); cotacao = cotacao.replace("price", "price_btc"); cotacoes = mapper.readValue(cotacao, mapper.getTypeFactory().constructCollectionType(List.class, Cotacao.class)); } catch (Exception e) { e.printStackTrace(); } } @Override public List<Cotacao> getVolume(Moeda moeda1, Moeda moeda2) { // TODO Auto-generated method stub return null; } @Override public void convertJsonVolume() { // TODO Auto-generated method stub } @Override public List<Cotacao> getTicket() { convertJsonTicker(); return cotacoes; } }
[ "Wandy@DESKTOP-05KF7F4" ]
Wandy@DESKTOP-05KF7F4
e276ec687b82641d28829669ec0cf1ed4f5315f1
cd401ddf5b8dec25a19aceed05cf83543a368d11
/Baekjoon/Main_연구소3.java
d945fbd66c91510f297861936a7f63cc9d262afc
[]
no_license
Jaewoo-Lee/Algorithm
d692eed8c7107ff93bea3fbda9c16b35086a2c9c
09233941e8b7da1317d28d657fbfc5bce175b6d7
refs/heads/master
2022-03-06T18:40:31.151361
2019-11-21T07:42:57
2019-11-21T07:42:57
208,998,613
0
0
null
null
null
null
UHC
Java
false
false
3,037
java
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main_연구소3 { static int[][] map; static int n, m; static boolean[][] active; // 활성화 되었는가 static int[][] mlist; // 바이러스가 올 수 있는 위치 리스트 static int idx; static int[] clist; // 초기에 활성화된 바이러스 리스트 static int minn; // minimum public static void main(String[] args) { Scanner s = new Scanner(System.in); n = s.nextInt(); m = s.nextInt(); map = new int[n][n]; mlist = new int[10][2]; idx = -1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int temp = s.nextInt(); map[i][j] = temp; if(temp == 2) { mlist[++idx][0] = i; mlist[idx][1] = j; } } } // input end minn = n*n; stmin = n*n; // static min : answer // combination clist = new int[m]; combi(m, 0, -1); if(stmin == n*n) stmin = -1; System.out.println(stmin); } static int stmin; static Queue<ver> que; public static void combi(int total, int chosen, int current) { if(total == chosen) { active = new boolean[n][n]; que = new LinkedList(); // for (int i = 0; i <= idx; i++) { // active[mlist[i][0]][mlist[i][1]] = true; // } // for (int i = 0; i < m; i++) { active[mlist[clist[i]][0]][mlist[clist[i]][1]] = true; que.add(new ver(mlist[clist[i]][0], mlist[clist[i]][1], 0)); } int curMin = defusion(); // current minimum // System.out.println(curMin); if(curMin< stmin) stmin = curMin; return; } for (int i = current+1; i <= idx; i++) { clist[chosen] = i; combi(total, chosen+1, i); } } public static int defusion() { int time = 0; // int[][] mmm = new int[n][n]; while(!que.isEmpty() && time <= minn) { int i = que.peek().x; int j = que.peek().y; int ti = que.peek().t; que.poll(); // System.out.println("======================"); // for (int k = 0; k < n; k++) { // for (int k2 = 0; k2 < n; k2++) { // System.out.print(mmm[k][k2]+" "); // } // System.out.println(); // } for (int k = 0; k < 4; k++) { int nx = i+dx[k]; int ny = j+dy[k]; if(nx < 0 || nx >= n) continue; if(ny < 0 || ny >= n) continue; if(map[nx][ny] == 1) continue; if(active[nx][ny]) continue; if(map[nx][ny] == 2) { active[nx][ny] = true; que.add(new ver(nx, ny, ti+1)); continue; } active[nx][ny] = true; // mmm[nx][ny] = ti+1; que.add(new ver(nx, ny, ti+1)); time=ti+1; } } if(check()) minn = minn>time? time:minn; return minn; } public static boolean check() { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if(!active[i][j] && map[i][j] != 1) return false; } } return true; } static int[] dx = {0,1,0,-1}; static int[] dy = {1,0,-1,0}; } class ver{ int x; int y; int t; public ver(int x, int y, int t) { this.x = x; this.y = y; this.t = t; } }
[ "ashilso29@naver.com" ]
ashilso29@naver.com
6f28a4645939c6674f77803e1e29375dd7453809
d39ccf65250d04d5f7826584a06ee316babb3426
/wb-mmb/wb-mojo/src/main/java/org/ihtsdo/mojo/maven/transform/UniqueWords.java
d1edbee42ecf53be45aab227d2bb53b3fcad8d33
[]
no_license
va-collabnet-archive/workbench
ab4c45504cf751296070cfe423e39d3ef2410287
d57d55cb30172720b9aeeb02032c7d675bda75ae
refs/heads/master
2021-01-10T02:02:09.685099
2012-01-25T19:15:44
2012-01-25T19:15:44
47,691,158
0
0
null
null
null
null
UTF-8
Java
false
false
822
java
/** * Copyright (c) 2009 International Health Terminology Standards Development * Organisation * * 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.ihtsdo.mojo.maven.transform; public class UniqueWords extends ProcessWords { protected void processToken(String t) { addWord(t); } }
[ "wsmoak" ]
wsmoak
e98f702a10585cb53a32dd14da762c3195aeae31
ec35e294d0ddf626d3e5d239c879e566b0815bcf
/src/main/java/com/hoyk138/springboot/config/WebConfig.java
e2acf5a4d136a3d43ac23d2318017ad3e205c5d7
[]
no_license
Hoyk138/springboot-webservice
cbcc050672973e65998978196e810f9d6ccbd021
9524d035d9aa64f870ed0395a04a1f4e83ebc602
refs/heads/master
2023-02-16T15:42:05.165636
2021-01-06T14:12:01
2021-01-06T14:12:01
325,598,167
0
0
null
null
null
null
UTF-8
Java
false
false
725
java
package com.hoyk138.springboot.config; import com.hoyk138.springboot.config.auth.LoginUserArgumentResolver; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Configuration; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; @RequiredArgsConstructor @Configuration public class WebConfig implements WebMvcConfigurer { private final LoginUserArgumentResolver loginUserArgumentResolver; @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { argumentResolvers.add(loginUserArgumentResolver); } }
[ "hoyk138@gmail.com" ]
hoyk138@gmail.com
e24a99176980b6c04ddaee26747462334ac01679
5384310d4925972ea6e2e48f270a4f4deb98d4e1
/src/main/java/yahooData/data/repositories/MongoAccountRepository.java
ea9ef3300dd35bb9e467461a3351152214cf4acf
[]
no_license
YanZhenLin/yahooData
39e088687d4e2ef7dae7250858d2b7542974b205
1551ba8d2bf95dd8186de77d9180c959d13aa1ab
refs/heads/master
2020-12-25T15:17:56.736343
2016-07-18T23:54:38
2016-07-18T23:54:38
63,538,301
0
0
null
null
null
null
UTF-8
Java
false
false
482
java
package yahooData.data.repositories; import org.springframework.data.mongodb.repository.MongoRepository; import yahooData.data.entities.Account; /* * important usage notes: * By extending MongoRepository, we are using Spring Data's automatic generation through its * We don't need to declare this interface as a component, when we * */ public interface MongoAccountRepository extends MongoRepository<Account, String> { public Account findByUsername(String username); }
[ "yanznln@gmail.com" ]
yanznln@gmail.com
93054e089923c5cf84f9a903f750204d6bf74196
2966a91e78cef70275f90f5cd9d0eec174430934
/src/seventh/until/ATMButton.java
5166add4c34c86b485478779def54aafed96b428
[]
no_license
309ATM/CCB_ATM
287cf11f7949e28d7963df55cecb35eca7c735ac
a180510c2f52d64591048aa5e54c04fc0ba98d7b
refs/heads/master
2020-03-07T02:39:50.261106
2018-04-22T09:19:12
2018-04-22T09:19:12
127,213,699
1
0
null
null
null
null
GB18030
Java
false
false
2,901
java
package seventh.until; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.geom.RoundRectangle2D; import javax.swing.JButton; /** * 自定义Button类 * */ @SuppressWarnings("serial") public class ATMButton extends JButton { /* 决定圆角的弧度 */ public static int radius = 30; /* 灰白 */ public static Color COLOR1 = new Color(250, 250, 250); public static Color COLOR2 = new Color(197, 197, 197); /* 光标进入按钮判断 */ private boolean hover; public ATMButton(String name) { super.setText(name); paintcolor(COLOR1, COLOR2); } private void paintcolor(Color COLOR1, Color COLOR2) { setMargin(new Insets(0, 0, 0, 0)); setFont(new Font("微软雅黑", Font.PLAIN, 24)); setBorderPainted(false); setForeground(Color.black); setFocusPainted(false); setContentAreaFilled(false); addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { hover = true; repaint(); } @Override public void mouseExited(MouseEvent e) { hover = false; repaint(); } }); } @Override protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g.create(); int height = getHeight(); int with = getWidth(); float tran = 0.95F; if (!hover) {/* 鼠标离开/进入时的透明度改变量 */ tran = 1F; } g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); /* GradientPaint是颜色渐变类 */ GradientPaint p1; GradientPaint p2; if (getModel().isPressed()) { p1 = new GradientPaint(0, 0, new Color(0, 0, 0), 0, height, new Color(100, 100, 100), true); p2 = new GradientPaint(0, 1, new Color(0, 0, 0, 50), 0, height, new Color(255, 255, 255, 100), true); } else { p1 = new GradientPaint(0, 0, new Color(100, 100, 100), 0, height, new Color(0, 0, 0), true); p2 = new GradientPaint(0, 1, new Color(255, 255, 255, 100), 0, height, new Color(0, 0, 0, 50), true); } g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, tran)); RoundRectangle2D.Float r2d = new RoundRectangle2D.Float(0, 0, with - 1, height - 1, radius, radius); // 最后两个参数数值越大,按钮越圆,以下同理 Shape clip = g2d.getClip(); g2d.clip(r2d); GradientPaint gp = new GradientPaint(0.0F, 0.0F, COLOR1, 0.0F, height / 2, COLOR2, true); g2d.setPaint(gp); g2d.fillRect(0, 0, with, height); g2d.setClip(clip); g2d.setPaint(p1); g2d.drawRoundRect(0, 0, with - 3, height - 3, radius, radius); g2d.setPaint(p2); g2d.drawRoundRect(1, 1, with - 3, height - 3, radius, radius); g2d.dispose(); super.paintComponent(g); } }
[ "1106025235@qq.com" ]
1106025235@qq.com
dc87ee75e23d8c6bac3480ee9d846c66da69629d
111f09d0f3fb7f11f9edba56087728a6d22c0feb
/src/editor/EditorFrame.java
17cb3cda265ff5a8c96ee040921298e31150e796
[]
no_license
BionicRADAR/LambdaCalculusInterpreter
55f498d61e823356699479e9e8931864f54bd1cb
7b9442498bd16a9b0c654b37414f5194c2128193
refs/heads/master
2021-01-21T21:47:14.713412
2018-03-20T18:00:12
2018-03-20T18:00:12
26,162,303
1
0
null
null
null
null
UTF-8
Java
false
false
8,697
java
package editor; import interpreter.Controller; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import javax.swing.AbstractAction; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; public class EditorFrame extends JFrame { private final static String[] CLOSING_OPTIONS = new String[4]; private InterpreterView parentFrame; private JMenuItem runAll; private JTextArea codeTextArea; private Font font; private File currentFile; /** * */ private static final long serialVersionUID = 1L; public EditorFrame() { this(null); } public EditorFrame(InterpreterView parent) { super("Lambda Editor"); parentFrame = parent; this.setBounds(820, 20, 500, 300); font = new Font("Monospaced", Font.PLAIN, 12); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowListener() { @Override public void windowActivated(WindowEvent arg0) {} @Override public void windowClosed(WindowEvent arg0) {} @Override public void windowClosing(WindowEvent arg0) { if (closingFile()) EditorFrame.this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); } @Override public void windowDeactivated(WindowEvent arg0) {} @Override public void windowDeiconified(WindowEvent arg0) {} @Override public void windowIconified(WindowEvent arg0) {} @Override public void windowOpened(WindowEvent arg0) {} }); Container p = this.getContentPane(); p.setLayout(new GridBagLayout()); makeMenu(); makeTextArea(p); currentFile = null; CLOSING_OPTIONS[0] = "Save"; CLOSING_OPTIONS[1] = "Don't Save"; CLOSING_OPTIONS[2] = "Save As"; CLOSING_OPTIONS[3] = "Cancel"; } private void makeMenu() { JMenuBar menuBar = new JMenuBar(); this.setJMenuBar(menuBar); JMenu file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); menuBar.add(file); JMenuItem newClear = new JMenuItem("New", KeyEvent.VK_N); file.add(newClear); newClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (closingFile()) { codeTextArea.setText(""); setCurrentFile(null); } } }); JMenuItem save = new JMenuItem("Save", KeyEvent.VK_S); file.add(save); save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); save.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { save(); } }); JMenuItem saveAs = new JMenuItem("Save As", KeyEvent.VK_A); file.add(saveAs); saveAs.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { saveAs(); } }); JMenuItem load = new JMenuItem("Load", KeyEvent.VK_L); file.add(load); load.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_DOWN_MASK)); load.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { load(); } }); JMenuItem close = new JMenuItem("Close Editor"); file.add(close); close.addActionListener(new CloseListener(this)); JMenu run = new JMenu("Run"); run.setMnemonic(KeyEvent.VK_R); menuBar.add(run); runAll = new JMenuItem("Run All", KeyEvent.VK_A); runAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0)); run.add(runAll); runAll.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { runAll(); } }); } private void makeTextArea(Container p) { GridBagConstraints c = new GridBagConstraints(); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 0; c.gridy = 0; c.fill = GridBagConstraints.BOTH; c.gridwidth = 1; c.gridheight = 1; codeTextArea = new JTextArea(12, 30); codeTextArea.setLineWrap(true); codeTextArea.setFont(font); codeTextArea.setBackground(Color.BLACK); codeTextArea.setForeground(Color.WHITE); codeTextArea.setCaretColor(Color.WHITE); p.add(codeTextArea, c); JScrollPane codeScroll = new JScrollPane(codeTextArea); p.add(codeScroll, c); codeTextArea.getInputMap().put(KeyStroke.getKeyStroke(';'), "putlambda"); codeTextArea.getActionMap().put("putlambda", new LambdaAction(codeTextArea)); } private void runAll() { runAll.setEnabled(false); if (parentFrame == null) { parentFrame = Controller.getInstance().multiLineInterpret(codeTextArea.getText()); } else { Controller.getInstance().multiLineInterpret(codeTextArea.getText(), parentFrame); } runAll.setEnabled(true); } private boolean save() { if (currentFile == null) { return saveAs(); } else { writeTo(currentFile, codeTextArea.getText()); return true; } } private boolean saveAs() { String toOutput = codeTextArea.getText(); JFileChooser chooser = new JFileChooser(); int accept = chooser.showSaveDialog(this); if (accept == JFileChooser.APPROVE_OPTION) { while (chooser.getSelectedFile().exists()) { int confirm = JOptionPane.showConfirmDialog(chooser, "A file by this name already exists. Would you like to replace it?", "File Name Taken", JOptionPane.YES_NO_CANCEL_OPTION); if (confirm == JOptionPane.YES_OPTION) { break; } if (confirm == JOptionPane.NO_OPTION) { accept = chooser.showSaveDialog(this); if (accept != JFileChooser.APPROVE_OPTION) return false; } else if (confirm == JOptionPane.CANCEL_OPTION) { return false; } } writeTo(chooser.getSelectedFile(), toOutput); setCurrentFile(chooser.getSelectedFile()); return true; } return false; } private void writeTo(File outputFile, String toOutput) { Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile))); writer.write(toOutput); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(this, "Error: File not found", "Save Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(this, "Error: I/O error while writing to file", "Save Error", JOptionPane.ERROR_MESSAGE); } finally { try { writer.close(); } catch (IOException e) { //Ignore } } } private void load() { closingFile(); JFileChooser chooser = new JFileChooser(); int accept = chooser.showOpenDialog(this); if (accept == JFileChooser.APPROVE_OPTION) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(chooser.getSelectedFile()))); codeTextArea.setText(""); String line = ""; while ((line = reader.readLine()) != null) { codeTextArea.append(line + "\n"); } } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(this, "Error: File not found", "Load Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(this, "Error: I/O error while reading from file", "Load Error", JOptionPane.ERROR_MESSAGE); } finally { try { reader.close(); } catch (IOException e) { //Ignore } } setCurrentFile(chooser.getSelectedFile()); } } private void setCurrentFile(File newCurrentFile) { currentFile = newCurrentFile; if (newCurrentFile == null) { this.setTitle("Lambda Editor"); } else { this.setTitle("Lambda Editor - " + currentFile.getName()); } } private boolean closingFile() { int option = JOptionPane.showOptionDialog(this, "Do you want to save this work before closing it?", "Closing File", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, CLOSING_OPTIONS, CLOSING_OPTIONS[0]); switch (option) { case 0: return save(); case 1: return true; case 2: return saveAs(); case 3: return false; default: return false; } } }
[ "nathan_or_related@sbcglobal.net" ]
nathan_or_related@sbcglobal.net
158644d0a31f97bd5496630434e28c14547a80a0
07be29bda9386284d3254db4149755a1dfeb0416
/src/com/travel/app/activity/LoginSignupActivity.java
d4cabd27eb477b81b143ed4904ee194737b39b04
[]
no_license
passiondroid/TravelDiary
48ea21d8af5bca9bc54946ea2aef7532c737a38e
ea0b82f168378343040c5b5b0c2caef23a77bf0e
refs/heads/master
2021-01-10T05:22:22.943154
2015-06-01T16:48:39
2015-06-01T16:48:39
36,673,198
0
0
null
null
null
null
UTF-8
Java
false
false
6,629
java
package com.travel.app.activity; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.parse.ParseException; import com.parse.ParseUser; import com.parse.SignUpCallback; import com.travel.app.util.ValidationUtil; public class LoginSignupActivity extends Activity { // Declare Variables Button loginbutton; Button okBtn; String nametxt; String emailtxt; String passwordtxt; String telephonetxt; EditText password; EditText name; EditText email; EditText telephone; TextView error_text; /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Get the view from main.xml setContentView(R.layout.activity_main); // Locate EditTexts in main.xml name = (EditText) findViewById(R.id.name_editText); password = (EditText) findViewById(R.id.password_editText); email = (EditText) findViewById(R.id.email_editText); telephone = (EditText) findViewById(R.id.telephone_editText); error_text = (TextView)findViewById(R.id.error_text); // Locate Buttons in main.xml okBtn = (Button) findViewById(R.id.okBtn); // Login Button Click Listener /*loginbutton.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { if(checkAllFieldsAreValid()){ // Retrieve the text entered from the EditText usernametxt = username.getText().toString(); passwordtxt = password.getText().toString(); // Send data to Parse.com for verification ParseUser.logInInBackground(usernametxt, passwordtxt,new LogInCallback() { public void done(ParseUser user, ParseException e) { if (user != null) { // If user exist and authenticated, send user to Welcome.class Intent intent = new Intent(LoginSignupActivity.this, SecondScreeen.class); startActivity(intent); Toast.makeText(getApplicationContext(),"Successfully Logged in",Toast.LENGTH_LONG).show(); finish(); } else { Log.e("Travel","Exception",e); Toast.makeText(getApplicationContext(),"No such user exist, please signup",Toast.LENGTH_LONG).show(); } } }); } }});*/ // Sign up Button Click Listener okBtn.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { if(checkAllFieldsAreValid()){ // Retrieve the text entered from the EditText emailtxt = email.getText().toString(); passwordtxt = password.getText().toString(); nametxt = name.getText().toString(); telephonetxt = telephone.getText().toString(); // Save new user data into Parse.com Data Storage ParseUser user = new ParseUser(); user.put("name", nametxt); user.put("telephone", telephonetxt); user.setUsername(emailtxt); user.setPassword(passwordtxt); user.setEmail(emailtxt); // Set up a progress dialog final ProgressDialog dlg = new ProgressDialog(LoginSignupActivity.this); dlg.setTitle("Please wait."); dlg.setMessage("Signing up..."); dlg.show(); user.signUpInBackground(new SignUpCallback() { public void done(ParseException e) { if (e == null) { // Show a simple Toast message upon successful registration dlg.dismiss(); Toast.makeText(getApplicationContext(),"Successfully Signed up.",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(LoginSignupActivity.this, SecondScreeen.class); startActivity(intent); finish(); } else { switch(e.getCode()){ case ParseException.USERNAME_TAKEN: error_text.setText("Sorry, this email id already exists."); break; case ParseException.USERNAME_MISSING: error_text.setText("Sorry, you must supply an email id to register."); break; case ParseException.PASSWORD_MISSING: error_text.setText("Sorry, you must supply a password to register."); break; case ParseException.EMAIL_TAKEN: error_text.setText("Sorry, this email id already exists."); break; case ParseException.EMAIL_MISSING: error_text.setText("Sorry, you must supply an email id to register."); break; default: error_text.setText("Something went wrong while registering you. Please try again."); } dlg.dismiss(); error_text.setVisibility(View.VISIBLE); Log.e("Travel","Exception",e); //Toast.makeText(getApplicationContext(),"Sign up Error", Toast.LENGTH_SHORT).show(); } } }); } }}); } private boolean checkAllFieldsAreValid() { if(isOnline()){ EditText nameText=(EditText) findViewById(R.id.name_editText); EditText emailIdText=(EditText) findViewById(R.id.email_editText); EditText passwordText=(EditText) findViewById(R.id.password_editText); EditText telephoneNoText=(EditText) findViewById(R.id.telephone_editText); boolean isNameValid = ValidationUtil.checkValidName(this, nameText); boolean isEmailValid = ValidationUtil.checkValidEmailId(this, emailIdText); boolean isPasswordValid = ValidationUtil.checkValidPasword(this, passwordText); boolean isPhoneValid = ValidationUtil.checkValidPhoneNumber(this, telephoneNoText); if(isNameValid && isEmailValid && isPasswordValid && isPhoneValid){ return true; }else{ return false; } }else{ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.no_internet) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.create().show(); return false; } } public boolean isOnline() { ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } return false; } }
[ "ttalo100@hotmail.com" ]
ttalo100@hotmail.com
f6d73961cd522a6b429d65b6f62edc98423bbc6c
0af8b92686a58eb0b64e319b22411432aca7a8f3
/large-multiproject/project42/src/main/java/org/gradle/test/performance42_4/Production42_384.java
e61aed17b174b3262434a5be507bb15d839bf769
[]
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
305
java
package org.gradle.test.performance42_4; public class Production42_384 extends org.gradle.test.performance14_4.Production14_384 { private final String property; public Production42_384() { this.property = "foo"; } public String getProperty() { return property; } }
[ "cedric.champeau@gmail.com" ]
cedric.champeau@gmail.com
3e3b957eec5add78ba08f3ba4febd598761ec7c6
b06143d70c2733ea40a7f68280a60dfba58a198e
/app/src/main/java/com/developer/manuelquinteros/legalsv/adapter/ConstitutionsRecyclerViewAdapter.java
53d8e8a0e759b6a5890f56c6787611771b830c5b
[]
no_license
manuelquinterosh/LegalSV
9c2c7336b68a4ccfc251a9f9e42483ed7e9a02a4
d2403a788555b0344a4d4eb51f314f500c58f616
refs/heads/master
2020-04-29T11:01:44.300274
2019-03-29T02:41:42
2019-03-29T02:41:42
170,629,845
0
0
null
null
null
null
UTF-8
Java
false
false
4,049
java
package com.developer.manuelquinteros.legalsv.adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.developer.manuelquinteros.legalsv.CustomItemClickListener; import com.developer.manuelquinteros.legalsv.Model.Menu; import com.developer.manuelquinteros.legalsv.R; import java.util.List; public class ConstitutionsRecyclerViewAdapter extends RecyclerView.Adapter<ConstitutionsRecyclerViewAdapter.MyViewHolder> { private Context mContext; private List<Menu> mItems; private CustomItemClickListener mClickListener; public ConstitutionsRecyclerViewAdapter(Context context, List<Menu> items, CustomItemClickListener clickListener) { mContext = context; mItems = items; mClickListener = clickListener; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { final View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardview_item, viewGroup, false); final ConstitutionsRecyclerViewAdapter.MyViewHolder holder = new ConstitutionsRecyclerViewAdapter.MyViewHolder(view); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mClickListener.onItemClick(view, holder.getPosition()); } }); return holder; } @Override public void onBindViewHolder(@NonNull final MyViewHolder myViewHolder, int i) { myViewHolder.title.setText(mItems.get(i).getTitle()); myViewHolder.subtitle.setText(mItems.get(i).getSubtitle()); Glide.with(mContext) .asBitmap() .load(mItems.get(i).getUrl()) .into(myViewHolder.url_img); myViewHolder.overflow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPopupMenu(myViewHolder.overflow); } }); } private void showPopupMenu(View view) { //Inflate menu PopupMenu popup = new PopupMenu(mContext, view); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.menu_constitutions, popup.getMenu()); popup.setOnMenuItemClickListener(new ConstitutionsRecyclerViewAdapter.MyMenuItemClickListener()); popup.show(); } class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener { public MyMenuItemClickListener() { } @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.action_agregar_favoritos: Toast.makeText(mContext, "Agregar a Favoritos", Toast.LENGTH_SHORT).show(); return true; case R.id.action_ver_descripcion: Toast.makeText(mContext, "Ver Descripcion", Toast.LENGTH_SHORT).show(); return true; default: } return false; } } @Override public int getItemCount() { return mItems.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { TextView title, subtitle; ImageView url_img, overflow; public MyViewHolder(View itemView) { super(itemView); overflow = itemView.findViewById(R.id.overflow); url_img = itemView.findViewById(R.id.imageView); title = itemView.findViewById(R.id.titleCard); subtitle = itemView.findViewById(R.id.subtitleCard); itemView.setClickable(true); } } }
[ "manuelq_hernandez@outlook.com" ]
manuelq_hernandez@outlook.com
b9960da28fa845d0bda4cd4a2a9c915991484b5c
75fe2b5e986f11373006275ffef92c3a36cd2cb4
/springBoot/afterEnd/dzw/src/main/java/com/accp/service/ManufacturerServie.java
166aff4a23e41e8d6f13e2fabea23dd949ec03b3
[]
no_license
zjia-0/NothingMeaningful
d71c64f4918d4f1fe5ec8f5f6d8967637dbcc802
c9fda9989d80c866a5b90ee9ae123bb1af7d76af
refs/heads/master
2022-07-14T05:24:02.142620
2020-03-01T14:32:24
2020-03-01T14:32:24
233,246,885
0
0
null
null
null
null
UTF-8
Java
false
false
546
java
package com.accp.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.accp.domain.Manufacturer; import com.accp.mapper.ManufacturerMapper; @Service @Transactional public class ManufacturerServie { @Autowired ManufacturerMapper manufacturerMapper; public List<Manufacturer> manufacturersel(){ return manufacturerMapper.selectByExample(null); } }
[ "318276717@qq.com" ]
318276717@qq.com
87233a175b3bf5abc6aa45bd08d0f05b6e43fe98
63d736d2a4306c7993bae31fdb00a7ae03ea8abb
/event-driven-architecture-pattern/src/main/java/com/mjduan/project/src/framework/IEvent.java
91d1f844df4a3b8767717bfcb29159334e50491c
[]
no_license
MingJunDuan/Java-design-pattern
a9304e11a0e48f5ff82a4fd94e4d6d5ea3a4a88b
9c4992f5dd38a036f074c47f8f6aee8af85959ce
refs/heads/master
2020-12-03T03:44:59.185802
2017-09-06T02:57:59
2017-09-06T02:57:59
95,768,072
1
0
null
null
null
null
UTF-8
Java
false
false
145
java
package com.mjduan.project.src.framework; /** * Hans 2017-07-03 18:31 */ public interface IEvent { Class<? extends IEvent> getType(); }
[ "mjduan@yahoo.com" ]
mjduan@yahoo.com
d6295f873c5a84fc0ffa5ce19b150c0ae06ec897
68b13d4b57cb3921f40d177738cceae9ada69461
/src/main/java/com/dpnice/iot/tutu/config/jwt/JwtAuthenticationEntryPoint.java
19cdb9999d62ed045bcd4e148db2f827b4688456
[]
no_license
pschen/tutu-iot
4035e2c7ddb61324dcfa2c96b0577a273e7abdfa
467d8b830fa2827da368b35fecd792ea50da63f0
refs/heads/master
2022-03-24T10:09:07.824467
2019-12-31T16:53:48
2019-12-31T16:53:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,041
java
package com.dpnice.iot.tutu.config.jwt; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { // This is invoked when user tries to access a secured REST resource without supplying any credentials // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to // Here you can place any message you want response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()+" " + "身份验证失败"); } }
[ "ruopeng.zhang@outlook.com" ]
ruopeng.zhang@outlook.com
af42d3caee709f6d48ea5f885c66cd9a4c4817a6
f2671d48696ec14590d7306f9f53207366ba631d
/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/startree/v2/store/StarTreeDataSource.java
0b9df12864870619970b3c909cc5e69bed7c580c
[ "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LGPL-2.0-or-later", "LicenseRef-scancode-unicode", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown-license-reference", "NAIST-2003", "bzip2-1.0.6", "OpenSSL", "CC-BY-2.5", "CC-BY-SA-3.0", "CDDL-1.0", "MIT", "CPL-1.0", "LicenseRef-scancode-public-domain", "CDDL-1.1", "EPL-1.0", "CC-BY-4.0", "WTFPL", "EPL-2.0", "ISC", "BSD-2-Clause" ]
permissive
mcvsubbu/incubator-pinot
5602f1bc925aec6f400f93f53915d1ca10d1f217
dc3b6fd3192b9301017e91a564241479e67727b9
refs/heads/master
2023-07-13T13:34:05.824578
2023-05-14T01:28:55
2023-05-14T01:28:55
175,093,979
2
0
Apache-2.0
2019-03-11T22:33:11
2019-03-11T22:33:11
null
UTF-8
Java
false
false
3,053
java
/** * 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.pinot.segment.local.startree.v2.store; import java.util.Set; import javax.annotation.Nullable; import org.apache.pinot.segment.local.segment.index.datasource.BaseDataSource; import org.apache.pinot.segment.spi.datasource.DataSourceMetadata; import org.apache.pinot.segment.spi.index.StandardIndexes; import org.apache.pinot.segment.spi.index.column.ColumnIndexContainer; import org.apache.pinot.segment.spi.index.reader.Dictionary; import org.apache.pinot.segment.spi.index.reader.ForwardIndexReader; import org.apache.pinot.segment.spi.partition.PartitionFunction; import org.apache.pinot.spi.data.FieldSpec; public class StarTreeDataSource extends BaseDataSource { public StarTreeDataSource(FieldSpec fieldSpec, int numDocs, ForwardIndexReader<?> forwardIndex, @Nullable Dictionary dictionary) { super( new StarTreeDataSourceMetadata(fieldSpec, numDocs), new ColumnIndexContainer.FromMap.Builder() .with(StandardIndexes.forward(), forwardIndex) .with(StandardIndexes.dictionary(), dictionary) .build()); } private static final class StarTreeDataSourceMetadata implements DataSourceMetadata { private final FieldSpec _fieldSpec; private final int _numDocs; StarTreeDataSourceMetadata(FieldSpec fieldSpec, int numDocs) { _fieldSpec = fieldSpec; _numDocs = numDocs; } @Override public FieldSpec getFieldSpec() { return _fieldSpec; } @Override public boolean isSorted() { return false; } @Override public int getNumDocs() { return _numDocs; } @Override public int getNumValues() { return _numDocs; } @Override public int getMaxNumValuesPerMVEntry() { return -1; } @Nullable @Override public Comparable getMinValue() { return null; } @Nullable @Override public Comparable getMaxValue() { return null; } @Nullable @Override public PartitionFunction getPartitionFunction() { return null; } @Nullable @Override public Set<Integer> getPartitions() { return null; } @Override public int getCardinality() { return -1; } } }
[ "noreply@github.com" ]
noreply@github.com
bd0fa1696781e05a7668f12c07a707ac3c42da60
a9e5371b321647ea4fbc7a37b1a35646b1b2daba
/src/com/iutorleans/bank/adapter/CompteCrudAdapter.java
7cee4287241093aa5e3b134b97d05c9d3442ae26
[]
no_license
Naijing/BankApp_Android
e94514d50673abfe48dd673b7fc16284b69145df
98ed655c2d408782920224ba8a34ed427d4e02b8
refs/heads/master
2021-01-22T03:23:28.115962
2017-02-06T19:11:48
2017-02-06T19:11:48
81,121,655
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
2,995
java
package com.iutorleans.bank.adapter; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.iutorleans.bank.R; import com.iutorleans.bank.bean.ComptesBean; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; public class CompteCrudAdapter extends BaseAdapter { private ArrayList<ComptesBean> list; private ArrayList<ComptesBean> listComptesChecked = new ArrayList<ComptesBean>() ; private Context context; Map<Integer, Boolean> isCheckMap = new HashMap<Integer, Boolean>(); public CompteCrudAdapter(Context context, ArrayList<ComptesBean> list) { this.list = list; this.context = context; } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; if (convertView != null) { view = convertView; } else { view = View.inflate(context, R.layout.item_comptes_checkbox_layout, null); } TextView item_tv_nom = (TextView) view .findViewById(R.id.item_tv_crud_nom); TextView item_tv_solde = (TextView) view .findViewById(R.id.item_tv_crud_solde); TextView item_tv_crud_id = (TextView) view .findViewById(R.id.item_tv_crud_id); CheckBox item_tv_crud_checkBox = (CheckBox) view .findViewById(R.id.item_tv_crud_checkBox); ComptesBean comptesBean = list.get(position); item_tv_nom.setText(comptesBean.nom); item_tv_solde.setText(comptesBean.solde + ""); item_tv_crud_id.setText("N°"+comptesBean.id); item_tv_crud_checkBox.setTag(position); if (isCheckMap != null && isCheckMap.containsKey(position)) { item_tv_crud_checkBox.setChecked(isCheckMap.get(position)); } else { item_tv_crud_checkBox.setChecked(false); } item_tv_crud_checkBox .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int checkBoxId = Integer.parseInt(buttonView.getTag() .toString()); if (isChecked) { System.out.println(list.get(checkBoxId).nom); listComptesChecked.add(list.get(checkBoxId)); isCheckMap.put(checkBoxId, isChecked); // System.out.println("on"+checkBoxId); } else { // System.out.println("off"+checkBoxId); listComptesChecked.remove(list.get(checkBoxId)); isCheckMap.remove(checkBoxId); } } }); return view; } public ArrayList<ComptesBean> getListComptesChecked() { return listComptesChecked; } }
[ "wangxiao8808@hotmail.com" ]
wangxiao8808@hotmail.com
b46b9a526e2d200dddb6b4e24d03faaaa92ddeb0
5010ca4b276d23cc627ae4db81089393077e39ec
/src/main/java/top/kuangcp/graduate/domain/TopicFile.java
68f90d9542870c3e62508cb03abaaf60ec3f5aa0
[ "Apache-2.0" ]
permissive
andersJava/Graduate
a8fcb080e3123fa3198f2d253aee6df8bede487d
9fd9dbb308d74472e69d83a0a3825896f928dbae
refs/heads/master
2020-06-11T20:06:49.737562
2018-09-02T15:02:41
2018-09-02T15:02:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
435
java
package top.kuangcp.graduate.domain; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * Created by https://github.com/kuangcp * * @author kuangcp * @date 18-5-9 下午12:34 */ @Data @Entity public class TopicFile { @Id @GeneratedValue private Long fileId; private String path; private Long topicId; private Integer batch; }
[ "kuangcp@aliyun.com" ]
kuangcp@aliyun.com
58bbadbdbe22f048e832027218067991728ad191
4bbaf61bab08723313d802e22b9b36c4370fa305
/OrEcli/src/TestUDP.java
ba532ca96067b4c5fd809dda912321b0fd50d404
[]
no_license
dennislao93/oriecli
347a8472fc258946dcb596da8ad5e5e7721ba4f7
174c3fa44a8443a4921cd6eca7cca925572d3783
refs/heads/master
2021-01-01T05:48:25.922462
2014-05-02T15:37:33
2014-05-02T15:37:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,351
java
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Scanner; public class TestUDP { public static void main(String[] args) { TestUDP test = new TestUDP(); if (args[0].equals("s")) { test.execute('s'); } else if (args[0].equals("c")) { test.execute('c'); } } public void execute(char c) { if (c == 's') { new ServerThread().start(); } else { new ClientThread().start(); } } public class ServerThread extends Thread { @Override public void run() { DatagramSocket socket; DatagramPacket packet; try { socket = new DatagramSocket(5822); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } byte[] b; String msg; boolean run = true; while (run) { try { b = new byte[32]; packet = new DatagramPacket(b, b.length); socket.receive(packet); byte[] bytes = packet.getData(); msg = new String(bytes); System.out.println("Length:" + msg.length() + ", num bytes: " + bytes.length); System.out.println(msg); System.out.println(new Integer(msg.charAt(29))); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); break; } if (msg.trim().equals("stop")) { run = false; } } } } public class ClientThread extends Thread { @Override public void run() { DatagramSocket socket; DatagramPacket packet; try { socket = new DatagramSocket(5823); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } byte[] b; Scanner in = new Scanner(System.in); boolean run = true; String msg; while (run) { msg = in.nextLine(); b = msg.getBytes(); try { packet = new DatagramPacket(b, b.length, InetAddress.getByName("localhost"), 5822); } catch (UnknownHostException e1) { // TODO Auto-generated catch block e1.printStackTrace(); break; } try { socket.send(packet); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); break; } if (msg.equals("stop")) { run = false; } } } } }
[ "dennislao93@yahoo.com" ]
dennislao93@yahoo.com
0d5187db77d96b8e5fb7c5078daa968794070b6c
53a4d554ae2d93aa2bfe3f9683af8e1413824a02
/src/main/java/org/djd/fun/taiga/resource/StationsResource.java
aaf946ba6e412ddd4d2446321eff226c7a4082f8
[]
no_license
do-i/heroku-ninja
77e1214466694054df3a77cb87e79a7b8d2271fd
4e82a759679034cc2fc75e1a8c3f90cfefedf575
refs/heads/master
2021-01-22T22:53:34.352535
2012-11-02T00:49:14
2012-11-02T00:49:14
6,151,884
0
1
null
null
null
null
UTF-8
Java
false
false
2,357
java
package org.djd.fun.taiga.resource; import com.sun.jersey.api.NotFoundException; import org.djd.fun.taiga.model.CtaStopsModel; import org.djd.fun.taiga.model.CuteResponse; import org.djd.fun.taiga.model.StationsOrderedModel; import org.djd.fun.taiga.service.CtaLStopsService; import org.djd.fun.taiga.service.ServiceException; import org.djd.fun.taiga.service.StationsService; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import java.util.List; import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; /** * TODO add authentication mechanism to @POST method */ @Path("/stations") @Produces({MediaType.APPLICATION_JSON}) public class StationsResource { private final StationsService stationsService; public StationsResource() { this(new StationsService()); } /** * for unit test * * @param stationsService */ public StationsResource(StationsService stationsService) { this.stationsService = stationsService; } @POST public CuteResponse seed() { try { stationsService.seed(); return new CuteResponse.Builder().statusCode(200).message("Database was successfully seeded.") .build(); } catch (ServiceException e) { throw new WebApplicationException(INTERNAL_SERVER_ERROR); } } @GET public List<StationsOrderedModel> fetchAll() { try { return stationsService.fetch(); } catch (ServiceException e) { throw new NotFoundException("Could not find any stations."); } } @GET @Path("/{color:\\w+}") public List<StationsOrderedModel> fetchByColor(@PathParam("color") String color) { try { return stationsService.fetchByColor(color); } catch (ServiceException e) { throw new NotFoundException("Could not find any stations."); } } @GET @Path("/{color:\\w+}/{destination:\\w+}") public List<StationsOrderedModel> fetchByColorAndDestination( @PathParam("color") String color, @PathParam("destination") String destination) { try { return stationsService.fetchByColorAndDestination(color, destination); } catch (ServiceException e) { throw new NotFoundException("Could not find any stations."); } } }
[ "lupin@myway.com" ]
lupin@myway.com
2dc18011c717e5338e35801a6855dd51d8a1c2c2
fda74cfffb9a26ea62183475981c640f484909e5
/src/main/java/oneric/mnc/blocks/BlockBigMushTop.java
8ddcfa7f32e41c6534ca3fdeed5efefed9745157
[]
no_license
TheOneric/UNM
7dc24137ac22a5019c824596d0f92f5a3de90d01
87183dbdadc0f86fa80bc1fc6f63a2e274d7bd6e
refs/heads/master
2020-07-18T02:42:47.577047
2020-05-13T18:49:45
2020-05-13T18:49:45
67,285,481
1
0
null
2016-09-03T11:32:57
2016-09-03T10:54:02
Java
UTF-8
Java
false
false
7,389
java
package oneric.mnc.blocks; import net.minecraft.block.BlockHugeMushroom; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.IStringSerializable; import net.minecraft.util.Mirror; import net.minecraft.util.Rotation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; public class BlockBigMushTop extends MNCBlock { public static final PropertyEnum<BlockBigMushTop.EnumType> VARIANT = PropertyEnum.<BlockBigMushTop.EnumType>create("variant", BlockBigMushTop.EnumType.class); public BlockBigMushTop(String name) { super(Material.WOOD, SoundType.WOOD, name); this.setDefaultState(blockState.getBaseState().withProperty(VARIANT, EnumType.ALL_OUTSIDE)); } @Override public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { return new ItemStack(this, 1, 0); //return super.getPickBlock(state, target, world, pos, player); } @Override public IBlockState getStateFromMeta(int meta) { return this.getDefaultState().withProperty(VARIANT, BlockBigMushTop.EnumType.byMetadata(meta)); } @Override public int getMetaFromState(IBlockState state) { return state.getValue(VARIANT).getMetadata(); } @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, new IProperty[] {VARIANT}); } @Override public IBlockState withRotation(IBlockState state, Rotation rot) { BlockBigMushTop.EnumType variant = state.getValue(VARIANT); switch(rot) { case CLOCKWISE_180: switch(variant) { case EAST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.WEST); case NORTH: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.SOUTH); case NORTH_EAST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.SOUTH_WEST); case NORTH_WEST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.SOUTH_EAST); case SOUTH: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.NORTH); case SOUTH_EAST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.NORTH_WEST); case SOUTH_WEST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.NORTH_EAST); case WEST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.EAST); default: break; } //break; Redundant case CLOCKWISE_90: switch(variant) { case EAST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.SOUTH); case NORTH: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.EAST); case NORTH_EAST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.SOUTH_EAST); case NORTH_WEST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.NORTH_EAST); case SOUTH: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.WEST); case SOUTH_EAST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.SOUTH_WEST); case SOUTH_WEST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.NORTH_WEST); case WEST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.NORTH); default: break; } case COUNTERCLOCKWISE_90: switch(variant) { case EAST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.NORTH); case NORTH: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.WEST); case NORTH_EAST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.NORTH_WEST); case NORTH_WEST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.SOUTH_WEST); case SOUTH: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.EAST); case SOUTH_EAST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.NORTH_EAST); case SOUTH_WEST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.SOUTH_EAST); case WEST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.SOUTH); default: break; } case NONE: break; } return state; } @Override public IBlockState withMirror(IBlockState state, Mirror mirrorIn) { BlockBigMushTop.EnumType variant = state.getValue(VARIANT); switch (mirrorIn) { case FRONT_BACK: switch(variant) { case EAST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.WEST); case WEST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.EAST); case NORTH_EAST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.NORTH_WEST); case NORTH_WEST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.NORTH_EAST); case SOUTH_EAST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.SOUTH_WEST); case SOUTH_WEST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.SOUTH_EAST); default: break; } case LEFT_RIGHT: switch(variant) { case NORTH: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.SOUTH); case SOUTH: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.NORTH); case NORTH_EAST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.SOUTH_EAST); case NORTH_WEST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.SOUTH_WEST); case SOUTH_EAST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.NORTH_EAST); case SOUTH_WEST: return state.withProperty(VARIANT, BlockBigMushTop.EnumType.NORTH_WEST); default: break; } default: break; } return super.withMirror(state, mirrorIn); } public enum EnumType implements IStringSerializable { NORTH_WEST(1, "north_west"), NORTH(2, "north"), NORTH_EAST(3, "north_east"), WEST(4, "west"), CENTER(5, "center"), EAST(6, "east"), SOUTH_WEST(7, "south_west"), SOUTH(8, "south"), SOUTH_EAST(9, "south_east"), ALL_OUTSIDE(0, "all_outside"); private static final EnumType[] metaLookUp = new EnumType[10]; private final int meta; private final String name; private EnumType(int meta, String name) { this.meta = meta; this.name = name; } public int getMetadata() { return this.meta; } public String toString() { return this.name; } public static BlockBigMushTop.EnumType byMetadata(int meta) { if (meta < 0 || meta >= metaLookUp.length) { meta = 0; } BlockBigMushTop.EnumType type = metaLookUp[meta]; return type == null ? metaLookUp[0] : type; } public String getName() { return this.name; } static { for(EnumType vari : values()) { metaLookUp[vari.meta] = vari; } } } }
[ "oneric@oneric.stub" ]
oneric@oneric.stub
015f60a7734042c667fdd8ab0e2b695ff4093480
0581be3ac37f05973c59fb1ac8a0eaeb38a9d01a
/aws-java-sdk-codedeploy/src/main/java/com/amazonaws/services/codedeploy/model/S3Location.java
15dcb3495cf625b262c940da64ce9d2c6cb555b5
[ "Apache-2.0", "JSON" ]
permissive
SoMCUSDev/aws-sdk-java
f0c47a9f9b7b817b95428b486c979fd8e1b49975
3f661541037eae1ba6adda84e9f44309f2502d33
refs/heads/master
2021-01-23T22:12:05.430492
2015-02-25T15:06:53
2015-02-25T15:08:19
31,318,689
0
0
null
2015-02-25T14:58:04
2015-02-25T14:58:04
null
UTF-8
Java
false
false
15,098
java
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.codedeploy.model; import java.io.Serializable; /** * <p> * Information about the location of application artifacts that are * stored in Amazon S3. * </p> */ public class S3Location implements Serializable { /** * The name of the Amazon S3 bucket where the application revision is * stored. */ private String bucket; /** * The name of the Amazon S3 object that represents the bundled artifacts * for the application revision. */ private String key; /** * The file type of the application revision. Must be one of the * following: <ul> <li>tar: A tar archive file.</li> <li>tgz: A * compressed tar archive file.</li> <li>zip: A zip archive file.</li> * </ul> * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>tar, tgz, zip */ private String bundleType; /** * A specific version of the Amazon S3 object that represents the bundled * artifacts for the application revision. <p>If the version is not * specified, the system will use the most recent version by default. */ private String version; /** * The ETag of the Amazon S3 object that represents the bundled artifacts * for the application revision. <p>If the ETag is not specified as an * input parameter, ETag validation of the object will be skipped. */ private String eTag; /** * The name of the Amazon S3 bucket where the application revision is * stored. * * @return The name of the Amazon S3 bucket where the application revision is * stored. */ public String getBucket() { return bucket; } /** * The name of the Amazon S3 bucket where the application revision is * stored. * * @param bucket The name of the Amazon S3 bucket where the application revision is * stored. */ public void setBucket(String bucket) { this.bucket = bucket; } /** * The name of the Amazon S3 bucket where the application revision is * stored. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param bucket The name of the Amazon S3 bucket where the application revision is * stored. * * @return A reference to this updated object so that method calls can be chained * together. */ public S3Location withBucket(String bucket) { this.bucket = bucket; return this; } /** * The name of the Amazon S3 object that represents the bundled artifacts * for the application revision. * * @return The name of the Amazon S3 object that represents the bundled artifacts * for the application revision. */ public String getKey() { return key; } /** * The name of the Amazon S3 object that represents the bundled artifacts * for the application revision. * * @param key The name of the Amazon S3 object that represents the bundled artifacts * for the application revision. */ public void setKey(String key) { this.key = key; } /** * The name of the Amazon S3 object that represents the bundled artifacts * for the application revision. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param key The name of the Amazon S3 object that represents the bundled artifacts * for the application revision. * * @return A reference to this updated object so that method calls can be chained * together. */ public S3Location withKey(String key) { this.key = key; return this; } /** * The file type of the application revision. Must be one of the * following: <ul> <li>tar: A tar archive file.</li> <li>tgz: A * compressed tar archive file.</li> <li>zip: A zip archive file.</li> * </ul> * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>tar, tgz, zip * * @return The file type of the application revision. Must be one of the * following: <ul> <li>tar: A tar archive file.</li> <li>tgz: A * compressed tar archive file.</li> <li>zip: A zip archive file.</li> * </ul> * * @see BundleType */ public String getBundleType() { return bundleType; } /** * The file type of the application revision. Must be one of the * following: <ul> <li>tar: A tar archive file.</li> <li>tgz: A * compressed tar archive file.</li> <li>zip: A zip archive file.</li> * </ul> * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>tar, tgz, zip * * @param bundleType The file type of the application revision. Must be one of the * following: <ul> <li>tar: A tar archive file.</li> <li>tgz: A * compressed tar archive file.</li> <li>zip: A zip archive file.</li> * </ul> * * @see BundleType */ public void setBundleType(String bundleType) { this.bundleType = bundleType; } /** * The file type of the application revision. Must be one of the * following: <ul> <li>tar: A tar archive file.</li> <li>tgz: A * compressed tar archive file.</li> <li>zip: A zip archive file.</li> * </ul> * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>tar, tgz, zip * * @param bundleType The file type of the application revision. Must be one of the * following: <ul> <li>tar: A tar archive file.</li> <li>tgz: A * compressed tar archive file.</li> <li>zip: A zip archive file.</li> * </ul> * * @return A reference to this updated object so that method calls can be chained * together. * * @see BundleType */ public S3Location withBundleType(String bundleType) { this.bundleType = bundleType; return this; } /** * The file type of the application revision. Must be one of the * following: <ul> <li>tar: A tar archive file.</li> <li>tgz: A * compressed tar archive file.</li> <li>zip: A zip archive file.</li> * </ul> * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>tar, tgz, zip * * @param bundleType The file type of the application revision. Must be one of the * following: <ul> <li>tar: A tar archive file.</li> <li>tgz: A * compressed tar archive file.</li> <li>zip: A zip archive file.</li> * </ul> * * @see BundleType */ public void setBundleType(BundleType bundleType) { this.bundleType = bundleType.toString(); } /** * The file type of the application revision. Must be one of the * following: <ul> <li>tar: A tar archive file.</li> <li>tgz: A * compressed tar archive file.</li> <li>zip: A zip archive file.</li> * </ul> * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>tar, tgz, zip * * @param bundleType The file type of the application revision. Must be one of the * following: <ul> <li>tar: A tar archive file.</li> <li>tgz: A * compressed tar archive file.</li> <li>zip: A zip archive file.</li> * </ul> * * @return A reference to this updated object so that method calls can be chained * together. * * @see BundleType */ public S3Location withBundleType(BundleType bundleType) { this.bundleType = bundleType.toString(); return this; } /** * A specific version of the Amazon S3 object that represents the bundled * artifacts for the application revision. <p>If the version is not * specified, the system will use the most recent version by default. * * @return A specific version of the Amazon S3 object that represents the bundled * artifacts for the application revision. <p>If the version is not * specified, the system will use the most recent version by default. */ public String getVersion() { return version; } /** * A specific version of the Amazon S3 object that represents the bundled * artifacts for the application revision. <p>If the version is not * specified, the system will use the most recent version by default. * * @param version A specific version of the Amazon S3 object that represents the bundled * artifacts for the application revision. <p>If the version is not * specified, the system will use the most recent version by default. */ public void setVersion(String version) { this.version = version; } /** * A specific version of the Amazon S3 object that represents the bundled * artifacts for the application revision. <p>If the version is not * specified, the system will use the most recent version by default. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param version A specific version of the Amazon S3 object that represents the bundled * artifacts for the application revision. <p>If the version is not * specified, the system will use the most recent version by default. * * @return A reference to this updated object so that method calls can be chained * together. */ public S3Location withVersion(String version) { this.version = version; return this; } /** * The ETag of the Amazon S3 object that represents the bundled artifacts * for the application revision. <p>If the ETag is not specified as an * input parameter, ETag validation of the object will be skipped. * * @return The ETag of the Amazon S3 object that represents the bundled artifacts * for the application revision. <p>If the ETag is not specified as an * input parameter, ETag validation of the object will be skipped. */ public String getETag() { return eTag; } /** * The ETag of the Amazon S3 object that represents the bundled artifacts * for the application revision. <p>If the ETag is not specified as an * input parameter, ETag validation of the object will be skipped. * * @param eTag The ETag of the Amazon S3 object that represents the bundled artifacts * for the application revision. <p>If the ETag is not specified as an * input parameter, ETag validation of the object will be skipped. */ public void setETag(String eTag) { this.eTag = eTag; } /** * The ETag of the Amazon S3 object that represents the bundled artifacts * for the application revision. <p>If the ETag is not specified as an * input parameter, ETag validation of the object will be skipped. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param eTag The ETag of the Amazon S3 object that represents the bundled artifacts * for the application revision. <p>If the ETag is not specified as an * input parameter, ETag validation of the object will be skipped. * * @return A reference to this updated object so that method calls can be chained * together. */ public S3Location withETag(String eTag) { this.eTag = eTag; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getBucket() != null) sb.append("Bucket: " + getBucket() + ","); if (getKey() != null) sb.append("Key: " + getKey() + ","); if (getBundleType() != null) sb.append("BundleType: " + getBundleType() + ","); if (getVersion() != null) sb.append("Version: " + getVersion() + ","); if (getETag() != null) sb.append("ETag: " + getETag() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getBucket() == null) ? 0 : getBucket().hashCode()); hashCode = prime * hashCode + ((getKey() == null) ? 0 : getKey().hashCode()); hashCode = prime * hashCode + ((getBundleType() == null) ? 0 : getBundleType().hashCode()); hashCode = prime * hashCode + ((getVersion() == null) ? 0 : getVersion().hashCode()); hashCode = prime * hashCode + ((getETag() == null) ? 0 : getETag().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof S3Location == false) return false; S3Location other = (S3Location)obj; if (other.getBucket() == null ^ this.getBucket() == null) return false; if (other.getBucket() != null && other.getBucket().equals(this.getBucket()) == false) return false; if (other.getKey() == null ^ this.getKey() == null) return false; if (other.getKey() != null && other.getKey().equals(this.getKey()) == false) return false; if (other.getBundleType() == null ^ this.getBundleType() == null) return false; if (other.getBundleType() != null && other.getBundleType().equals(this.getBundleType()) == false) return false; if (other.getVersion() == null ^ this.getVersion() == null) return false; if (other.getVersion() != null && other.getVersion().equals(this.getVersion()) == false) return false; if (other.getETag() == null ^ this.getETag() == null) return false; if (other.getETag() != null && other.getETag().equals(this.getETag()) == false) return false; return true; } }
[ "aws@amazon.com" ]
aws@amazon.com
01a80e38cc4554f0f3a632b7b11a4aa65ba96e0d
61064a04318e965ee23237d8b47fa8f757ae25a4
/EntregaFinal5/src/coolc/Coolc.java
45030ff8881ea2763105d25b998b7c071cbb903a
[]
no_license
NeoRichard/compi
3bb3552a48d590fb19822f6b27aa16364024b1bb
6f56db5637cda27e05fd9f91d0c9688dd921d024
refs/heads/master
2016-09-11T02:40:00.333848
2013-08-04T23:32:43
2013-08-04T23:32:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,119
java
package coolc; import coolc.parser.*; import coolc.infrastructure.*; import coolc.ast.*; import java.io.*; import java.util.*; /* * Ejecutar con * llvm-link-3.2 output.ll coolstd.ll | lli-3.2 * y los que usen in_string o in_int, debe hacerse el linking e intepretación por separado llvm-link-3.2 output.ll coolstd.ll -o output.bc lli-3.2 output.bc */ /* * EL PROGRAMA DEBE MANEJAR: * - tipos básicos (String, Int, Bool) <- esto implica una sola clase * - funciones * - Expresiones Binarias * - Asignaciones * - Expresion if * * * Tipo Cool Valor inicial Tipo LLVM Int 0 i32 Bool false i1 String "" i8* * *Según las reglas de Cool, sólo debe existir un método main(), y se llama sobre una nueva instancia de la clase que lo contiene. Para esta entrega no se usan las clases, por lo que basta con que generen el código del main, y traten el self como un puntero null * * * Su objetivo es entregar programas en LLVM IR ejecutables * * Se les dará una implementación de los métodos de los tipos básicos (coolstd.ll) * * * Compilar código clang -O1 -S -o - -emit-llvm file.c -O1 es optimizacion * */ public class Coolc { static boolean texto = true; public static void printInstructions() { System.out.println( "Usage Coolc <action> file1 file2 ... filen\n" + "Available actions: \n" + "scan - scans each files and outputs a token list\n" + "parse - parses each file and outputs the syntax tree\n" + "symtable - generates and prints the symbol table\n" + "semantic - performs semanic analysis\n" + "codegen - print cool program equivalent\n" ); } public static void main(String[] args) throws FileNotFoundException, IOException { if (args.length < 2) { printInstructions(); return; } String action = args[0]; List<String> files = Arrays.asList(args).subList(1, args.length); switch(action) { case "scan": scan(files); break; case "parse": parse(files); break; case "symtable": symTable(files); break; case "semantic": semantic(files); break; case "codegen": codegen(files); break; default: printInstructions(); return; } } private static void scan(List<String> files) throws FileNotFoundException, IOException { for(String filename: files) { File f = new File(filename); Reader r = new FileReader(f); Lexer lex = new Lexer(r); Random rand = new Random(); for(int token = lex.yylex(); token != Parser.EOF; token = lex.yylex()) { Position pos = lex.getStartPos(); switch(token) { case Parser.ID: System.out.printf("%s:%2d:%2d Id<%s>\n", f.getPath(), pos.line, pos.column, lex.getLVal()); break; case Parser.INTEGER: System.out.printf("%s:%2d:%2d Int<%s>\n", f.getPath(), pos.line, pos.column, lex.getLVal()); break; case Parser.BOOL: System.out.printf("%s:%2d:%2d Boolean<%s>\n", f.getPath(), pos.line, pos.column, (boolean)lex.getLVal() ? "True" : "False"); break; case Parser.TYPE: System.out.printf("%s:%2d:%2d String<%s>\n", f.getPath(), pos.line, pos.column, lex.getLVal()); break; case Parser.STRING: String strval =((String)lex.getLVal()).replace("\n","").replace("\b", "").replace("\t", "").replace(">", ""); strval = strval.substring(0, Math.min(strval.length(), 20)); System.out.printf("%s:%2d:%2d String<%s>\n", f.getPath(), pos.line, pos.column, strval); break; default: System.out.printf("%s:%2d:%2d %s\n", f.getPath(), pos.line, pos.column, Parser.getTokenName(token)); break; } } } } private static void parse(List<String> files) throws FileNotFoundException, IOException { for(String filename: files) { File f = new File(filename); Reader r = new FileReader(f); Lexer lex = new Lexer(r); Parser p = new Parser(lex); System.err.printf("parsing %s\n", filename); p.parse(); AstPrinter printer = new AstPrinter(p.getRoot()); printer.print(); } } private static void symTable(List<String> files) throws FileNotFoundException, IOException { for(String filename: files) { File f = new File(filename); Reader r = new FileReader(f); Lexer lex = new Lexer(r); Parser p = new Parser(lex); System.err.printf("generating symTable %s\n", filename); p.parse(); SymTable table = new SymTable(p.getRoot()); table.printErrors(); table.print(); } } private static void codegen(List<String> files) throws FileNotFoundException, IOException { for(String filename: files) { File f = new File(filename); Reader r = new FileReader(f); Lexer lex = new Lexer(r); Parser p = new Parser(lex); System.err.printf("codegen %s\n", filename); p.parse(); SemanticAnalizer analizer = new SemanticAnalizer(p.getRoot()); // analizer.printErrors(); if( texto ) try { System.setOut(new PrintStream(new FileOutputStream("/home/richard/Escritorio/Entrega4/output.ll"))); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // CodeGenPrinter printer = new CodeGenPrinter(p.getRoot(), true); ClassPrinter printer = new ClassPrinter(p.getRoot(), true); printer.print(); } } private static void semantic(List<String> files) throws FileNotFoundException, IOException { for(String filename: files) { File f = new File(filename); Reader r = new FileReader(f); Lexer lex = new Lexer(r); Parser p = new Parser(lex); System.err.printf("semantic analysis %s\n", filename); p.parse(); SemanticAnalizer analizer = new SemanticAnalizer(p.getRoot()); AstPrinter printer = new AstPrinter(p.getRoot(), true); analizer.printErrors(); printer.print(); } } }
[ "richard@Leo.(none)" ]
richard@Leo.(none)
c4a74fc67f01c83cd45c1cb26521c58470b3b2a1
bf5039074deb78e9741320405847a869d4c62ff6
/CSE219/HWs/hw1/HW1Solution/WebPageMakerApp/src/wpm/file/FileManager.java
2a4bf7b4d9044d5516dcb93cc92ec8f4a010b7dc
[]
no_license
dtbinh/Personal
f216d37632535c3489fa1fbcd33713f11f837dd2
7befbe86d58e4f1f2f26f82767174016953900c9
refs/heads/master
2021-01-18T01:49:23.493061
2016-04-06T17:35:43
2016-04-06T17:35:43
56,241,995
1
0
null
2016-04-14T13:59:19
2016-04-14T13:59:19
null
UTF-8
Java
false
false
18,081
java
package wpm.file; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import javafx.collections.ObservableList; import javafx.scene.control.TreeItem; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonWriter; import javax.json.JsonWriterFactory; import javax.json.stream.JsonGenerator; import saf.components.AppDataComponent; import saf.components.AppFileComponent; import wpm.data.DataManager; import wpm.data.HTMLTagPrototype; import static wpm.data.HTMLTagPrototype.TAG_TEXT; import static wpm.file.FileManager.JSON_TAG_NAME; /** * This class serves as the file management component for this application, * providing all I/O services. * * @author Richard McKenna * @author ? * @version 1.0 */ public class FileManager implements AppFileComponent { // FOR JSON LOADING static final String JSON_TAGS_ARRAY_NAME = "tags"; static final String JSON_TAG_NAME = "tag"; static final String JSON_TAG_ATTRIBUTES = "attributes"; static final String JSON_TAG_ATTRIBUTE_NAME = "attribute_name"; static final String JSON_TAG_ATTRIBUTE_VALUE = "attribute_value"; static final String JSON_TAG_LEGAL_PARENTS = "legal_parents"; static final String JSON_TAG_HAS_CLOSING_TAG = "has_closing_tag"; static final String JSON_TAG_TREE = "tag_tree"; static final String JSON_TAG_NUMBER_OF_CHILDREN = "number_of_children"; static final String JSON_TAG_NODE_INDEX = "node_index"; static final String JSON_TAG_PARENT_INDEX = "parent_index"; static final String JSON_CSS_CONTENT = "css_content"; static final String DEFAULT_DOCTYPE_DECLARATION = "<!doctype html>\n"; static final String DEFAULT_ATTRIBUTE_VALUE = ""; // THIS IS THE TEMP PAGE FOR OUR SITE public static final String INDEX_FILE = "index.html"; public static final String CSS_FILE = "home.css"; public static final String PATH_CSS = "./temp/css/"; public static final String TEMP_CSS_PATH = PATH_CSS + CSS_FILE; public static final String PATH_TEMP = "./temp/"; public static final String TEMP_PAGE = PATH_TEMP + INDEX_FILE; /** * This method is for saving user work, which in the case of this * application means the data that constitutes the page DOM. * * @param data The data management component for this application. * * @param filePath Path (including file name/extension) to where * to save the data to. * * @throws IOException Thrown should there be an error writing * out data to the file. */ @Override public void saveData(AppDataComponent data, String filePath) throws IOException { StringWriter sw = new StringWriter(); // BUILD THE HTMLTags ARRAY DataManager dataManager = (DataManager)data; // THEN THE TREE JsonArrayBuilder arrayBuilder = Json.createArrayBuilder(); TreeItem root = dataManager.getHTMLRoot(); fillArrayWithTreeTags(root, arrayBuilder); JsonArray nodesArray = arrayBuilder.build(); // THEN PUT IT ALL TOGETHER IN A JsonObject JsonObject dataManagerJSO = Json.createObjectBuilder() .add(JSON_TAG_TREE, nodesArray) .add(JSON_CSS_CONTENT, dataManager.getCSSText()) .build(); // AND NOW OUTPUT IT TO A JSON FILE WITH PRETTY PRINTING Map<String, Object> properties = new HashMap<>(1); properties.put(JsonGenerator.PRETTY_PRINTING, true); JsonWriterFactory writerFactory = Json.createWriterFactory(properties); JsonWriter jsonWriter = writerFactory.createWriter(sw); jsonWriter.writeObject(dataManagerJSO); jsonWriter.close(); // INIT THE WRITER OutputStream os = new FileOutputStream(filePath); JsonWriter jsonFileWriter = Json.createWriter(os); jsonFileWriter.writeObject(dataManagerJSO); String prettyPrinted = sw.toString(); PrintWriter pw = new PrintWriter(filePath); pw.write(prettyPrinted); pw.close(); } // HELPER METHOD FOR SAVING DATA TO A JSON FORMAT private JsonObject makeTagJsonObject(HTMLTagPrototype tag, int numChildren) { String tagName; HashMap<String, String> attributes = tag.getAttributes(); ArrayList<String> legalParents = tag.getLegalParents(); JsonObject jso = Json.createObjectBuilder() .add(JSON_TAG_NAME, tag.getTagName()) .add(JSON_TAG_HAS_CLOSING_TAG, tag.hasClosingTag()) .add(JSON_TAG_LEGAL_PARENTS, buildJsonArray(legalParents)) .add(JSON_TAG_ATTRIBUTES, makeAttributesJsonArray(attributes)) .add(JSON_TAG_NUMBER_OF_CHILDREN, numChildren) .add(JSON_TAG_NODE_INDEX, tag.getNodeIndex()) .add(JSON_TAG_PARENT_INDEX, tag.getParentIndex()) .build(); return jso; } int maxNodeCounter; // HELPER METHOD FOR SAVING DATA TO A JSON FORMAT private void fillArrayWithTreeTags(TreeItem root, JsonArrayBuilder arrayBuilder) { maxNodeCounter = 0; // FIRST THE ROOT NODE HTMLTagPrototype nodeData = (HTMLTagPrototype)root.getValue(); nodeData.setNodeIndex(0); nodeData.setParentIndex(-1); JsonObject tagObject = makeTagJsonObject(nodeData, root.getChildren().size()); arrayBuilder.add(tagObject); // INC THE COUNTER maxNodeCounter++; // AND NOW START THE RECURSIVE FUNCTION addChildrenToTagTreeJsonObject(root, arrayBuilder); } // HELPER METHOD FOR SAVING DATA TO A JSON FORMAT private void addChildrenToTagTreeJsonObject(TreeItem node, JsonArrayBuilder arrayBuilder) { HTMLTagPrototype parentData = (HTMLTagPrototype)node.getValue(); // AND NOW GO THROUGH THE CHILDREN ObservableList<TreeItem> children = node.getChildren(); for (TreeItem child : children) { HTMLTagPrototype childData = (HTMLTagPrototype)child.getValue(); childData.setParentIndex(parentData.getNodeIndex()); childData.setNodeIndex(maxNodeCounter); maxNodeCounter++; arrayBuilder.add(makeTagJsonObject(childData, child.getChildren().size())); // AND NOW MAKE THE RECURSIVE CALL ON THE CHILDREN addChildrenToTagTreeJsonObject(child, arrayBuilder); } } // HELPER METHOD FOR SAVING DATA TO A JSON FORMAT private JsonArray buildJsonArray(ArrayList<String> data) { JsonArrayBuilder jsb = Json.createArrayBuilder(); for (String d : data) { jsb.add(d); } JsonArray jA = jsb.build(); return jA; } // HELPER METHOD FOR SAVING DATA TO A JSON FORMAT private JsonArray makeAttributesJsonArray(HashMap<String,String> attributes) { Set<String> keys = attributes.keySet(); JsonArrayBuilder arrayBuilder = Json.createArrayBuilder(); for (String attributeName : keys) { String attributeValue = attributes.get(attributeName); JsonObject jso = Json.createObjectBuilder() .add(JSON_TAG_ATTRIBUTE_NAME, attributeName) .add(JSON_TAG_ATTRIBUTE_VALUE, attributeValue) .build(); arrayBuilder.add(jso); } JsonArray jA = arrayBuilder.build(); return jA; } /** * This method loads data from a JSON formatted file into the data * management component and then forces the updating of the workspace * such that the user may edit the data. * * @param data Data management component where we'll load the file into. * * @param filePath Path (including file name/extension) to where * to load the data from. * * @throws IOException Thrown should there be an error reading * in data from the file. */ @Override public void loadData(AppDataComponent data, String filePath) throws IOException { // CLEAR THE OLD DATA OUT DataManager dataManager = (DataManager)data; dataManager.reset(); // LOAD THE JSON FILE WITH ALL THE DATA JsonObject json = loadJSONFile(filePath); // LOAD THE TAG TREE JsonArray jsonTagTreeArray = json.getJsonArray(JSON_TAG_TREE); loadTreeTags(jsonTagTreeArray, dataManager); // AND GET THE CSS CONTENT String cssContent = json.getString(JSON_CSS_CONTENT); dataManager.setCSSText(cssContent); } // HELPER METHOD FOR LOADING DATA FROM A JSON FORMAT private JsonObject loadJSONFile(String jsonFilePath) throws IOException { InputStream is = new FileInputStream(jsonFilePath); JsonReader jsonReader = Json.createReader(is); JsonObject json = jsonReader.readObject(); jsonReader.close(); is.close(); return json; } // HELPER METHOD FOR LOADING DATA FROM A JSON FORMAT private void loadTreeTags(JsonArray jsonTagsArray, DataManager dataManager) { ArrayList<TreeItem> nodes = new ArrayList(); // FIRST UPDATE THE ROOT JsonObject rootJso = jsonTagsArray.getJsonObject(0); HTMLTagPrototype rootData = loadTag(rootJso); TreeItem root = dataManager.getHTMLRoot(); nodes.add(root); root.getChildren().clear(); root.setValue(rootData); // AND NOW JUST GO THROUGH THE REST OF THE ARRAY for (int i = 1; i < jsonTagsArray.size(); i++) { JsonObject nodeJso = jsonTagsArray.getJsonObject(i); HTMLTagPrototype nodeData = loadTag(nodeJso); TreeItem newNode = new TreeItem(nodeData); nodes.add(newNode); TreeItem parentNode = nodes.get(nodeData.getParentIndex()); parentNode.getChildren().add(newNode); } } // HELPER METHOD FOR LOADING DATA FROM A JSON FORMAT private void loadChildren(TreeItem parent, JsonArray jsonTagsArray, int startIndex, int endIndex) { // GET ALL THE CHILD DATA FIRST for (int i = startIndex; i < endIndex; i++) { JsonObject nodeJso = jsonTagsArray.getJsonObject(i); HTMLTagPrototype nodeData = loadTag(nodeJso); TreeItem newNode = new TreeItem(nodeData); parent.getChildren().add(newNode); } // NOW FOR THE RECURSIVE CALLS int childIndex = 0; for (int j = startIndex; j < endIndex; j++) { JsonObject nodeJso = jsonTagsArray.getJsonObject(j); int numberOfGrandchildren = nodeJso.getInt(JSON_TAG_NUMBER_OF_CHILDREN); TreeItem childNode = (TreeItem)parent.getChildren().get(childIndex); s += "j: " + j + "\tparent: " + parent.getValue().toString() + "\tchildNode: " + childNode.getValue().toString() + "\tstartIndex: " + startIndex + "\tnumChildren: " + endIndex + "\tnumberOfGrandchildren: " + numberOfGrandchildren + "\tchildIndex: " + childIndex + "\n"; if (numberOfGrandchildren > 0) loadChildren(childNode, jsonTagsArray, startIndex, numberOfGrandchildren); childIndex++; } } static String s = ""; // HELPER METHOD FOR LOADING DATA FROM A JSON FORMAT private void loadTags(JsonArray jsonTagsArray, DataManager dataManager) { for (int i = 0; i < jsonTagsArray.size(); i++) { JsonObject tag= jsonTagsArray.getJsonObject(i); HTMLTagPrototype tagToAdd = loadTag(tag); dataManager.addTag(tagToAdd); } } // HELPER METHOD FOR LOADING DATA FROM A JSON FORMAT private HTMLTagPrototype loadTag(JsonObject tag) { HTMLTagPrototype tagToLoad = new HTMLTagPrototype(tag.getString(JSON_TAG_NAME), tag.getBoolean(JSON_TAG_HAS_CLOSING_TAG)); JsonArray legalParentsArray = tag.getJsonArray(JSON_TAG_LEGAL_PARENTS); for (int j = 0; j < legalParentsArray.size(); j++) { String legalParent = legalParentsArray.getString(j); tagToLoad.addLegalParent(legalParent); } JsonArray attributesArray = tag.getJsonArray(JSON_TAG_ATTRIBUTES); for (int k = 0; k < attributesArray.size(); k++) { JsonObject attributeJso = attributesArray.getJsonObject(k); String attributeName = attributeJso.getString(JSON_TAG_ATTRIBUTE_NAME); String attributeValue = attributeJso.getString(JSON_TAG_ATTRIBUTE_VALUE); tagToLoad.addAttribute(attributeName, attributeValue); } tagToLoad.setNodeIndex(tag.getInt(JSON_TAG_NODE_INDEX)); tagToLoad.setParentIndex(tag.getInt(JSON_TAG_PARENT_INDEX)); return tagToLoad; } /** * This method exports the contents of the data manager to a * Web page including the html page, needed directories, and * the CSS file. * * @param data The data management component. * * @param filePath Path (including file name/extension) to where * to export the page to. * * @throws IOException Thrown should there be an error writing * out data to the file. */ @Override public void exportData(AppDataComponent data, String filePath) throws IOException { // WALK THE TREE DataManager pageData = ((DataManager)data); TreeItem root = pageData.getHTMLRoot(); // WRITE OUT THE HTML PrintWriter out = new PrintWriter(filePath); out.print(DEFAULT_DOCTYPE_DECLARATION); exportNode(root, out, 0); out.close(); } /** * This function writes the CSS content out to the CSS file * that is found using the filePath argument. * * @param cssContent The CSS content to write. * * @param filePath The path to the CSS file. * * @throws IOException Thrown should there be any problems writing * to the CSS File. */ public void exportCSS(String cssContent, String filePath) throws IOException { PrintWriter out = new PrintWriter(filePath); out.print(cssContent); out.close(); } // HELPER METHOD FOR EXPORTING THE SITE private void exportNode(TreeItem node, PrintWriter out, int tabCounter) throws IOException { // WRITE OUT NODE STARTING TAG HTMLTagPrototype nodeData = (HTMLTagPrototype)node.getValue(); writeNodeOpen(nodeData, out, tabCounter); // WRITE OUT ALL THE CHILDREN ObservableList<TreeItem> children = node.getChildren(); for (TreeItem child : children) { exportNode(child, out, tabCounter + 1); } // AND NOW CLOSE THE TAG if (nodeData.hasClosingTag()) writeNodeClose(nodeData, out, tabCounter); } // HELPER METHOD FOR EXPORTING THE SITE private void writeNodeOpen(HTMLTagPrototype nodeData, PrintWriter out, int tabCounter) throws IOException { String text = ""; for (int i = 0; i < tabCounter; i++) { text += "\t"; } if (nodeData.getTagName().equals(TAG_TEXT)) { text += nodeData.getAttribute(TAG_TEXT.toLowerCase()); } else { text += "<" + nodeData.getTagName(); HashMap<String, String> attributes = nodeData.getAttributes(); Collection<String> keySet = attributes.keySet(); for (String attributeName : keySet) { String attributeValue = attributes.get(attributeName); if (attributeValue.trim().length() > 0) text += " " + attributeName + "=\"" + attributeValue + "\""; } if (nodeData.hasClosingTag()) text += ">\n"; else text += " />\n"; } out.print(text); } // HELPER METHOD FOR EXPORTING THE SITE private void writeNodeClose(HTMLTagPrototype nodeData, PrintWriter out, int tabCounter) throws IOException { String text = ""; for (int i = 0; i < tabCounter; i++) { text += "\t"; } text += "</" + nodeData.getTagName() + ">\n"; out.print(text); } /** * This method is provided to satisfy the compiler, but it * is not used by this application. */ @Override public void importData(AppDataComponent data, String filePath) throws IOException { // NOTE THAT THE Web Page Maker APPLICATION MAKES // NO USE OF THIS METHOD SINCE IT NEVER IMPORTS // EXPORTED WEB PAGES } /** * This method loads the HTML tags that the application will let the * user build with into the data manager. * * @param data The data management component for this application. This method * will load tags from the file into this object. * * @param filePath File path and name/extension of the JSON file that * contains the list of tags to be used for editing. * * @throws IOException Thrown should there be a problem reading from * the JSON file. */ public void loadHTMLTags(DataManager data, String filePath) throws IOException { // LOAD THE JSON FILE WITH ALL THE DATA JsonObject json = loadJSONFile(filePath); // GET THE ARRAY JsonArray tagsArray = json.getJsonArray(JSON_TAGS_ARRAY_NAME); // AND LOAD ALL THE ITEMS IN for (int i = 0; i < tagsArray.size(); i++) { JsonObject tagJSO = tagsArray.getJsonObject(i); String tagName = tagJSO.getString(JSON_TAG_NAME); String tagHasClosingTag = tagJSO.getString(JSON_TAG_HAS_CLOSING_TAG); boolean hasClosingTag = Boolean.parseBoolean(tagHasClosingTag); HTMLTagPrototype tag = new HTMLTagPrototype(tagName, hasClosingTag); // NOW GET ALL THE TAG ATTRIBUTES THAT CAN BE EDITED JsonArray attributesArray = tagJSO.getJsonArray(JSON_TAG_ATTRIBUTES); for (int j = 0; j < attributesArray.size(); j++) { String attribute = attributesArray.getString(j); tag.addAttribute(attribute, DEFAULT_ATTRIBUTE_VALUE); } // AND NOW GET THE LEGAL PARENTS JsonArray legalParentsArray = tagJSO.getJsonArray(JSON_TAG_LEGAL_PARENTS); for (int k = 0; k < legalParentsArray.size(); k++) { String legalParent = legalParentsArray.getString(k); tag.addLegalParent(legalParent); } // NOW GIVE THE LOADED TAG TO THE DATA MANAGER data.addTag(tag); } } /** * This function clears the contents of the file argument. * * @param filePath The file to clear. * * @throws IOException Thrown should there be an issue writing * to the file to clear. */ public void clearFile(String filePath) throws IOException { PrintWriter out = new PrintWriter(filePath); out.print(""); out.close(); } }
[ "ronaldbalchand@gmail.com" ]
ronaldbalchand@gmail.com
8832a9293abddc65c43f50a8c123b38fe404fbd3
8f183f85a95467f2703df94ad0e5ed357f4b60cc
/dragon-storage/src/main/java/info/yangguo/dragon/storage/mysql/dao/pojo/AnnotationPojo.java
2a6536ded4fea3ad0e3f287bab76c7697cf305c4
[]
no_license
zh-soft/dragon
a0602c303b15c2314a92dd9ee165351eca94d7a8
7d1f08a32831b97c549742b1134f12f4a5dbb3ef
refs/heads/master
2021-05-07T23:43:15.314126
2017-06-25T14:03:52
2017-06-25T14:03:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,826
java
package info.yangguo.dragon.storage.mysql.dao.pojo; import java.io.Serializable; /** * @author:杨果 * @date:16/6/6 上午10:54 * * Description: * */ public class AnnotationPojo implements Serializable { private static final long serialVersionUID = 8229331674571219289L; private String type; private String ip; private int port; private long time; private String spanId; private String value; private String app; private String traceId; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public String getSpanId() { return spanId; } public void setSpanId(String spanId) { this.spanId = spanId; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getApp() { return app; } public void setApp(String app) { this.app = app; } public String getTraceId() { return traceId; } public void setTraceId(String traceId) { this.traceId = traceId; } //主要用在去掉相同异常,特别是既是provider有事consumer的地方 @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AnnotationPojo that = (AnnotationPojo) o; if (!type.equals(that.type)) return false; if (!ip.equals(that.ip)) return false; if (!spanId.equals(that.spanId)) return false; if (value != null ? !value.equals(that.value) : that.value != null) return false; return app.equals(that.app); } @Override public int hashCode() { int result = type.hashCode(); result = 31 * result + ip.hashCode(); result = 31 * result + spanId.hashCode(); result = 31 * result + (value != null ? value.hashCode() : 0); result = 31 * result + app.hashCode(); return result; } @Override public String toString() { return "AnnotationPojo{" + "type='" + type + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", time=" + time + ", spanId='" + spanId + '\'' + ", value='" + value + '\'' + ", app='" + app + '\'' + '}'; } }
[ "yang.guo@chinaredstar.com" ]
yang.guo@chinaredstar.com
54a712201978d4e3ecb2be37780c8d2ccc259288
2df06b989fd39e8329f8f0472c16ec2b427e289d
/java/com/android/dialer/lookup/DirectoryId.java
9749dc4404c2832ca1bb038cdc6a21c3a655e976
[ "Apache-2.0" ]
permissive
ResurrectionRemix/android_packages_apps_Dialer
8488cdbef44d1a5458e6061c7dc91958ec671ad9
6828921e03932700b17676b62d04328f6567e515
refs/heads/oreo
2021-01-18T01:54:41.978801
2018-10-05T00:16:13
2018-10-10T20:21:44
43,914,283
3
87
NOASSERTION
2019-06-28T13:53:25
2015-10-08T20:21:20
Java
UTF-8
Java
false
false
1,087
java
package com.android.dialer.lookup; import android.net.Uri; import android.provider.ContactsContract; public class DirectoryId { // default contacts directory public static final long DEFAULT = ContactsContract.Directory.DEFAULT; // id for a non existant directory public static final long NULL = Long.MAX_VALUE; // id for nearby forward lookup results (not a real directory) public static final long NEARBY = NULL - 1; // id for people forward lookup results (not a real directory) public static final long PEOPLE = NULL - 2; public static boolean isFakeDirectory(long directory) { return directory == NULL || directory == NEARBY || directory == PEOPLE; } public static long fromUri(Uri lookupUri) { long directory = DirectoryId.DEFAULT; if (lookupUri != null) { String dqp = lookupUri.getQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY); if (dqp != null) { directory = Long.valueOf(dqp); } } return directory; } }
[ "dan.pasanen@gmail.com" ]
dan.pasanen@gmail.com
52062c96c024ecce6761377321e2bae515a33d9e
67ad735a683439f51f7259010ec5483f1a06ced8
/src/java/iw/socialdevelop/controller/ProgettoDettaglio.java
870cd17171524217ff8d2cfe3a9e6953df8d219c
[]
no_license
Lucgril/SocialDevelop
3171405643eabe6cb548c7484f1409499826af57
860bf4d409143367dbb0b91fe1d2d6561140f1f0
refs/heads/master
2021-09-10T12:53:13.917473
2018-03-26T15:09:31
2018-03-26T15:09:31
126,087,599
0
0
null
null
null
null
UTF-8
Java
false
false
6,018
java
package iw.socialdevelop.controller; import it.univaq.f4i.iw.framework.result.FailureResult; import it.univaq.f4i.iw.framework.result.TemplateManagerException; import it.univaq.f4i.iw.framework.result.TemplateResult; import it.univaq.f4i.iw.framework.security.SecurityLayer; import iw.framework.data.DataLayerException; import iw.socialdevelop.data.model.Domanda; import iw.socialdevelop.data.model.Messaggio; import iw.socialdevelop.data.model.Progetto; import iw.socialdevelop.data.model.Proposta; import iw.socialdevelop.data.model.SocialDevelopDataLayer; import iw.socialdevelop.data.model.Task; import iw.socialdevelop.data.model.Tipo; import iw.socialdevelop.data.model.UtenteProgetto; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class ProgettoDettaglio extends SocialDevelopBaseController { private void action_error(HttpServletRequest request, HttpServletResponse response) { if (request.getAttribute("exception") != null) { (new FailureResult(getServletContext())).activate((Exception) request.getAttribute("exception"), request, response); } else { (new FailureResult(getServletContext())).activate((String) request.getAttribute("message"), request, response); } } private void action_default(HttpServletRequest request, HttpServletResponse response, int n) { try { HttpSession s = SecurityLayer.checkSession(request); if (s != null) { request.setAttribute("logged", s.getAttribute("logged")); request.setAttribute("userid", s.getAttribute("userid")); } request.setAttribute("n", n); TemplateResult res = new TemplateResult(getServletContext()); Progetto progetto = ((SocialDevelopDataLayer) request.getAttribute("datalayer")).getProgetto(n); List<Task> tasks = ((SocialDevelopDataLayer) request.getAttribute("datalayer")).getTask(progetto); List<Messaggio> messaggi = ((SocialDevelopDataLayer) request.getAttribute("datalayer")).getMessaggi(progetto); request.setAttribute("progetto", progetto); request.setAttribute("page_title", progetto.getNome()); request.setAttribute("messaggi", messaggi); for (Task t : tasks) { Tipo tipo = ((SocialDevelopDataLayer) request.getAttribute("datalayer")).getTipo(t.getIdTipo()); t.setTipo(tipo); } request.setAttribute("tasks", tasks); if (s != null) { List<Domanda> domanda = ((SocialDevelopDataLayer) request.getAttribute("datalayer")).getUtentiPartecipantiProggettoDomanda((int) s.getAttribute("userid"), n); List<Proposta> proposta = ((SocialDevelopDataLayer) request.getAttribute("datalayer")).getUtentiPartecipantiProggettoProp((int) s.getAttribute("userid"), n); if (domanda.size() > 0 || proposta.size() > 0) { request.setAttribute("partecipa", true); } UtenteProgetto utenteprogetto = ((SocialDevelopDataLayer) request.getAttribute("datalayer")).getUtenteProgetto((int) s.getAttribute("userid"), n); if (utenteprogetto != null && utenteprogetto.getRuolo().equals("admin")) { request.setAttribute("adminp", true); } } res.activate("progettoDettaglio.html", request, response); } catch (DataLayerException ex) { Logger.getLogger(ProgettoDettaglio.class.getName()).log(Level.SEVERE, null, ex); } catch (TemplateManagerException ex) { Logger.getLogger(ProgettoDettaglio.class.getName()).log(Level.SEVERE, null, ex); } } @Override protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException { int n; try { n = SecurityLayer.checkNumeric(request.getParameter("n")); request.setAttribute("riferimento", "progetto?n=" + n); if (request.getParameter("tipo") != null) { action_messaggio(request, response, n); } action_default(request, response, n); } catch (NumberFormatException ex) { request.setAttribute("message", "Numero non valido"); action_error(request, response); } } @Override public String getServletInfo() { return "Progetto dettaglio servlet"; }// </editor-fold> private void action_messaggio(HttpServletRequest request, HttpServletResponse response, int n) { try { HttpSession s = SecurityLayer.checkSession(request); if (s != null) { request.setAttribute("logged", s.getAttribute("logged")); request.setAttribute("userid", s.getAttribute("userid")); } int userid = (int) request.getAttribute("userid"); Messaggio messaggio = ((SocialDevelopDataLayer) request.getAttribute("datalayer")).createMessaggio(); messaggio.setProgetto(((SocialDevelopDataLayer) request.getAttribute("datalayer")).getProgetto(n)); messaggio.setUtente(((SocialDevelopDataLayer) request.getAttribute("datalayer")).getUtente(userid)); messaggio.setTipo(request.getParameter("tipo")); messaggio.setTesto(request.getParameter("messaggio")); ((SocialDevelopDataLayer) request.getAttribute("datalayer")).storeMessaggio(messaggio); } catch (DataLayerException ex) { Logger.getLogger(ProgettoDettaglio.class.getName()).log(Level.SEVERE, null, ex); } } }
[ "luca.grillo@student.univaq.it" ]
luca.grillo@student.univaq.it
879645bdd8c9935401e9a229834c049f7a27106a
a744882fb7cf18944bd6719408e5a9f2f0d6c0dd
/sourcecode8/src/sun/management/jdp/package-info.java
bb6dabcf9978707a29d24bf4514a44d03f0d2231
[ "Apache-2.0" ]
permissive
hanekawasann/learn
a39b8d17fd50fa8438baaa5b41fdbe8bd299ab33
eef678f1b8e14b7aab966e79a8b5a777cfc7ab14
refs/heads/master
2022-09-13T02:18:07.127489
2020-04-26T07:58:35
2020-04-26T07:58:35
176,686,231
0
0
Apache-2.0
2022-09-01T23:21:38
2019-03-20T08:16:05
Java
UTF-8
Java
false
false
3,231
java
/* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * Summary * ------- * <p> * Define a lightweight network protocol for discovering running and * manageable Java processes within a network subnet. * <p> * <p> * Description * ----------- * <p> * The protocol is lightweight multicast based, and works like a beacon, * broadcasting the JMXService URL needed to connect to the external JMX * agent if an application is started with appropriate parameters. * <p> * The payload is structured like this: * <p> * 4 bytes JDP magic (0xC0FFEE42) * 2 bytes JDP protocol version (1) * 2 bytes size of the next entry * x bytes next entry (UTF-8 encoded) * 2 bytes size of next entry * ... Rinse and repeat... * <p> * The payload will be parsed as even entries being keys, odd entries being * values. * <p> * The standard JDP packet contains four entries: * <p> * - `DISCOVERABLE_SESSION_UUID` -- Unique id of the instance; this id changes every time * the discovery protocol starts and stops * <p> * - `MAIN_CLASS` -- The value of the `sun.java.command` property * <p> * - `JMX_SERVICE_URL` -- The URL to connect to the JMX agent * <p> * - `INSTANCE_NAME` -- The user-provided name of the running instance * <p> * The protocol sends packets to 224.0.23.178:7095 by default. * <p> * The protocol uses system properties to control it's behaviour: * - `com.sun.management.jdp.port` -- override default port * <p> * - `com.sun.management.jdp.address` -- override default address * <p> * - `com.sun.management.jmxremote.autodiscovery` -- whether we should start autodiscovery or * not. Autodiscovery starts if and only if following conditions are met: (autodiscovery is * true OR (autodiscovery is not set AND jdp.port is set)) * <p> * - `com.sun.management.jdp.ttl` -- set ttl for broadcast packet, default is 1 * - `com.sun.management.jdp.pause` -- set broadcast interval in seconds default is 5 * - `com.sun.management.jdp.source_addr` -- an address of interface to use for broadcast */ package sun.management.jdp;
[ "763803382@qq.com" ]
763803382@qq.com
2755d62511d6160ca8fb5de43f6b639d12453d48
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/robolectric/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCookieSyncManager.java
2c910c2e37326ab521e7df0dd0b91af1b8dfc53c
[ "MIT", "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
Java
false
false
1,161
java
package com.xtremelabs.robolectric.shadows; import android.content.Context; import android.webkit.CookieSyncManager; import com.xtremelabs.robolectric.Robolectric; import com.xtremelabs.robolectric.internal.Implementation; import com.xtremelabs.robolectric.internal.Implements; /** * Shadows the {@code android.webkit.CookieSyncManager} class. */ @Implements(CookieSyncManager.class) public class ShadowCookieSyncManager { private static CookieSyncManager sRef; private boolean synced = false; @Implementation public static synchronized CookieSyncManager createInstance(Context ctx) { if (sRef == null) { sRef = Robolectric.newInstanceOf(CookieSyncManager.class); } return sRef; } @Implementation public static CookieSyncManager getInstance() { if (sRef == null) { throw new IllegalStateException("createInstance must be called first"); } return sRef; } @Implementation public void sync() { synced = true; } public boolean synced() { return synced; } public void reset() { synced = false; } }
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
cfbaef62f6aa3fdf3d46497ea29666d5a74a4bba
c39941b11a5b467a3ff60ba20da0f37b17d0bc35
/AOP/src/main/java/com/demo/afterThrowing/AfterThrowingDemoApp.java
87b2cdf19754a6f7d618af87aa851b01688336ad
[]
no_license
FebrianFrancione/Spring
af2bf0a901da38a0a16585cf86e6debfac4335cf
eb7ad275bf76995861ae2e76e52bca52118245da
refs/heads/master
2023-03-30T09:00:17.975935
2021-04-01T00:36:23
2021-04-01T00:36:23
333,269,151
0
0
null
2021-02-12T03:00:37
2021-01-27T01:38:00
Java
UTF-8
Java
false
false
973
java
package com.demo.afterThrowing; import com.demo.afterThrowing.Dao.AccountDao; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.List; public class AfterThrowingDemoApp { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class); AccountDao theAccountDao = context.getBean("accountDao", AccountDao.class); List<Account> theAccounts = null; try { boolean tripwire = true; theAccounts = theAccountDao.findAccounts(tripwire); }catch ( Exception exc){ System.out.println("\n\nMain Program ... caught exception" + exc); } System.out.println("\n\n Main program: AfterThrowingDemo App"); System.out.println("-------------------------------------------"); System.out.println(theAccounts + "\n"); context.close(); } }
[ "febrian.francione@gmail.com" ]
febrian.francione@gmail.com
f13cc210b266b68b3aea57598533344de9591eed
b96aef78d22b141a9f4eff979219c274ec607935
/test/org.xkonnex.repo.dsl.moduledsl.test/src/org/xkonnex/repo/dsl/moduledsl/test/ModuleDslTestModule.java
7cd5bd3455f4927875391ccc656e4f5eafb0db1f
[]
no_license
andrearn/org.fornax.soa.xtextservicerepository
cb3417905568c361a59c85108e3a0042967be387
d04631d5a82c42290687495ec76ed5d36dcab44c
refs/heads/master
2021-07-12T11:41:32.920447
2019-02-16T23:13:45
2019-02-16T23:13:45
1,440,923
4
0
null
null
null
null
UTF-8
Java
false
false
581
java
package org.xkonnex.repo.dsl.moduledsl.test; import org.xkonnex.repo.generator.moduledsl.ModuleDslGeneratorModule; import com.google.inject.Binder; import com.google.inject.name.Names; public class ModuleDslTestModule extends ModuleDslGeneratorModule { public void configureUseNestedPaths (Binder bind) { bind.bind(Boolean.class).annotatedWith(Names.named("useNestedPaths")).toInstance(false); } public void configureUseRegistryBasedFilePaths (Binder bind) { bind.bind (Boolean.class).annotatedWith(Names.named("useRegistryBasedFilePaths")).toInstance(false); } }
[ "andre.arnold@gmx.de" ]
andre.arnold@gmx.de
02d3c046495785b30a6f4d4ebae2ac29cc773444
82e79be4db5edce0fae55d44e85d3a28fbfcc521
/src/main/java/observers/LobbyObserver.java
f06a27bedb35bd780dde58635604b4196d46f6e5
[]
no_license
MartinVeltman/MartinRisk
f631eae6f54077a7877ac948b6ddbfda17c397b2
b91bd41fa3819ed09b3bf2f302f9b0e870aff05d
refs/heads/master
2023-05-31T22:48:00.886285
2021-07-05T21:49:15
2021-07-05T21:49:15
381,051,038
0
0
null
null
null
null
UTF-8
Java
false
false
274
java
package observers; import com.google.cloud.firestore.DocumentSnapshot; public interface LobbyObserver { void update(LobbyObservable lb); void updateDocument(DocumentSnapshot lb); //alleen de updateDocument word gerund zou dus naar update kunnen worden veranderd }
[ "martinveltman@live.nl" ]
martinveltman@live.nl
c4e934e841c881dbedfcfbd381d395bbd7c04f80
87f970ab8b4b504c8215f6aac2d6e98ac0e9f9d5
/src/java/com/wonders/stpt/ThemeDatabase/action/ThemeDatabaseAction.java
3573da877d5b6adada7bd037dd92bb8f7779b3e6
[]
no_license
Q-jone/wd-portal
f7339fd76e89744576780b0f02761c74a77b9a13
7dd219cf23c7474d2a81f3ae61cfed6e458f8e88
refs/heads/master
2021-01-19T18:41:43.377611
2015-06-24T15:57:18
2015-06-24T15:57:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
11,208
java
package com.wonders.stpt.ThemeDatabase.action; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionContext; import com.wonders.stpt.ThemeDatabase.model.bo.GreataProject; import com.wonders.stpt.ThemeDatabase.model.bo.GreataProjectCompany; import com.wonders.stpt.ThemeDatabase.service.ThemeDatabaseService; import com.wonders.stpt.util.ActionWriter; @ParentPackage("struts-default") @Namespace(value="/themeDatabase") @Controller("themeDatabaseAction") @Scope("prototype") public class ThemeDatabaseAction { public ActionContext actionContext = ActionContext.getContext(); public HttpServletRequest request = (HttpServletRequest) actionContext.get(ServletActionContext.HTTP_REQUEST); public HttpServletResponse response = (HttpServletResponse) actionContext.get(ServletActionContext.HTTP_RESPONSE); public HttpSession session = request.getSession(); @Autowired private ThemeDatabaseService themeDatabaseService; ActionWriter ac = new ActionWriter(response); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateFormat dfy = new SimpleDateFormat("yyyy"); @Action(value="showIndex",results={@Result(name="success",location="/themeDatabase/index.jsp")}) public String showIndex(){ String sql = "select t.id,t.project_id,t.line_id,t.project_name from greata_project t where t.removed = '0' order by t.project_name"; List<Object[]> projectList = themeDatabaseService.findBySql(sql, null); List<Object[]> assetList = findEstimateList(); request.setAttribute("projectList", projectList); request.setAttribute("assetList", assetList); return "success"; } @Action(value="showPlanTask") public String showPlanTask(){ String sql = "select t.project_id,t1.plan_type_name,sum(t.total_completion) "+ " from greata_plan_task t,greata_plan_type t1 "+ " where t.plan_id = t1.plan_id "+ " group by t.project_id,t1.plan_type_name "+ " order by t.project_id,t1.plan_type_name"; List<Object[]> list = themeDatabaseService.findBySql(sql, null); ac.writeJson(list); return null; } @Action(value="showQuality") public String showQuality(){ String sql = "select t.project_id,t.status,count(*) from greata_quality t " + " where to_date(submit_time,'yyyy-mm-dd')>sysdate-30 "+ " group by t.project_id,t.status order by t.project_id,t.status"; List<Object[]> list = themeDatabaseService.findBySql(sql, null); ac.writeJson(list); return null; } @Action(value="toIntroduction",results={@Result(name="introduction",location="/themeDatabase/introduction.jsp")}) public String introduction(){ String id=request.getParameter("id"); if(id!=null&&id.length()>0){ GreataProject go=(GreataProject)themeDatabaseService.load(id, GreataProject.class); if(go.getProjectCompanyId()!=null&&go.getProjectCompanyId().length()>0){ GreataProjectCompany co=(GreataProjectCompany)themeDatabaseService.load(go.getProjectCompanyId(), GreataProjectCompany.class); request.setAttribute("co", co); } request.setAttribute("go", go); } return "introduction"; } @Action(value="toView",results={@Result(name="view",location="/themeDatabase/view.jsp")}) public String view(){ String projectId=request.getParameter("projectId"); String sql=""; List<Object> list=new ArrayList<Object>(); if(projectId!=null){ sql+="select t.plan_name,t.plan_begin_time,t.plan_finish_time,t.real_begin_time, t.real_finish_time "+ " from greata_plan_task t "+ " where t.removed='0' and t.plan_type='9' and t.project_id = ? order by t.plan_name desc"; list.add(projectId); List<Object[]> pbt=themeDatabaseService.findBySql(sql, list); request.setAttribute("list", pbt); return "view"; } return "view"; } @Action(value="toEstimate",results={@Result(name="estimate",location="/themeDatabase/estimate.jsp")}) public String estimate(){ String projectId=request.getParameter("projectId"); String sql=""; List<Object> list=new ArrayList<Object>(); if(projectId!=null){ sql+="select t.estimates_name,t.final_base_amount "+ "from greata_estimates t where t.project_id = ?"; list.add(projectId); List<Object[]> ge=themeDatabaseService.findBySql(sql, list); request.setAttribute("list", ge); return "estimate"; } return "estimate"; } @Action(value="countPlanTask") public String countPlanTask(){ String year = dfy.format(new Date()); String sql = "select distinct t.plan_type_name from greata_plan_type t where t.removed = '0' order by t.plan_type_name"; List<Object[]> list = themeDatabaseService.findBySql(sql, null); sql = "select t1.plan_type_name,count(*) from greata_plan_task t,greata_plan_type t1 "+ " where t.plan_id = t1.plan_id and t.removed = '0' and t1.removed = '0' "+ " group by t1.plan_type_name order by t1.plan_type_name"; List<Object[]> list1 = themeDatabaseService.findBySql(sql, null); sql = "select t1.plan_type_name,count(*) from greata_plan_task t,greata_plan_type t1 "+ " where t.plan_id = t1.plan_id and t.removed = '0' and t1.removed = '0' "+ " and t.real_finish_time is not null "+ " group by t1.plan_type_name order by t1.plan_type_name"; List<Object[]> list2 = themeDatabaseService.findBySql(sql, null); sql = "select t1.plan_type_name,count(*) from greata_plan_task t,greata_plan_type t1 "+ " where t.plan_id = t1.plan_id and t.removed = '0' and t1.removed = '0' "+ " and t.plan_finish_time like '"+year+"%' "+ " group by t1.plan_type_name order by t1.plan_type_name"; List<Object[]> list3 = themeDatabaseService.findBySql(sql, null); sql = "select t1.plan_type_name,count(*) from greata_plan_task t,greata_plan_type t1 "+ " where t.plan_id = t1.plan_id and t.removed = '0' and t1.removed = '0' "+ " and t.real_finish_time like '"+year+"%' "+ " group by t1.plan_type_name order by t1.plan_type_name"; List<Object[]> list4 = themeDatabaseService.findBySql(sql, null); List<Integer[]> outList = new ArrayList<Integer[]>(); if(list!=null&&list.size()>0){ Map<String,Integer> map1 = new HashMap<String,Integer>(); if(list1!=null&&list1.size()>0){ for(int i=0;i<list1.size();i++){ map1.put(list1.get(i)[0]+"", Integer.parseInt(list1.get(i)[1]+"")); } } Map<String,Integer> map2 = new HashMap<String,Integer>(); if(list2!=null&&list2.size()>0){ for(int i=0;i<list2.size();i++){ map2.put(list2.get(i)[0]+"", Integer.parseInt(list2.get(i)[1]+"")); } } Map<String,Integer> map3 = new HashMap<String,Integer>(); if(list3!=null&&list3.size()>0){ for(int i=0;i<list3.size();i++){ map3.put(list3.get(i)[0]+"", Integer.parseInt(list3.get(i)[1]+"")); } } Map<String,Integer> map4 = new HashMap<String,Integer>(); if(list4!=null&&list4.size()>0){ for(int i=0;i<list4.size();i++){ map4.put(list4.get(i)[0]+"", Integer.parseInt(list4.get(i)[1]+"")); } } Integer[] datas1 = new Integer[list.size()]; Integer[] datas2 = new Integer[list.size()]; Integer[] datas3 = new Integer[list.size()]; Integer[] datas4 = new Integer[list.size()]; for(int i=0;i<list.size();i++){ if(map1.containsKey(list.get(i))){ datas1[i] = map1.get(list.get(i)); }else{ datas1[i] = 0; } if(map2.containsKey(list.get(i))){ datas2[i] = map2.get(list.get(i)); }else{ datas2[i] = 0; } if(map3.containsKey(list.get(i))){ datas3[i] = map3.get(list.get(i)); }else{ datas3[i] = 0; } if(map4.containsKey(list.get(i))){ datas4[i] = map4.get(list.get(i)); }else{ datas4[i] = 0; } } outList.add(datas1); outList.add(datas2); outList.add(datas3); outList.add(datas4); } ac.writeJson(outList); return null; } @Action(value="findAllTypes") public String findAllTypes(){ String sql = "select distinct t.plan_type_name from greata_plan_type t where t.removed = '0' order by t.plan_type_name"; List<Object[]> list = themeDatabaseService.findBySql(sql, null); ac.writeJson(list); return null; } @Action(value="toCountPlanTaskPage",results={@Result(name="success",location="/themeDatabase/countPlanTask.jsp")}) public String tocountPlanTaskPage(){ return "success"; } public List<Object[]> findEstimateList(){ String sql = "select v.*,sum(nvl(t2.final_base_amount,0)) sum6 from ( "+ " select t1.project_name,t1.project_id,sum(nvl(t.done_contract_amount,0)) sum1,sum(nvl(t.approved_change_amount,0)) sum2,sum(nvl(t.todo_change_amount,0)) sum3,"+ " sum(nvl(t.total_payment,0)) sum4,sum(nvl(t.this_month_payment,0)) sum5 from greata_asset_execute t right join greata_project t1 "+ " on t.project_id = t1.project_id group by t1.project_name,t1.project_id) v "+ " left join greata_estimates t2 on t2.project_id = v.project_id "+ " group by v.project_name,v.project_id,v.sum1,v.sum2,v.sum3,v.sum4,v.sum5 order by v.project_name"; return themeDatabaseService.findBySql(sql, null); } @Action(value="showEstimateView",results={@Result(name="success",location="/themeDatabase/estimateView.jsp")}) public String showEstimateView(){ List<Object[]> list = findEstimateList(); List<String[]> showList = new ArrayList<String[]>(); String[] sum = {"合计:","0","0","0","0","0","0"}; if(list!=null&&list.size()>0){ for(int i=0;i<list.size();i++){ String[] strs = new String[7]; strs[0] = list.get(i)[0]+""; strs[1] = list.get(i)[7]+""; strs[2] = list.get(i)[2]+""; strs[3] = list.get(i)[3]+""; strs[4] = list.get(i)[4]+""; strs[5] = String.valueOf(Double.parseDouble(list.get(i)[2]+"")+Double.parseDouble(list.get(i)[3]+"")); strs[6] = String.valueOf(Double.parseDouble(strs[5])-Double.parseDouble(list.get(i)[7]+"")<0?0:Double.parseDouble(strs[5])-Double.parseDouble(list.get(i)[7]+"")); showList.add(strs); sum[1] = String.valueOf(Double.parseDouble(strs[1])+Double.parseDouble(sum[1])); sum[2] = String.valueOf(Double.parseDouble(strs[2])+Double.parseDouble(sum[2])); sum[3] = String.valueOf(Double.parseDouble(strs[3])+Double.parseDouble(sum[3])); sum[4] = String.valueOf(Double.parseDouble(strs[4])+Double.parseDouble(sum[4])); sum[5] = String.valueOf(Double.parseDouble(strs[5])+Double.parseDouble(sum[5])); sum[6] = String.valueOf(Double.parseDouble(strs[6])+Double.parseDouble(sum[6])); } showList.add(sum); } request.setAttribute("showList", showList); return "success"; } }
[ "657603429@qq.com" ]
657603429@qq.com
7c3c1c44650526e03db02c8c5c892a0dc2e2ce14
be73270af6be0a811bca4f1710dc6a038e4a8fd2
/crash-reproduction-moho/results/XWIKI-13141-23-13-NSGA_II-WeightedSum:TestLen:CallDiversity/org/xwiki/container/servlet/filters/internal/SetCharacterEncodingFilter_ESTest_scaffolding.java
7801083fee38b03e644a6d936852d965a83dcfea
[]
no_license
STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application
cf118b23ecb87a8bf59643e42f7556b521d1f754
3bb39683f9c343b8ec94890a00b8f260d158dfe3
refs/heads/master
2022-07-29T14:44:00.774547
2020-08-10T15:14:49
2020-08-10T15:14:49
285,804,495
0
0
null
null
null
null
UTF-8
Java
false
false
475
java
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Sun Jan 19 03:24:25 UTC 2020 */ package org.xwiki.container.servlet.filters.internal; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; @EvoSuiteClassExclude public class SetCharacterEncodingFilter_ESTest_scaffolding { // Empty scaffolding for empty test suite }
[ "pouria.derakhshanfar@gmail.com" ]
pouria.derakhshanfar@gmail.com
8fda31b1592092b35d20c29ec511b5fb862cc1f6
132979b7af2ddde19095e76f26fa43eaa81671a9
/selenium-project/src/test/java/com/james/training/selenium_project/uielementspagetests/HorizontalSliderTest.java
b5d63954cafd19c70de197fdf4d110e5cf296173
[]
no_license
jamesngondo2013/Java-Selenium-Automation-Framework
3184f6a8754a67ed948be5fdee667d98f1f2ed67
59fd1b1cd9fc673ff6794e96c6d64c81e37a64c2
refs/heads/master
2022-06-23T12:01:29.168482
2020-06-06T13:18:46
2020-06-06T13:18:46
223,250,003
0
0
null
2022-06-21T02:41:35
2019-11-21T19:33:47
HTML
UTF-8
Java
false
false
967
java
package com.james.training.selenium_project.uielementspagetests; import org.testng.Assert; import org.testng.annotations.Test; import com.james.training.selenium_project.basetest.TestUtilities; import com.james.training.selenium_project.pages.HorizontalSliderPage; import com.james.training.selenium_project.pages.WelcomePage; public class HorizontalSliderTest extends TestUtilities{ @Test public void sliderTest() { // Open WelcomePage WelcomePage welcomePage = new WelcomePage(getDriver(), log); welcomePage.openPage(); //open horizontal slider page HorizontalSliderPage horizontalSilderPage = welcomePage.clickHorizontalSliderPageLink(); String value = "3.5"; // Set slider value sleep(2000); horizontalSilderPage.setSliderTo(value); sleep(2000); // Verify slider value String sliderValue = horizontalSilderPage.getSliderValue(); Assert.assertTrue(sliderValue.equals(value), "Range is not correct. It is: " + sliderValue); } }
[ "jamesngondo2013@outlook.com" ]
jamesngondo2013@outlook.com
012aa16e9550e42ef3d3fd7461770fa10fd95ef1
b7dbfe6d99dc7f43c6c25c44fb84093d3cbbc39e
/src/main/java/com/app/twitterstreaming/consumer/TwitterConsumer.java
1521ad740732a81650552f9cee36d03ac3fa26c8
[]
no_license
giri-nitesh/twitter-streaming
65fb4b23cbcb2b5ea629b6b19696372cb44c677a
fc64f58a5a82d0f39e8830abd801f58687613654
refs/heads/master
2022-06-02T00:42:41.594619
2019-09-17T10:15:11
2019-09-17T10:15:11
206,628,281
2
0
null
2022-05-20T21:08:33
2019-09-05T18:11:33
Java
UTF-8
Java
false
false
2,262
java
package com.app.twitterstreaming.consumer; import java.util.ArrayList; import java.util.List; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.app.twitterstreaming.model.Tweet; import com.app.twitterstreaming.service.KafkaConsumerService; import com.google.gson.Gson; /** * * @author Nitesh * Represents Twitter Consumer that fetches tweets from * Kafka queue * */ public class TwitterConsumer implements KafkaConsumerService { private static final Logger LOGGER = LoggerFactory.getLogger(TwitterConsumer.class); /** * @param offset Represents the starting point of * message in the queue * @param size Represents the size of the response to be * returned to the caller * @param kafkaTopicName Represents the topic name for which * the tweets needs to be fetched */ public List<Tweet> getTweets(int offset, int size, String kafkaTopicName) { KafkaConsumer<String, String> kafkaConsumer = null; boolean flag = true; List<Tweet> messagesFromKafka = new ArrayList<>(); int recordCount = 0; int i = 0; KafkaTweetConsumer tweetConsumer = new KafkaTweetConsumer(kafkaTopicName); kafkaConsumer = tweetConsumer.createConsumer(); LOGGER.info("Creaetd a consumer successfully which has been subscribed to : {} ", tweetConsumer.getTopic()); while (flag) { // will consume all the messages and store in records ConsumerRecords<String, String> records = kafkaConsumer.poll(1000); // getting total records count recordCount = records.count(); Gson gson = new Gson(); for (ConsumerRecord<String, String> record : records) { if(record.value() != null) { if (i >= recordCount - size) { // adding last 'size' messages to messagesFromKafka Tweet tweet = gson.fromJson(record.value(), Tweet.class); LOGGER.info("Tweet with id: {} processed", tweet.getId()); messagesFromKafka.add(tweet); } i++; } } if (recordCount > 0) { flag = false; } } LOGGER.info("Fetched {} messages from Kafka", size); kafkaConsumer.close(); return messagesFromKafka; } }
[ "giri17nit@gmail.com" ]
giri17nit@gmail.com
43027467870110b26e7d1d00f54f682c25b35edb
d0e73cda30de4ef0d66d07561c6f572a0f1d952f
/jspwiki-war/src/test/java/org/apache/wiki/plugin/GroupsTest.java
5a59584ad2e84b329834037425d64d3243c06eb6
[ "Apache-2.0", "MPL-2.0", "BSD-2-Clause", "CC-BY-2.5", "DOC", "LicenseRef-scancode-jdom", "Apache-1.1", "CPL-1.0", "MPL-1.1", "BSD-3-Clause", "CDDL-1.0", "MIT" ]
permissive
managanesh/jspwiki
9846293491cacad90efe4c87dfe86a877172fcfe
a3c80aa35ba33f9097ce8e3cb44a155155493459
refs/heads/trunk
2023-04-28T04:42:27.121021
2015-08-20T08:54:26
2015-08-20T08:54:26
18,417,527
0
0
Apache-2.0
2023-04-15T18:43:39
2014-04-03T20:40:03
Java
UTF-8
Java
false
false
2,105
java
/* 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.wiki.plugin; import java.util.Properties; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.wiki.TestEngine; public class GroupsTest extends TestCase { Properties props = new Properties(); TestEngine testEngine; public GroupsTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( TestEngine.findTestProperties() ); testEngine = new TestEngine(props); } public void tearDown() throws Exception { super.tearDown(); testEngine.deletePage( "Test" ); } public void testTag() throws Exception { String src="[{Groups}]"; testEngine.saveText( "Test", src ); String res = testEngine.getHTML( "Test" ); assertEquals( "<a href=\"/Group.jsp?group=Admin\">Admin</a>, " + "<a href=\"/Group.jsp?group=Art\">Art</a>, " + "<a href=\"/Group.jsp?group=Literature\">Literature</a>, " + "<a href=\"/Group.jsp?group=TV\">TV</a>\n" , res ); } public static Test suite() { return new TestSuite( GroupsTest.class ); } }
[ "juanpablo@apache.org" ]
juanpablo@apache.org
58eb1d1aa0f39414220cfe1f4fb145a9d30eba0d
adffbe6b1ca38a8a999e1a291ae7bc7b4840010c
/src/main/java/com/forever17/project/charityquest/pojos/entity/ReturnStatus.java
e4d7d963d0adfbdfad1062b23f73c81fcc4ad30e
[]
no_license
Nvpiao/charityquest-backend
0dca0c0f5f475a155bd72e7031fe92790deecf5a
207362795cc50e2cc21b774623e29f55e7a3d5e4
refs/heads/master
2022-11-11T09:52:37.536586
2020-04-21T15:48:38
2020-04-21T15:48:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,954
java
package com.forever17.project.charityquest.pojos.entity; import com.forever17.project.charityquest.constants.CharityCodes; import com.forever17.project.charityquest.enums.StatusType; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Setter; import java.util.Collections; import java.util.List; /** * Return Status of Project * * @author MingLiu (MLiu54@sheffield.ac.uk) * @version 1.0 * @date 15 Feb 2020 * @since 1.0 */ @Getter @Setter @NoArgsConstructor @RequiredArgsConstructor @AllArgsConstructor public class ReturnStatus { /** * messages */ @NonNull private List<String> returnMsgs; /** * result error code */ @NonNull private String returnCode; /** * state of request */ private StatusType statusType = StatusType.SUCCESS; /** * result data */ private Object data; // success public ReturnStatus(String returnMsg) { this(returnMsg, CharityCodes.GLOBAL_SUCCESS); } // success public ReturnStatus(String returnMsg, String returnCode) { this(Collections.singletonList(returnMsg), returnCode); } // success public ReturnStatus(String returnMsg, Object data) { this(Collections.singletonList(returnMsg), CharityCodes.GLOBAL_SUCCESS, StatusType.SUCCESS, data); } public ReturnStatus(String returnMsg, String returnCode, StatusType statusType) { this(Collections.singletonList(returnMsg), returnCode, statusType, null); } public ReturnStatus(String returnMsg, String returnCode, StatusType statusType, Object data) { this(Collections.singletonList(returnMsg), returnCode, statusType, data); } public ReturnStatus(List<String> returnMsg, String returnCode, StatusType statusType) { this(returnMsg, returnCode, statusType, null); } }
[ "mliu54@sheffield.ac.uk" ]
mliu54@sheffield.ac.uk
6e291afc63ae05dbf44e1c2f7ce735334bedc1e4
ff8169eb5ed08e233aaefe336338252c15c03488
/src/main/MyMain.java
e1e981ae6e93f635f88bf09f69353bf5247beb69
[]
no_license
prajjwal-cs/QueueUsingLinkedList
ae239f443c7dd5f7fa78c03072e30d99f9ad305f
bef2962c8f06cc8acd3f3d59510515f61aa6586b
refs/heads/master
2023-03-11T15:58:03.741767
2021-02-26T20:20:23
2021-02-26T20:20:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
631
java
/* Created by IntelliJ IDEA. Author: Prajjwal Pachauri(cypher) Date: 26-02-2021 Time: 23:46 File: MyMain.java */ package main; import implementation.MyQueue; public class MyMain { public static void main(String[] args) { MyQueue<Integer> queue = new MyQueue<>(); queue.enqueue(10); queue.enqueue(20); queue.enqueue(30); queue.enqueue(40); queue.traverse(); int size = queue.size(); System.out.println("Size --> " + size); queue.dequeue(); queue.traverse(); size = queue.size(); System.out.println("Size --> " + size); } }
[ "prajjwalpachauri725@gmail.com" ]
prajjwalpachauri725@gmail.com
6b156d8c4015f89975c635dbfba41b5124ad8776
0e06e096a9f95ab094b8078ea2cd310759af008b
/classes52-dex2jar/com/google/android/gms/games/video/zza.java
50cf53bd97089f4594d8732acc9c56ea8a07d5a6
[]
no_license
Manifold0/adcom_decompile
4bc2907a057c73703cf141dc0749ed4c014ebe55
fce3d59b59480abe91f90ba05b0df4eaadd849f7
refs/heads/master
2020-05-21T02:01:59.787840
2019-05-10T00:36:27
2019-05-10T00:36:27
185,856,424
1
2
null
2019-05-10T00:36:28
2019-05-09T19:04:28
Java
UTF-8
Java
false
false
303
java
// // Decompiled by Procyon v0.5.34 // package com.google.android.gms.games.video; import com.google.android.gms.common.internal.safeparcel.SafeParcelReader; import android.os.Parcel; import android.os.Parcelable$Creator; public final class zza implements Parcelable$Creator<VideoCapabilities> { }
[ "querky1231@gmail.com" ]
querky1231@gmail.com
148f87882e66e2c94356833c14cbcf7fa21fc25a
d605b91301373752a27c7906976b6457be800836
/Joakim/Assigment1_Task6/GlobalSimulation.java
5bb376fb938eb92cc9e6a69141465756cf008104
[]
no_license
olivernilssen/EITN95_Simulation_A1
bb348443d58eaaae387a0c21c34efbb740681605
660cab18c4e18615db925051125212d14fe3fffe
refs/heads/master
2022-04-26T05:12:08.124789
2020-05-01T13:03:25
2020-05-01T13:03:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
789
java
public class GlobalSimulation{ // This class contains the definition of the events that shall take place in the // simulation. It also contains the global time, the event list and also a method // for insertion of events in the event list. That is just for making the code in // MainSimulation.java and State.java simpler (no dot notation is needed). public static final int ARRIVAL = 1, DEPART = 2, MEASURE = 3; // The events, add or remove if needed! public static double time = 0; // The global time variable public static EventListClass eventList = new EventListClass(); // The event list used in the program public static void insertEvent(int type, double TimeOfEvent){ // Just to be able to skip dot notation eventList.InsertEvent(type, TimeOfEvent); } }
[ "noreply@github.com" ]
noreply@github.com
9a2cb02f330068c955101a82515c214e7452baac
e9d3fd05bd49f3c5c95f67feb37b86bb4b8d422b
/org.xtext.example.msat.tests/src-gen/org/xtext/example/mydsl1/tests/MSatInjectorProvider.java
26bec63703a0cedbb35c7089d679db760128a900
[]
no_license
diverse-project/SAT-DSLmorphic
6ac5ba9cc93faa915f8b1d6ac28bb40571cec029
a2c4a56566a0e28a26ba0f0d12a306160eff52eb
refs/heads/master
2020-07-24T09:38:16.448423
2020-01-08T10:53:56
2020-01-08T10:53:56
207,883,485
0
15
null
2020-01-08T11:04:01
2019-09-11T18:48:10
Jupyter Notebook
UTF-8
Java
false
false
1,927
java
/* * generated by Xtext 2.19.0 */ package org.xtext.example.mydsl1.tests; import com.google.inject.Guice; import com.google.inject.Injector; import org.eclipse.xtext.testing.GlobalRegistries; import org.eclipse.xtext.testing.GlobalRegistries.GlobalStateMemento; import org.eclipse.xtext.testing.IInjectorProvider; import org.eclipse.xtext.testing.IRegistryConfigurator; import org.xtext.example.mydsl1.MSatRuntimeModule; import org.xtext.example.mydsl1.MSatStandaloneSetup; public class MSatInjectorProvider implements IInjectorProvider, IRegistryConfigurator { protected GlobalStateMemento stateBeforeInjectorCreation; protected GlobalStateMemento stateAfterInjectorCreation; protected Injector injector; static { GlobalRegistries.initializeDefaults(); } @Override public Injector getInjector() { if (injector == null) { this.injector = internalCreateInjector(); stateAfterInjectorCreation = GlobalRegistries.makeCopyOfGlobalState(); } return injector; } protected Injector internalCreateInjector() { return new MSatStandaloneSetup() { @Override public Injector createInjector() { return Guice.createInjector(createRuntimeModule()); } }.createInjectorAndDoEMFRegistration(); } protected MSatRuntimeModule createRuntimeModule() { // make it work also with Maven/Tycho and OSGI // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=493672 return new MSatRuntimeModule() { @Override public ClassLoader bindClassLoaderToInstance() { return MSatInjectorProvider.class .getClassLoader(); } }; } @Override public void restoreRegistry() { stateBeforeInjectorCreation.restoreGlobalState(); stateBeforeInjectorCreation = null; } @Override public void setupRegistry() { stateBeforeInjectorCreation = GlobalRegistries.makeCopyOfGlobalState(); if (injector == null) { getInjector(); } stateAfterInjectorCreation.restoreGlobalState(); } }
[ "mathieu.acher@irisa.fr" ]
mathieu.acher@irisa.fr
d932e0c5145dadf127c2ebb1220caf7c7b7d1529
0e99f85269b18602ac0e6df1dcfbdbf093dd607b
/src/client/gui/fxcontrol/EIPManagement.java
6353c08068e1459bbcc5e57fac3fe7e6e60a711c
[ "MIT" ]
permissive
leprekon91/AES14
37dc86684536aeec116d967a1eb1bd30c2f977a5
288ff4e8605e5babfd45cc423e22303846f9c716
refs/heads/master
2020-03-18T09:44:48.245013
2018-07-09T05:39:37
2018-07-09T05:39:37
134,578,577
2
3
null
2018-06-04T13:47:37
2018-05-23T14:04:22
Java
UTF-8
Java
false
false
1,858
java
package client.gui.fxcontrol; import client.control.TeacherControl; import com.Contract; import com.data.ExamInProgress; import com.data.Message; import javafx.event.ActionEvent; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.ListView; import javafx.stage.Stage; import java.io.IOException; import java.util.Optional; public class EIPManagement { public ListView eipList; public void initialize() { eipList.setCellFactory(list -> new EipListCell()); eipList.setItems(TeacherControl.getInstance().eips); } public void startNewExam(ActionEvent actionEvent) { ExamInProgress examInProgress = new ExamInProgress(null, null, null, null, TeacherControl.getInstance().teacher, null, false); try { CreateNewEIPDialog.openWindow(new Stage(), examInProgress); } catch (IOException e) { e.printStackTrace(); } } public void openExtensionRequest(ActionEvent actionEvent) { ExtensionRequestWindow.openWindow((ExamInProgress) eipList.getSelectionModel().getSelectedItems().get(0)); } public void lockExam(ActionEvent actionEvent) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirmation"); alert.setHeaderText("Confirm Lock"); alert.setContentText("Are you sure you want to lock this exam?"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { ExamInProgress eip = (ExamInProgress) eipList.getSelectionModel().getSelectedItems().get(0); try { TeacherControl.getInstance().client.sendToServer(new Message(Contract.LOCK_EXAM, eip)); } catch (IOException e) { e.printStackTrace(); } } } }
[ "reist2009@gmail.com" ]
reist2009@gmail.com
c70dadb4d12a61484819737d08d5ab2baac15372
dd76d0b680549acb07278b2ecd387cb05ec84d64
/divestory-Fernflower/androidx/documentfile/provider/TreeDocumentFile.java
96020a98439391654894a0f46ce7aadbea874b1d
[]
no_license
ryangardner/excursion-decompiling
43c99a799ce75a417e636da85bddd5d1d9a9109c
4b6d11d6f118cdab31328c877c268f3d56b95c58
refs/heads/master
2023-07-02T13:32:30.872241
2021-08-09T19:33:37
2021-08-09T19:33:37
299,657,052
0
0
null
null
null
null
UTF-8
Java
false
false
3,124
java
package androidx.documentfile.provider; import android.content.Context; import android.net.Uri; import android.provider.DocumentsContract; class TreeDocumentFile extends DocumentFile { private Context mContext; private Uri mUri; TreeDocumentFile(DocumentFile var1, Context var2, Uri var3) { super(var1); this.mContext = var2; this.mUri = var3; } private static void closeQuietly(AutoCloseable var0) { if (var0 != null) { try { var0.close(); } catch (RuntimeException var1) { throw var1; } catch (Exception var2) { } } } private static Uri createFile(Context var0, Uri var1, String var2, String var3) { try { Uri var5 = DocumentsContract.createDocument(var0.getContentResolver(), var1, var2, var3); return var5; } catch (Exception var4) { return null; } } public boolean canRead() { return DocumentsContractApi19.canRead(this.mContext, this.mUri); } public boolean canWrite() { return DocumentsContractApi19.canWrite(this.mContext, this.mUri); } public DocumentFile createDirectory(String var1) { Uri var2 = createFile(this.mContext, this.mUri, "vnd.android.document/directory", var1); TreeDocumentFile var3; if (var2 != null) { var3 = new TreeDocumentFile(this, this.mContext, var2); } else { var3 = null; } return var3; } public DocumentFile createFile(String var1, String var2) { Uri var3 = createFile(this.mContext, this.mUri, var1, var2); TreeDocumentFile var4; if (var3 != null) { var4 = new TreeDocumentFile(this, this.mContext, var3); } else { var4 = null; } return var4; } public boolean delete() { try { boolean var1 = DocumentsContract.deleteDocument(this.mContext.getContentResolver(), this.mUri); return var1; } catch (Exception var3) { return false; } } public boolean exists() { return DocumentsContractApi19.exists(this.mContext, this.mUri); } public String getName() { return DocumentsContractApi19.getName(this.mContext, this.mUri); } public String getType() { return DocumentsContractApi19.getType(this.mContext, this.mUri); } public Uri getUri() { return this.mUri; } public boolean isDirectory() { return DocumentsContractApi19.isDirectory(this.mContext, this.mUri); } public boolean isFile() { return DocumentsContractApi19.isFile(this.mContext, this.mUri); } public boolean isVirtual() { return DocumentsContractApi19.isVirtual(this.mContext, this.mUri); } public long lastModified() { return DocumentsContractApi19.lastModified(this.mContext, this.mUri); } public long length() { return DocumentsContractApi19.length(this.mContext, this.mUri); } public DocumentFile[] listFiles() { // $FF: Couldn't be decompiled } public boolean renameTo(String param1) { // $FF: Couldn't be decompiled } }
[ "ryan.gardner@coxautoinc.com" ]
ryan.gardner@coxautoinc.com
5dadbbaf9bfa1badcd34533aec67903235154c20
6967754e556accd29d7764f0a196dc4573afd94e
/errai-jaxrs/errai-jaxrs-client/src/test/java/org/jboss/errai/enterprise/jaxrs/server/QueryParamTestServiceImpl.java
17dda6a28c93d7f583c04d91d4b67d6296f22bf2
[]
no_license
wclaeys/errai
5ecdda91b78b5c69777f73c0871bd98c56a70db6
f13151ba300c0b18c6a2531d4fb6c9642b811cea
refs/heads/master
2021-01-18T04:25:49.476218
2012-11-04T11:11:35
2012-11-04T11:11:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,518
java
/* * Copyright 2011 JBoss, by Red Hat, 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.jboss.errai.enterprise.jaxrs.server; import org.jboss.errai.enterprise.jaxrs.client.shared.QueryParamTestService; /** * Implementation of {@link QueryParamTestService} returning test data. * * @author Christian Sadilek <csadilek@redhat.com> */ public class QueryParamTestServiceImpl implements QueryParamTestService { @Override public Long getWithQueryParam(long id) { return id; } @Override public String getWithStringQueryParam(String id) { return id; } @Override public String getWithMultipleQueryParams(long id1, long id2) { return "" + id1 + "/" + id2; } @Override public int postWithQueryParam(int id) { return id; } @Override public Double putWithQueryParam(Double id) { return id; } @Override public short deleteWithQueryParam(short id) { return id; } @Override public void headWithQueryParam(long id) { } }
[ "christian.sadilek@gmail.com" ]
christian.sadilek@gmail.com