blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
5d2d17e961ef219d4ba3b951f61debc55e2c1db8
22,522,808,547,019
97989671c4228498ff0968cf2a359894d3015768
/CoreTesting/src/au/gov/asd/tac/constellation/testing/NBFilesystemTestAction.java
fa677a4fe76f2f5be017149c9f605d866892a44a
[ "Apache-2.0" ]
permissive
constellation-app/constellation
https://github.com/constellation-app/constellation
d8ef3156f6f8b39da8636a41b16191678b9edac0
a0489877b4c77fb6c7a47c66a947895af35ecf19
refs/heads/master
2023-09-02T13:52:54.448000
2023-08-30T00:51:47
2023-08-30T00:51:47
196,507,883
393
105
Apache-2.0
false
2023-09-12T04:40:36
2019-07-12T04:19:50
2023-09-08T17:55:44
2023-09-12T04:40:36
67,591
367
54
121
Java
false
false
/* * Copyright 2010-2021 Australian Signals Directorate * * 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 au.gov.asd.tac.constellation.testing; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.logging.Level; import java.util.logging.Logger; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.NbBundle.Messages; @ActionID(category = "Experimental", id = "au.gov.asd.tac.constellation.testing.NBFilesystemTestAction") @ActionRegistration(displayName = "#CTL_NBFilesystemTestAction") @ActionReference(path = "Menu/Experimental/Developer", position = 0) @Messages("CTL_NBFilesystemTestAction=Test NetBeans File System") public final class NBFilesystemTestAction implements ActionListener { private static final Logger LOGGER = Logger.getLogger(NBFilesystemTestAction.class.getName()); @Override public void actionPerformed(final ActionEvent e) { final FileObject root = FileUtil.getConfigRoot(); for (final FileObject fo : root.getChildren()) { LOGGER.log(Level.INFO, "object: {0}", fo.getPath()); } final FileObject toolbars = root.getFileObject("Toolbars"); descend(toolbars, 0); } private static void descend(final FileObject fo, final int level) { final String fmt = String.format("%%%ds", (level + 1) * 2); final String log = String.format(fmt + " %s %s\n", " ", fo.getNameExt(), fo.getAttribute("position")); LOGGER.log(Level.INFO, log); for (final FileObject child : fo.getChildren()) { descend(child, level + 1); } } }
UTF-8
Java
2,292
java
NBFilesystemTestAction.java
Java
[]
null
[]
/* * Copyright 2010-2021 Australian Signals Directorate * * 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 au.gov.asd.tac.constellation.testing; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.logging.Level; import java.util.logging.Logger; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.NbBundle.Messages; @ActionID(category = "Experimental", id = "au.gov.asd.tac.constellation.testing.NBFilesystemTestAction") @ActionRegistration(displayName = "#CTL_NBFilesystemTestAction") @ActionReference(path = "Menu/Experimental/Developer", position = 0) @Messages("CTL_NBFilesystemTestAction=Test NetBeans File System") public final class NBFilesystemTestAction implements ActionListener { private static final Logger LOGGER = Logger.getLogger(NBFilesystemTestAction.class.getName()); @Override public void actionPerformed(final ActionEvent e) { final FileObject root = FileUtil.getConfigRoot(); for (final FileObject fo : root.getChildren()) { LOGGER.log(Level.INFO, "object: {0}", fo.getPath()); } final FileObject toolbars = root.getFileObject("Toolbars"); descend(toolbars, 0); } private static void descend(final FileObject fo, final int level) { final String fmt = String.format("%%%ds", (level + 1) * 2); final String log = String.format(fmt + " %s %s\n", " ", fo.getNameExt(), fo.getAttribute("position")); LOGGER.log(Level.INFO, log); for (final FileObject child : fo.getChildren()) { descend(child, level + 1); } } }
2,292
0.723386
0.715532
56
39.92857
29.437498
110
false
false
0
0
0
0
0
0
0.660714
false
false
13
39b777a1d4f29cdc6aa93d211bd9b579699e106c
22,522,808,546,355
ebb602cbb5ac332a5a026e9fb2475a840a3bb351
/app/src/main/java/com/udacity/stockhawk/utils/StockUtils.java
1417790f7362ae2d2a14723cdcf740f00ce00f1c
[]
no_license
nowxd/StockHawk
https://github.com/nowxd/StockHawk
a0c2ce101a0cb57591a6bd990e4c14ef1e7f4ff9
35a0928312a71d70072cc4da125d13751b527416
refs/heads/master
2021-01-22T18:50:11.755000
2017-04-05T13:26:04
2017-04-05T13:26:04
85,116,414
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.udacity.stockhawk.utils; import android.content.Context; import android.support.annotation.IntDef; import com.udacity.stockhawk.data.PrefUtils; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import timber.log.Timber; public class StockUtils { public static final int STATUS_OK = 0; public static final int STATUS_DUPLICATE_EXISTS = 1; public static final int STATUS_STOCK_DOES_NOT_EXIST = 2; public static final int STATUS_NETWORK_ERROR = 3; /** * Must be called asynchronously since there is a network call with YahooUtils */ public static int validStockSymbol(Context context, String symbol) { // Already added boolean duplicateExists = PrefUtils.checkStockExistsPref(context, symbol); if (duplicateExists) { return STATUS_DUPLICATE_EXISTS; } // Check if Yahoo can identify the symbol int yahooStatus = YahooUtils.checkStockExistsYahoo(symbol); if (yahooStatus == YahooUtils.STOCK_DOES_NOT_EXIST) { return STATUS_STOCK_DOES_NOT_EXIST; } else if (yahooStatus == YahooUtils.NETWORK_ERROR) { return STATUS_NETWORK_ERROR; } else if (yahooStatus == YahooUtils.STOCK_EXISTS) { return STATUS_OK; } throw new UnsupportedOperationException("Invalid Status"); } }
UTF-8
Java
1,393
java
StockUtils.java
Java
[]
null
[]
package com.udacity.stockhawk.utils; import android.content.Context; import android.support.annotation.IntDef; import com.udacity.stockhawk.data.PrefUtils; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import timber.log.Timber; public class StockUtils { public static final int STATUS_OK = 0; public static final int STATUS_DUPLICATE_EXISTS = 1; public static final int STATUS_STOCK_DOES_NOT_EXIST = 2; public static final int STATUS_NETWORK_ERROR = 3; /** * Must be called asynchronously since there is a network call with YahooUtils */ public static int validStockSymbol(Context context, String symbol) { // Already added boolean duplicateExists = PrefUtils.checkStockExistsPref(context, symbol); if (duplicateExists) { return STATUS_DUPLICATE_EXISTS; } // Check if Yahoo can identify the symbol int yahooStatus = YahooUtils.checkStockExistsYahoo(symbol); if (yahooStatus == YahooUtils.STOCK_DOES_NOT_EXIST) { return STATUS_STOCK_DOES_NOT_EXIST; } else if (yahooStatus == YahooUtils.NETWORK_ERROR) { return STATUS_NETWORK_ERROR; } else if (yahooStatus == YahooUtils.STOCK_EXISTS) { return STATUS_OK; } throw new UnsupportedOperationException("Invalid Status"); } }
1,393
0.687724
0.684853
47
28.638298
26.274675
82
false
false
0
0
0
0
0
0
0.425532
false
false
13
18050e6008d8ba50bbdfa2c4e66ad54991122aaa
22,497,038,699,921
5e968095e548beb73d814a368566efa2a7f253f8
/src/main/java/bot/HeroB.java
1fa4415674f12b6342e9d40d04c7a2c5a39d6832
[]
no_license
AidarBabanov/simulator2
https://github.com/AidarBabanov/simulator2
2c55b7f67945857c57188b62b84ed79dc8c43f01
cb8ab745f60d589363317c027af44c345dcbda21
refs/heads/master
2020-03-09T02:23:24.725000
2018-12-29T08:03:21
2018-12-29T08:03:21
128,538,422
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bot; import com.google.gson.JsonObject; public class HeroB { private int health; private HeroPowerB heroPowerB; public HeroB() { } public HeroB(JsonObject jsonObject) { int health = jsonObject.get("currentHealth").getAsInt(); this.setHealth(health); this.setHeroPowerB(new HeroPowerB(jsonObject.get("heroPower").getAsJsonObject())); } public int getHealth() { return health; } public void setHealth(int health) { this.health = health; } public HeroPowerB getHeroPowerB() { return heroPowerB; } public void setHeroPowerB(HeroPowerB heroPowerB) { this.heroPowerB = heroPowerB; } }
UTF-8
Java
707
java
HeroB.java
Java
[]
null
[]
package bot; import com.google.gson.JsonObject; public class HeroB { private int health; private HeroPowerB heroPowerB; public HeroB() { } public HeroB(JsonObject jsonObject) { int health = jsonObject.get("currentHealth").getAsInt(); this.setHealth(health); this.setHeroPowerB(new HeroPowerB(jsonObject.get("heroPower").getAsJsonObject())); } public int getHealth() { return health; } public void setHealth(int health) { this.health = health; } public HeroPowerB getHeroPowerB() { return heroPowerB; } public void setHeroPowerB(HeroPowerB heroPowerB) { this.heroPowerB = heroPowerB; } }
707
0.643564
0.643564
33
20.424242
21.405226
90
false
false
0
0
0
0
0
0
0.333333
false
false
13
cee4e357c19cb59189a740b6863cf0cb830aa153
30,614,526,893,377
ce8e70cd4bc9d9e5d7ebcc7b57b6501bb970270c
/Exam/T2/TestExpr2.java
c7ba2c99ac4d43ccaa0c6787a1dd4eb9a8ea3b42
[]
no_license
airone-cenerino/programmingA
https://github.com/airone-cenerino/programmingA
1899492f87f740714509c12c0c94816cd3293b5f
af428900165489b7388adb49208e8f6b8100709f
refs/heads/master
2022-01-24T20:23:36.817000
2019-07-24T02:44:21
2019-07-24T02:44:21
180,090,684
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class TestExpr2 { public static void main(String args[]) { Expr e0 = new Num(3); // outputs "e0.eval() is 3" System.out.println("e0.eval() is " + e0.eval()); Expr e1 = new Times(new Plus(new Num(-2),e0),new Num(4)); // outputs "e1.eval() is 4" System.out.println("e1.eval() is " + e1.eval()); Expr e2 = new Plus(e1,new Times(new Num(99),new Num(-101))); // outputs "e2.eval() is -9995" System.out.println("e2.eval() is " + e2.eval()); Expr e3 = new Minus(new Num(100),new Num(99)); // outputs "e3.eval() is 1" System.out.println("e3.eval() is " + e3.eval()); // outputs "e4 is (4*5-(100-99))" Expr e4 = new Minus(new Times(new Num(4),new Num(5)),e3); // outputs "e4.eval() is 19" System.out.println("e4.eval() is " + e4.eval()); } }
UTF-8
Java
764
java
TestExpr2.java
Java
[]
null
[]
public class TestExpr2 { public static void main(String args[]) { Expr e0 = new Num(3); // outputs "e0.eval() is 3" System.out.println("e0.eval() is " + e0.eval()); Expr e1 = new Times(new Plus(new Num(-2),e0),new Num(4)); // outputs "e1.eval() is 4" System.out.println("e1.eval() is " + e1.eval()); Expr e2 = new Plus(e1,new Times(new Num(99),new Num(-101))); // outputs "e2.eval() is -9995" System.out.println("e2.eval() is " + e2.eval()); Expr e3 = new Minus(new Num(100),new Num(99)); // outputs "e3.eval() is 1" System.out.println("e3.eval() is " + e3.eval()); // outputs "e4 is (4*5-(100-99))" Expr e4 = new Minus(new Times(new Num(4),new Num(5)),e3); // outputs "e4.eval() is 19" System.out.println("e4.eval() is " + e4.eval()); } }
764
0.603403
0.530105
20
37.200001
16.403048
61
false
false
0
0
0
0
0
0
1.65
false
false
13
dd62eb1fd06bd2a00dbd64c04078871f5ef7eea0
24,043,226,928,620
75ee16ee423e272ac123edf9537451606f6fcdd2
/src/ij/plugin/DM3_Reader.java
835185277fc5379f024234fb675cda34b9416169
[ "BSD-3-Clause" ]
permissive
luttero/Maud
https://github.com/luttero/Maud
0b031a40f94b3f6519ef3b74f883a19c8b82788b
51b07e0c36011c68d71c6d0dfbfb6a1992c18eec
refs/heads/version2
2023-06-21T20:13:03.621000
2023-06-19T15:37:29
2023-06-19T15:37:29
81,939,182
5
5
BSD-3-Clause
false
2022-08-05T16:26:19
2017-02-14T11:36:38
2022-05-25T22:53:06
2022-08-05T16:26:18
180,699
2
4
2
Java
false
false
package ij.plugin; import java.io.*; import java.util.*; // for the Vector and Hashtable classes import ij.*; import ij.process.*; import ij.io.*; import ij.measure.*; // ------------------------------------------ // DM3_Reader.java // ------------------------------------------ // This plugin will read DM3 files produced by Gatan Digital Micrograph // Decoding is based on info gleaned from the EMAN project based at Baylor // Made a start using the Analyze_Reader plugin by Guy Williams and // the Biorad_Reader as a base, but not that much remains. // The guts were significantly inspired by the GatanDM3.C and // GatanDM3.h files of the EMAN project source code: // http://ncmi.bcm.tmc.edu/~stevel/EMAN/doc/ // ------------------------------------ // Greg Jefferis, // Dept Biological Sciences, // Stanford University // jefferis@stanford.edu // ------------------------------------------- // as of v1.0.1 030615 // ------------------------------------------- // - reads 16 bit images only, // - correctly parses all simple tags // - Places tags in File/Show Info // including acquisition time / sample date etc. // - allows spatial calibration of images // - sets minimum and maximum intensity // ------------------------------------ // as of v1.1 030615 // - went back to making it an ImagePlus extension // ------------------------------------ // as of v1.2.6 030618 // - Corrected a bad bug - The offset for the image data was off // by +1 // - AND I never told the image opener whether the image data was // in little endian format or not. // - So what I was doing was reading one byte from pixel n and one from pixel n+1! // (which looked more or less like the correct number in big-endian) // - Added my best guess for what ImageJ image type should be set for // the standard data types // - Changed load(), parseDM3() and getDM3FileInfo functions to receive // directory and FileName as parameters - that way load() can be called // directly bypassing the run() function. // ------------------------------------ // v 1.2.7 030621 // - Most functions were previously defined as public, now restricted // to those that might actually get an external call // - read through code once making a few small tidies and improving comments // ------------------------------------ // v 1.2.8 030624 // - Improved ability to set min/max brightness of image according to information // in the Gatan file after bug report from Charles Daghlian at Dartmouth. // This takes place at the end of the load()function. // ------------------------------------ // v 1.2.9 030625 // - Fixed handling of signed 16 bit and 32 bit images by using the // FileInfo.GRAY16_SIGNED and FileInfo.GRAY32_INT constants // & keeping the Calibration object generated by ImageJ when the image // is loaded rather than creating my own from scratch - I had been // throwing away the brightness calibration which ImageJ does on // 16 bit signed images as a result. // & supplying _raw_ values of loVal and hiVal to setMinAndMax() // ------------------------------------ // v 1.3.0 030625 // - Removed calls to functions introduced since Java 1.1 to allow // plugin to run on OS9 Macs with Java 1.1.7 // - However as far as I can see there is a bug in MRJ that prevents // UTF-16 conversion from occurring so unicode strings in the // DM3 tags don't import. Instead there will be a string saying // "couldn't read string blah". This is annoying because the // calibration units are given as a unicode string. // ------------------------------------ // v 1.3.1 030625 // - Fixed UTF-16 conversion bug in MRJ by writing a quick and dirty unicode // reader to be used if the UTF-16 conversion fails. Now correctly // sets the spatial calibration on OS9 // - Another thing that I noticed was that it seemed to be important to // compile with v1.3.1 if one wanted to use the class with v1.1.7 // ------------------------------------ // v 1.3.2 030808 // - Fixed a bug in getDM3FileInfo which meant that the last rather than // the largest image in the DM3 file was chosen // - Fixed a bug in getDM3CalibrationInfo which caused a failure to // recognise "nm" as a valid calibration unit - the problem was caused // by doing (unit == "nm") instead of (unit.equals("nm")) // ------------------------------------ // v 1.3.3 030821 // - Fixed a remaining bug in the image selection routine which now // works for all files that I have available to test. // ------------------------------------ // v 1.3.4 040506 // - Fixed a bug reading in USHORT image data. The problem was that // USHORT data and strings are hard to tell apart. Although Image Data // can be identified categorically, other lumps of data (e.g. LUTs) // scattered throughout the file are harder to spot and will cause problems // if read as a string. Have compromised by reading as string if: // + it isn't image data // + but is an unsigned short array // + of less than 256 bytes // ------------------------------------ // v 1.3.4 051213 (Yes the 2nd v1.3.4 - hadn't noticed a branch!) // - Fixed a bug which prevented units other than �m or nm being passed to // calibration object. Occasioned by a file with units 1/nm // ------------------------------------ // v 1.3.5 051213 // - Adding handling of DIFFRACTION mode images (ie reciprocal space) by // setting FHT property and copying // calibration object. Occasioned by a file with units 1/nm // ------------------------------------ // v 1.3.6 060904 // - Added storing of struct fields to tag list // They are displayed as tag= {1,2,3,4} // This means that Digital Micrograph selection rectangles // can now be identified from Show Info // ------------------------------------ // v 1.3.7 070831 // - debugLevel is now set according to IJ.debugMode // (accesible from Edit ... Options ... Misc) // - Can now open data type 23 (RGBA_UINT8_3_DATA) images // ------------------------------------ // v 1.3.8 080326 // - Fixed a bug in which tag hashes were not cleared when reading a new file // - Small speed improvement by converting tags to String via StringBuffer // - Both thanks to report by Eric Olson at UIUC public class DM3_Reader extends ImagePlus implements PlugIn { // Decide whether to use Gatan's information for determining the min // and maximum brightness thresholds for display or leave to ImageJ // I find Gatan more reliable public boolean useGatanMinMax = true; private boolean littleEndian = true; // default for .dm3 files // nb all tags are written big-endian, it is only the actual data // attached to each tag that may be little-endian (and will be for PC files) //private String directory; //private String fileName; private RandomAccessFile f; // This stream will be used for reading by parseDM3() private FileInfo fi; private String notes = ""; // I will store interesting file info in here // 0=none, 1-3=basic, 4-5=simple, 6-10 verbose private static final int debugLevel = IJ.debugMode?10:0; // the number of the chosen image in the DM3 file // since there apparently may be several - usually at least a thumbnail // I will select the largest image. If there are multiple images // of the same size, the first will be chosen. private int chosenImage = 1; private int curGroupLevel=-1; // Track how deep is the group we are currently reading private static final int MAXDEPTH = 64; // Maximum number of levels of tags private int[] curGroupAtLevelX=new int[MAXDEPTH]; // To track group at current level private String[] curGroupNameAtLevelX=new String[MAXDEPTH]; // To track group name at current level private int[] curTagAtLevelX=new int[MAXDEPTH]; // To track tag number at current level private String curTagName = ""; // the name of the current tag data item // Will use these to store tags private Vector storedTags = new Vector(); private Hashtable tagHash = new Hashtable(); // Set up constants for the different encoded data types used in DM3 files private static final int SHORT = 2; private static final int LONG = 3; private static final int USHORT = 4; private static final int ULONG = 5; private static final int FLOAT = 6; private static final int DOUBLE = 7; private static final int BOOLEAN = 8; private static final int CHAR = 9; private static final int OCTET = 10; private static final int STRUCT = 15; private static final int STRING = 18; private static final int ARRAY = 20; // This the lhs of Image list tags private static final String IMGLIST = "root.ImageList."; // This is the lhs for Document Object List Tags // root.DocumentObjectList.0.AnnotationGroupList.0.AnnotationType = 31 private static final String OBJLIST = "root.DocumentObjectList."; public void run(String arg) { String directory = ""; String fileName = arg; //if (debugLevel>5); if (debugLevel>5) IJ.write("IN:dir = "+directory+", file="+fileName); if ((arg==null) || (arg=="")) { // Choose a file since none specified OpenDialog od = new OpenDialog("Load DM3 File...", arg); fileName = od.getFileName(); if (fileName==null) return; directory = od.getDirectory(); if (debugLevel>5) IJ.write("IF:dir = "+directory+", file="+fileName); } else { // we were sent a filename to open File dest = new File(arg); directory = dest.getParent(); fileName = dest.getName(); if (debugLevel>5) IJ.write("ELSE:dir = "+directory+", file="+fileName); } // Load in the image ImagePlus imp = load(directory, fileName); if (imp==null) return; // Attach the Image Processor setProcessor(fileName, imp.getProcessor()); // Copy the scale info over copyScale(imp); // Copy the Show Info field over setProperty("Info",imp.getProperty("Info")); // and the FHT property (to handle diffraction mode images) if(imp.getProperty("FHT")!=null) setProperty("FHT", imp.getProperty("FHT")); // Show the image if it was selected by the file // chooser, don't if an argument was passed ie // some other ImageJ process called the plugin if (arg.equals("")) show(); } public ImagePlus load(String directory, String fileName) /*throws IOException*/ { if ((fileName == null) || (fileName == "")) return null; if (!directory.endsWith(File.separator)) directory += File.separator; IJ.showStatus("Loading DM3 File: " + directory + fileName); // Clear the lists of tags in which additional info will be stored tagHash.clear(); storedTags.clear(); // Try calling the parse routine try{ parseDM3(directory, fileName);} catch (Exception e) { IJ.showStatus("parseDM3() error"); IJ.showMessage("DM3_Reader", ""+e); return null; } // Make a blank file information object fi = new FileInfo(); // Go and fetch the DM3 specific file Information try {fi=getDM3FileInfo(directory, fileName);} // This is in case of trouble parsing the tag table catch (Exception e) { IJ.showStatus(""); IJ.showMessage("DM3_Reader", "gDM3:"+e); return null; } // Write out Calculated Offset if reqd if(debugLevel>1) IJ.write("Calculated offset = "+fi.offset); if(debugLevel>1) IJ.write("Chosen image = "+chosenImage); // Open the image! FileOpener fo = new FileOpener(fi); ImagePlus imp = fo.open(false); //if(debugLevel>5) if(imp==null) IJ.write("Image load failed!"); // Write out the contents of the storedTags list // and set the value of notes StringBuffer notesBuffer=new StringBuffer(); for (int i = 0; i<storedTags.size();i++){ // Can decide whether I want to do this //IJ.log((String) storedTags.elementAt(i)); notesBuffer.append( (String) storedTags.elementAt(i) + "\n"); } notes=notesBuffer.toString(); if (!notes.equals("")) imp.setProperty("Info", notes); // Set (spatial) calibration // nb pass the current calibration in case that contains useful info // already (such as a brightness calibration) try { imp.setCalibration(getDM3CalibrationInfo(imp.getCalibration())); } catch (Exception e) { IJ.showStatus("No Calibration info in "+fileName); } // If this is a diffraction (ie reciprocal space) image then set the // FHT property so that ImageJ displays inverse scale String imagingMode = (String) tagHash.get(IMGLIST+chosenImage+".ImageTags.Microscope Info.Imaging Mode"); if (imagingMode!=null && imagingMode.toUpperCase().equals("DIFFRACTION")){ imp.setProperty("FHT", "Dummy FHT"); } // Set the min and max brightness for display purposes // from DM3 header info if required - ImageJ can do this // but is less robust if(useGatanMinMax) { // now searches through all tags // after bug report by <Charles.P.Daghlian@Dartmouth.EDU> double hiVal=0.0, loVal=0.0; // Iterate over components of the taglist // looking for the image brightness tag // all this because I don't know how to partially match a hash key for (Enumeration e = tagHash.keys() ; e.hasMoreElements() ;) { String thisElementString = (String) e.nextElement(); if( (thisElementString).endsWith("ImageDisplayInfo.HighLimit")) hiVal = ((Float) tagHash.get(thisElementString)).doubleValue(); if( (thisElementString).endsWith("ImageDisplayInfo.LowLimit")) loVal = ((Float) tagHash.get(thisElementString)).doubleValue(); } // If we found at least one, then set the min max brightness if (hiVal!=0.0 || loVal!=0.0) { // min,max are set through the image processor, so get it ImageProcessor ip = imp.getProcessor(); // set them - nb setMinMax expects raw pixel values // if a brightness calibration is in force then getRawValue() // does the appropriate conversion ip.setMinAndMax(imp.getCalibration().getRawValue(loVal),imp.getCalibration().getRawValue(hiVal)); } } return imp; } void parseDM3(String directory, String fileName) throws IOException { // This reads through the DM3 file, extracting useful tags // which allow one to determine the data offset etc. // alternative way to read from file - allows seeks! // and therefore keeps track of position (use long getFilePointer()) // also has DataInput Interface allowing // reading of specific types f = new RandomAccessFile(directory+fileName,"r"); if(debugLevel>0) IJ.write("Directory = "+directory); if(debugLevel>0) IJ.write("File = "+fileName); // Get the first 3 4byte ints from Header to find out // FileVersion (which must be 3) int fileVersion = f.readInt(); if (fileVersion!=3) throw new IOException("This does not seem to be a DM3 file"); if(debugLevel>5) IJ.write("File Version"+fileVersion); // ... file size int FileSize=f.readInt(); int lE=f.readInt(); if(debugLevel>5) IJ.write("lE "+lE); // ... and whether it was written in little endian (PC) format or not // (Mac and Java output are big endian) if(lE==1) { littleEndian=true; } else { if(lE==0) littleEndian=false; else { throw new IOException("This does not seem to be a DM3 file"); } } // The DM3 file has an unnamed root group which contains everything in the file curGroupNameAtLevelX[0] = "root"; // Set the name of the root group // Now go read it (and all of its sub groups. readTagGroup(); // Close the input stream f.close(); } FileInfo getDM3FileInfo(String directory, String fileName) throws IOException { // this gets the basic file information using the contents of the tag // tables created by parseDM3() // Set the basic file information FileInfo fi = new FileInfo(); fi.fileFormat = fi.RAW; fi.fileName = fileName; fi.directory = directory; // Originally forgot to do this - tells ImageJ what endian form the actual // image data is in fi.intelByteOrder=littleEndian; chosenImage = 0; // Look for largest Image and assume that is the one we want int i=0; // nb the first image is image = 0 long largestDataSizeSoFar=0; // Iterate over images keeping a note of the largest image so far while (true) { // The specific part of the key we are looking for String rString=".ImageData.Data.Size"; if(debugLevel>1) IJ.write("Looking for:"+IMGLIST+i+rString); // Can we find information for image i if(tagHash.containsKey(IMGLIST+i+rString)) { if(debugLevel>1) IJ.write("Found:"+IMGLIST+i+rString); // how big is this image? long dataSize = ((Long) tagHash.get(IMGLIST+i+rString)).longValue(); if(debugLevel>1) IJ.write("Current Data Size"+dataSize); // Is it the largest so far? if(dataSize>largestDataSizeSoFar) { // Choose this image largestDataSizeSoFar=dataSize; if(debugLevel>1) IJ.write("New Largest Data Size:"+largestDataSizeSoFar); chosenImage=i; if(debugLevel>1) IJ.write("New Chosen Image:"+chosenImage); } i++; // move on to the next image } else { break; // we ran out of images } } /* Here are the ImageData.DataType definitions from GatanDM3.h class DataType { public: enum Type { 0= NULL_DATA, 1= SIGNED_INT16_DATA, ... REAL4_DATA, COMPLEX8_DATA, OBSELETE_DATA, PACKED_DATA, UNSIGNED_INT8_DATA, SIGNED_INT32_DATA, RGB_DATA, SIGNED_INT8_DATA, UNSIGNED_INT16_DATA, UNSIGNED_INT32_DATA, REAL8_DATA, COMPLEX16_DATA, BINARY_DATA, RGB_UINT8_0_DATA, RGB_UINT8_1_DATA, RGB_UINT16_DATA, RGB_FLOAT32_DATA, RGB_FLOAT64_DATA, RGBA_UINT8_0_DATA, RGBA_UINT8_1_DATA, RGBA_UINT8_2_DATA, RGBA_UINT8_3_DATA, RGBA_UINT16_DATA, RGBA_FLOAT32_DATA, RGBA_FLOAT64_DATA, POINT2_SINT16_0_DATA, POINT2_SINT16_1_DATA, POINT2_SINT32_0_DATA, POINT2_FLOAT32_0_DATA, RECT_SINT16_1_DATA, RECT_SINT32_1_DATA, RECT_FLOAT32_1_DATA, RECT_FLOAT32_0_DATA, SIGNED_INT64_DATA, UNSIGNED_INT64_DATA, LAST_DATA }; }; */ // OK pick the DataType int dataType = ((Integer) tagHash.get(IMGLIST+chosenImage+".ImageData.DataType")).intValue(); // I have made my best guess for types 1-14 // ie SIGNED_INT16_DATA to BINARY_DATA // but I don't know how to implement the remainder switch(dataType){ case 1: // SIGNED_INT16_DATA fi.fileType=FileInfo.GRAY16_SIGNED; break; case 10: // UNSIGNED_INT16_DATA fi.fileType=FileInfo.GRAY16_UNSIGNED; break; case 2: // REAL4_DATA fi.fileType=FileInfo.GRAY32_FLOAT; break; //case 9: // or SIGNED_INT8_DATA // NB ImageJ only handles unsigned ints - initially was treating // these as unsigned, but in the end decided to remove for safety case 6: // UNSIGNED_INT8_DATA fi.fileType=FileInfo.GRAY8; break; case 7: // SIGNED_INT32_DATA fi.fileType=FileInfo.GRAY32_INT; break; case 11: // UNSIGNED_INT32_DATA fi.fileType=FileInfo.GRAY32_UNSIGNED; break; case 8: // RGB_DATA fi.fileType=FileInfo.RGB; break; case 14: // BINARY_DATA fi.fileType=FileInfo.BITMAP; break; case 23: // RGBA_UINT8_3_DATA // NB it is uncertain if this data type corresponds exactly to ImageJ's ARGB // A definitely comes first but the RGB values could be scrambled // (since they were all equal on my test image) fi.fileType=FileInfo.ARGB; break; default: throw new IOException("Unimplemented ImageData dataType="+dataType+" in DM3 file. See getDM3FileInfo() for details"); } // Get the dimensions of the image for the chosen image // I'm assuming they are ordered width then height fi.width = ((Integer) tagHash.get(IMGLIST+chosenImage+".ImageData.Dimensions.0")).intValue(); fi.height = ((Integer) tagHash.get(IMGLIST+chosenImage+".ImageData.Dimensions.1")).intValue(); // Get the offset of the Image Data for chosen image fi.offset = ((Long) tagHash.get(IMGLIST+chosenImage+".ImageData.Data.Offset")).intValue(); return fi; } Calibration getDM3CalibrationInfo(Calibration cal){ // get the spatial calibration information // could also do brightness // (actually a calibration fn is applied by ImageJ according // to the image Type - GRAY16_SIGNED has 32768 removed in calibration // Figure out what the units are - need to check if nm is correct and // if other units are likely // also will �m get corrupted? may be necessary to do a unicode comparison String unit = (String) tagHash.get(IMGLIST+chosenImage+".ImageData.Calibrations.Dimension.0.Units"); // Reciprocal space images - return the original unit - reciprocal // space will be handled by setting the FHT image property if (unit.startsWith("1/")) unit=unit.substring(2); if (unit.equals("�m")){ cal.setUnit("micron"); } else { cal.setUnit(unit); } if(debugLevel>0) IJ.write("Calibration unit: "+unit); cal.pixelWidth = ((Float) tagHash.get(IMGLIST+chosenImage+".ImageData.Calibrations.Dimension.0.Scale")).doubleValue(); cal.pixelHeight = ((Float) tagHash.get(IMGLIST+chosenImage+".ImageData.Calibrations.Dimension.1.Scale")).doubleValue(); // not yet implemented stacks - if they exist //cal.pixelDepth = return cal; } int readTagGroup() throws IOException { curGroupLevel+=1; // Go down a level since this is a new group curGroupAtLevelX[curGroupLevel]++; // Increment the group counter at this level // Set the number of current tag at this level to -1 // since the readTagEntry routine pre-increments // ie the first tag will be labelled tag 0 curTagAtLevelX[curGroupLevel]=-1; if(debugLevel>5) IJ.write("rTG: Current Group Level: "+curGroupLevel); int isSorted=f.readByte(); int isOpen=f.readByte(); int nTags=f.readInt(); if(debugLevel>5) IJ.write("rTG: Iterating over the "+nTags+" tag entries in this group"); // Iterate over the number of Tag Entries in this group for( int i = 0; i<nTags;i++) { readTagEntry(); } // Go back up a level now that we've finished reading this group curGroupLevel-=1; return 1; }; String makeGroupString() { // Produces a string which is the concatenation of the current group levels String tString = new String(""+curGroupAtLevelX[0]); for (int i=1; i<=curGroupLevel;i++){ tString += "."+curGroupAtLevelX[i]; } return tString; } int readTagEntry() throws IOException { int isData=f.readByte(); // Record that we've found a new tag at this level curTagAtLevelX[curGroupLevel]++; //Get the tag label if one exists int lenTagLabel=f.readShort(); String tagLabel; if(lenTagLabel!=0){ tagLabel=readString(lenTagLabel); } else { tagLabel=new String(""+curTagAtLevelX[curGroupLevel]); } // For debugging if(debugLevel>5) { IJ.write(curGroupLevel+"|"+makeGroupString()+": Tag label = "+tagLabel); } else if (debugLevel>0){ IJ.write(curGroupLevel+": Tag label = "+tagLabel); } // Figure out if the tag was data or a new group if (isData==21) { // this tag entry is data // OK settle what this piece of data will be called curTagName = new String(makeGroupNameString()+"."+tagLabel); // now get it readTagType(); } else { //this tag entry is a tag group // Slightly ugly that this can't be done in readTagGroup curGroupNameAtLevelX[curGroupLevel+1]=tagLabel; // Store the name of the group at the new level readTagGroup(); // which will actually increment curGroupLevel } return 1; }; String makeGroupNameString() { // A utility function: // Produces a string which is the concatenation of the current group names String tString = new String(curGroupNameAtLevelX[0]); for (int i=1; i<=curGroupLevel;i++){ tString += "."+curGroupNameAtLevelX[i]; } return tString; } int readTagType() throws IOException { int Delim=f.readInt(); // Should always start with %%%% if (Delim!=0x25252525) throw new IOException("Tag Type delimiter not %%%%"); // This is redundant info, so just ignore it. int nInTag=f.readInt(); readAnyData(); return 1; }; int readAnyData() throws IOException { // Higher level function which dispatches to functions // handling specific data types // This specifies what kind of type we are dealing with // eg short, long, struct, array etc. int encodedType = f.readInt(); // Figure out the size of the encodedType int etSize = encodedTypeSize(encodedType); if(debugLevel>5) IJ.write("rAnD, "+hexPosition()+": Tag Type = "+encodedType+", Tag Size = "+etSize); if(etSize>0){ // must be a regular data type, so read it and store a tag for ir storeTag( curTagName,readNativeData(encodedType,etSize) ); } // OK then, perhaps it's an array, struct or string. else if (encodedType==STRING) // String { // nb readStringData will also store tags internally int stringSize = f.readInt(); readStringData(stringSize); } else if (encodedType==STRUCT) // Struct { // This now stores fields (in curly braces) but does not store // field names. In fact the code will be break for non-zero // field names. Vector structTypes = readStructTypes(); readStructData(structTypes); } else if (encodedType==ARRAY) // Array { // This only stores a tag which I defined myself // to indicate the size of data chunks that are skipped Vector arrayTypes=readArrayTypes(); readArrayData(arrayTypes); } else { throw new IOException("rAnD, 0x"+hexPosition()+": Can't understand encoded type"); } return 1; } Object readNativeData(int encodedType,int etSize) throws IOException { // Does the actual reading of ordinary data types // since it starts as an object, it is not tied to a particular // data type Object val=null; if(encodedType==SHORT){ //short val = new Short(blreadShort()); } else if(encodedType==LONG){ //long val = new Integer(blreadInt()); } else if(encodedType==USHORT){ //u short val = new Short(blreadUShort()); } else if(encodedType==ULONG){ //u long val = new Integer(blreadInt()); } else if(encodedType==FLOAT){ //float val = new Float(blreadFloat()); } else if(encodedType==DOUBLE){ //double val = new Double(blreadDouble()); } else if(encodedType==BOOLEAN){ //boolean if (f.readByte()==0){ val = new Boolean(false); } else { val = new Boolean(true); } } else if(encodedType==CHAR){ //char val = new Character( (char) f.readByte() ); } else if(encodedType==OCTET){ //octet // what's the difference? val = new Byte( f.readByte() ); } else { // Not a known data type throw new IOException("rND, 0x"+hexPosition()+": Unknown data type "+encodedType); } // Print out the value if necessary if(debugLevel>3){ IJ.write("rND, 0x"+hexPosition()+": "+val); } else if(debugLevel>0) { IJ.write(""+val); } return val; } String readStringData(int stringSize) throws IOException { // Does the actual reading of string data types // These should be written as Unicode which can be directly // converted by the String constructor if(stringSize<=0) return new String(""); // Read the string data into a temporary byte buffer. byte[] temp = new byte[stringSize]; f.read(temp,0,stringSize); // Now convert these unicode bytes into a real string String rString; // Note that I can't get UTF encoding to work on MRJ 2.2.5 = // JDK 1.1.7 even though I think it should // so I have put together a kludge if(littleEndian){ // Use UTF-16LE encoding (this seems to fail with MacOS 9 Java 1.1.7) try { rString=new String(temp,"UTF-16LE"); } catch (Exception e) { // Manual conversion of the string if the above fails rString=""; for(int i=0;i<stringSize;i+=2) { rString+=new Character((char)((temp[i+1]&0xFF) <<8 | (temp[i] & 0xFF))); } } }else{ // use UTF-16BE encoding (this seems to fail with MacOS 9 Java 1.1.7) try { rString=new String(temp,"UTF-16BE"); } catch (Exception e) { // Manual conversion of the string if the above fails rString=""; for(int i=0;i<stringSize;i+=2) { rString+=new Character((char)((temp[i]&0xFF) <<8 | (temp[i+1] & 0xFF))); } } } if(debugLevel>0) IJ.write("StringVal: "+rString); // Store the value of this tag storeTag(curTagName,rString); return rString; } Vector readArrayTypes() throws IOException { // Figures out the data types in an array data type // complicated by the fact that the array type could be a struct! // Don't know if this will behave for arrays of strings or arrays int arrayType=f.readInt(); Vector itemTypes = new Vector(); if (arrayType==STRUCT) { // ie a Struct itemTypes = readStructTypes(); } else if (arrayType==ARRAY) { // ie a sub array itemTypes = readArrayTypes(); // not sure if this will work! } else { // assume its an array of simple types // add changed to addElement for Java 1.1.7 compatibility itemTypes.addElement(new Integer(arrayType)); } return itemTypes; } int readArrayData(Vector arrayTypes) throws IOException { // Reads in array data // First thing to do is get number of array elements int arraySize=f.readInt(); if(debugLevel>3) IJ.write("rArD, 0x"+hexPosition()+": Reading array of size = "+arraySize); // Now figure out the total width of each element in the array // nb these elements can have subelements if the array is an array // of STRUCTS etc. int itemSize=0; // Iterate over every type in arrayTypes - there may be more than // one type if this is an array of structs or arrays. int encodedType=0; for (int i = 0; i < arrayTypes.size(); i++) { // cast the ith Vector element to Integer and then get a regular int encodedType = ((Integer) arrayTypes.elementAt(i)).intValue(); int etSize=encodedTypeSize(encodedType); // Now add that size to our running total itemSize+=etSize; // For debugging if(debugLevel>5) IJ.write("rArD: Tag Type = "+encodedType+", Tag Size = "+etSize); //readNativeData(encodedType,etSize); } if(debugLevel>5) IJ.write("rArD: Array Item Size = "+itemSize); // OK now figure out what to do with this array // this would be the buffer size needed to accommodate ot long bufSize = (long) arraySize * (long) itemSize; // If this isn't image data but is an unsigned short array // of less than 256 bytes then it is probably a string if(!curTagName.endsWith("ImageData.Data") && arrayTypes.size() == 1 && encodedType == USHORT && arraySize <256) { // read in as string String val = readStringData((int) bufSize); } else { // treat as binary data // Make up my own tags to indicate data size storeTag(curTagName+".Size",new Long(bufSize)); // and current offset // nb for a while I had offset + 1but this was wrong! // and gave a peculiar staircase histogram because what I had // ended up doing was reading one byte each from a pair of pixels // rather than 2 bytes from a single pixel. Ugh! storeTag(curTagName+".Offset",new Long(f.getFilePointer())); // then go ahead and skip bufSize bytes from current position // without trying to read this data f.seek( f.getFilePointer()+bufSize); } return 1; } Vector readStructTypes() throws IOException { // Figures out the data types in a struct if(debugLevel>3) IJ.write("Reading Struct Types at Pos = "+f.getFilePointer()+", 0x"+hexPosition()); // nb GatanDM3 has longs - I think C++ long = 4 bytes, so use Java int int structNameLength=f.readInt(); int nFields=f.readInt(); if(debugLevel>5) IJ.write("nFields = "+nFields); if (nFields>100) throw new IOException("Too many fields"); Vector fieldTypes = new Vector(); int nameLength = 0; for (int i = 0; i<nFields; i++) { nameLength=f.readInt(); if(debugLevel>10) IJ.write(i+"th namelength = "+nameLength); int fieldType=f.readInt(); // add changed to addElement for Java 1.1.7 compatibility fieldTypes.addElement(new Integer(fieldType)); } return fieldTypes; } int readStructData(Vector structTypes) throws IOException { // Reads in struct data based on the type info in structTypes String structAsString=""; for (int i = 0; i < structTypes.size(); i++) { Integer iTagType = (Integer) structTypes.elementAt(i); int encodedType = iTagType.intValue(); int etSize=encodedTypeSize(encodedType); // For debugging if(debugLevel>5) IJ.write("Tag Type = "+encodedType+", Tag Size = "+etSize); // OK now get the data structAsString+=readNativeData(encodedType,etSize); // Add a comma to separate values unless this is the last entry if(i+1!=structTypes.size()) structAsString+=","; } storeTag(curTagName,"{"+structAsString+"}"); return 1; } int encodedTypeSize(int encodedType){ // returns the size in bytes of the data type // 030614 Replaced type numbers based on GatanDM3.h // so -1 will be the value returned for an unrecognised type // (which could include ARRAYs, STRUCTs, STRINGs) int width=-1; switch(encodedType){ case 0: // blank field? Do I need this? width = 0; break; case BOOLEAN: // boolean: data size = 1 case CHAR: // char: data size = 1 case OCTET: // octet: data size = 1 width=1; break; case SHORT: // 1. short: data size = 2 case USHORT: // 3. unsigned short: data size = 2 width=2; break; case LONG: // 2. long: data size = 4 case ULONG: // 4. unsigned long: data size = 4 case FLOAT: // 5. float: data size = 4 width=4; break; case DOUBLE: // double: data size = 8 width=8; break; } return(width); } // Store the value and key of the tag that we have just // read in a table void storeTag( String tagName, Object tagValue){ // add changed to addElement for Java 1.1.7 compatibility storedTags.addElement(new String(tagName+" = "+tagValue)); tagHash.put(tagName,tagValue); } // ******************************************************** // the bl methods will check value of littleEndian and read // from the RandomAccessFile f accordingly. // (bl for big/little - ie can cope with either endian format) // ******************************************************** short blreadShort() throws IOException { if (!littleEndian) return f.readShort(); byte b1 = f.readByte(); byte b2 = f.readByte(); return ( (short) (((b2 & 0xff) << 8) | (b1 & 0xff)) ); } short blreadUShort() throws IOException // Identical to blreadShort - is this correct? // not really - java uses signed shorts, but I think it's // too complicated to try and implement unsigned // In principle, one should add 65536 to negative values // to convert, but then they would have to be stored as 4 byte ints // or something. { if (!littleEndian) return (short) f.readUnsignedShort(); byte b1 = f.readByte(); byte b2 = f.readByte(); return ( (short) (((b2 & 0xff) << 8) | (b1 & 0xff)) ); } int blreadInt() throws IOException { if (!littleEndian) return f.readInt(); byte b1 = f.readByte(); byte b2 = f.readByte(); byte b3 = f.readByte(); byte b4 = f.readByte(); return ( (((b4 & 0xff) << 24) | ((b3 & 0xff) << 16) | ((b2 & 0xff) << 8) | (b1 & 0xff)) ); } long blreadLong() throws IOException // New fn, not quite sure if the little endian version is correct // OK Corrected now as far as I can tell { if (!littleEndian) return f.readLong(); int i1=blreadInt(); int i2=blreadInt(); // need to convert intermediates to long explicitly since the standard // is presumably just to work with them as int return ( ((long) (i2 & 0xffffffff) << 32) | (long) (i1 & 0xffffffff) ); } double blreadDouble() throws IOException // new fn to read 8 byte doubles using blreadLong as a base { if (!littleEndian) return f.readDouble(); long orig = blreadLong(); return (Double.longBitsToDouble(orig)); } float blreadFloat() throws IOException { if (!littleEndian) return f.readFloat(); int orig = blreadInt(); return (Float.intBitsToFloat(orig)); } // used to read in field labels String readString(int n) throws IOException{ // not sure if this readString limit is sensible or necessary if(n>2000) throw new IOException("Can't handle strings longer than 2000 chars, n = "+n+" at pos = "+f.getFilePointer()); byte[] temp = new byte[n]; f.read(temp,0,n); return new String(temp); } String hexPosition() throws IOException { // Utility fn to return current file position in hex return ( Long.toHexString( f.getFilePointer() ) ); } }
UTF-8
Java
36,635
java
DM3_Reader.java
Java
[ { "context": "// Made a start using the Analyze_Reader plugin by Guy Williams and\n// the Biorad_Reader as a base, but not that ", "end": 492, "score": 0.9998218417167664, "start": 480, "tag": "NAME", "value": "Guy Williams" }, { "context": "AN/doc/\n// ------------------------------...
null
[]
package ij.plugin; import java.io.*; import java.util.*; // for the Vector and Hashtable classes import ij.*; import ij.process.*; import ij.io.*; import ij.measure.*; // ------------------------------------------ // DM3_Reader.java // ------------------------------------------ // This plugin will read DM3 files produced by Gatan Digital Micrograph // Decoding is based on info gleaned from the EMAN project based at Baylor // Made a start using the Analyze_Reader plugin by <NAME> and // the Biorad_Reader as a base, but not that much remains. // The guts were significantly inspired by the GatanDM3.C and // GatanDM3.h files of the EMAN project source code: // http://ncmi.bcm.tmc.edu/~stevel/EMAN/doc/ // ------------------------------------ // <NAME>, // Dept Biological Sciences, // Stanford University // <EMAIL> // ------------------------------------------- // as of v1.0.1 030615 // ------------------------------------------- // - reads 16 bit images only, // - correctly parses all simple tags // - Places tags in File/Show Info // including acquisition time / sample date etc. // - allows spatial calibration of images // - sets minimum and maximum intensity // ------------------------------------ // as of v1.1 030615 // - went back to making it an ImagePlus extension // ------------------------------------ // as of v1.2.6 030618 // - Corrected a bad bug - The offset for the image data was off // by +1 // - AND I never told the image opener whether the image data was // in little endian format or not. // - So what I was doing was reading one byte from pixel n and one from pixel n+1! // (which looked more or less like the correct number in big-endian) // - Added my best guess for what ImageJ image type should be set for // the standard data types // - Changed load(), parseDM3() and getDM3FileInfo functions to receive // directory and FileName as parameters - that way load() can be called // directly bypassing the run() function. // ------------------------------------ // v 1.2.7 030621 // - Most functions were previously defined as public, now restricted // to those that might actually get an external call // - read through code once making a few small tidies and improving comments // ------------------------------------ // v 1.2.8 030624 // - Improved ability to set min/max brightness of image according to information // in the Gatan file after bug report from <NAME> at Dartmouth. // This takes place at the end of the load()function. // ------------------------------------ // v 1.2.9 030625 // - Fixed handling of signed 16 bit and 32 bit images by using the // FileInfo.GRAY16_SIGNED and FileInfo.GRAY32_INT constants // & keeping the Calibration object generated by ImageJ when the image // is loaded rather than creating my own from scratch - I had been // throwing away the brightness calibration which ImageJ does on // 16 bit signed images as a result. // & supplying _raw_ values of loVal and hiVal to setMinAndMax() // ------------------------------------ // v 1.3.0 030625 // - Removed calls to functions introduced since Java 1.1 to allow // plugin to run on OS9 Macs with Java 1.1.7 // - However as far as I can see there is a bug in MRJ that prevents // UTF-16 conversion from occurring so unicode strings in the // DM3 tags don't import. Instead there will be a string saying // "couldn't read string blah". This is annoying because the // calibration units are given as a unicode string. // ------------------------------------ // v 1.3.1 030625 // - Fixed UTF-16 conversion bug in MRJ by writing a quick and dirty unicode // reader to be used if the UTF-16 conversion fails. Now correctly // sets the spatial calibration on OS9 // - Another thing that I noticed was that it seemed to be important to // compile with v1.3.1 if one wanted to use the class with v1.1.7 // ------------------------------------ // v 1.3.2 030808 // - Fixed a bug in getDM3FileInfo which meant that the last rather than // the largest image in the DM3 file was chosen // - Fixed a bug in getDM3CalibrationInfo which caused a failure to // recognise "nm" as a valid calibration unit - the problem was caused // by doing (unit == "nm") instead of (unit.equals("nm")) // ------------------------------------ // v 1.3.3 030821 // - Fixed a remaining bug in the image selection routine which now // works for all files that I have available to test. // ------------------------------------ // v 1.3.4 040506 // - Fixed a bug reading in USHORT image data. The problem was that // USHORT data and strings are hard to tell apart. Although Image Data // can be identified categorically, other lumps of data (e.g. LUTs) // scattered throughout the file are harder to spot and will cause problems // if read as a string. Have compromised by reading as string if: // + it isn't image data // + but is an unsigned short array // + of less than 256 bytes // ------------------------------------ // v 1.3.4 051213 (Yes the 2nd v1.3.4 - hadn't noticed a branch!) // - Fixed a bug which prevented units other than �m or nm being passed to // calibration object. Occasioned by a file with units 1/nm // ------------------------------------ // v 1.3.5 051213 // - Adding handling of DIFFRACTION mode images (ie reciprocal space) by // setting FHT property and copying // calibration object. Occasioned by a file with units 1/nm // ------------------------------------ // v 1.3.6 060904 // - Added storing of struct fields to tag list // They are displayed as tag= {1,2,3,4} // This means that Digital Micrograph selection rectangles // can now be identified from Show Info // ------------------------------------ // v 1.3.7 070831 // - debugLevel is now set according to IJ.debugMode // (accesible from Edit ... Options ... Misc) // - Can now open data type 23 (RGBA_UINT8_3_DATA) images // ------------------------------------ // v 1.3.8 080326 // - Fixed a bug in which tag hashes were not cleared when reading a new file // - Small speed improvement by converting tags to String via StringBuffer // - Both thanks to report by <NAME> at UIUC public class DM3_Reader extends ImagePlus implements PlugIn { // Decide whether to use Gatan's information for determining the min // and maximum brightness thresholds for display or leave to ImageJ // I find Gatan more reliable public boolean useGatanMinMax = true; private boolean littleEndian = true; // default for .dm3 files // nb all tags are written big-endian, it is only the actual data // attached to each tag that may be little-endian (and will be for PC files) //private String directory; //private String fileName; private RandomAccessFile f; // This stream will be used for reading by parseDM3() private FileInfo fi; private String notes = ""; // I will store interesting file info in here // 0=none, 1-3=basic, 4-5=simple, 6-10 verbose private static final int debugLevel = IJ.debugMode?10:0; // the number of the chosen image in the DM3 file // since there apparently may be several - usually at least a thumbnail // I will select the largest image. If there are multiple images // of the same size, the first will be chosen. private int chosenImage = 1; private int curGroupLevel=-1; // Track how deep is the group we are currently reading private static final int MAXDEPTH = 64; // Maximum number of levels of tags private int[] curGroupAtLevelX=new int[MAXDEPTH]; // To track group at current level private String[] curGroupNameAtLevelX=new String[MAXDEPTH]; // To track group name at current level private int[] curTagAtLevelX=new int[MAXDEPTH]; // To track tag number at current level private String curTagName = ""; // the name of the current tag data item // Will use these to store tags private Vector storedTags = new Vector(); private Hashtable tagHash = new Hashtable(); // Set up constants for the different encoded data types used in DM3 files private static final int SHORT = 2; private static final int LONG = 3; private static final int USHORT = 4; private static final int ULONG = 5; private static final int FLOAT = 6; private static final int DOUBLE = 7; private static final int BOOLEAN = 8; private static final int CHAR = 9; private static final int OCTET = 10; private static final int STRUCT = 15; private static final int STRING = 18; private static final int ARRAY = 20; // This the lhs of Image list tags private static final String IMGLIST = "root.ImageList."; // This is the lhs for Document Object List Tags // root.DocumentObjectList.0.AnnotationGroupList.0.AnnotationType = 31 private static final String OBJLIST = "root.DocumentObjectList."; public void run(String arg) { String directory = ""; String fileName = arg; //if (debugLevel>5); if (debugLevel>5) IJ.write("IN:dir = "+directory+", file="+fileName); if ((arg==null) || (arg=="")) { // Choose a file since none specified OpenDialog od = new OpenDialog("Load DM3 File...", arg); fileName = od.getFileName(); if (fileName==null) return; directory = od.getDirectory(); if (debugLevel>5) IJ.write("IF:dir = "+directory+", file="+fileName); } else { // we were sent a filename to open File dest = new File(arg); directory = dest.getParent(); fileName = dest.getName(); if (debugLevel>5) IJ.write("ELSE:dir = "+directory+", file="+fileName); } // Load in the image ImagePlus imp = load(directory, fileName); if (imp==null) return; // Attach the Image Processor setProcessor(fileName, imp.getProcessor()); // Copy the scale info over copyScale(imp); // Copy the Show Info field over setProperty("Info",imp.getProperty("Info")); // and the FHT property (to handle diffraction mode images) if(imp.getProperty("FHT")!=null) setProperty("FHT", imp.getProperty("FHT")); // Show the image if it was selected by the file // chooser, don't if an argument was passed ie // some other ImageJ process called the plugin if (arg.equals("")) show(); } public ImagePlus load(String directory, String fileName) /*throws IOException*/ { if ((fileName == null) || (fileName == "")) return null; if (!directory.endsWith(File.separator)) directory += File.separator; IJ.showStatus("Loading DM3 File: " + directory + fileName); // Clear the lists of tags in which additional info will be stored tagHash.clear(); storedTags.clear(); // Try calling the parse routine try{ parseDM3(directory, fileName);} catch (Exception e) { IJ.showStatus("parseDM3() error"); IJ.showMessage("DM3_Reader", ""+e); return null; } // Make a blank file information object fi = new FileInfo(); // Go and fetch the DM3 specific file Information try {fi=getDM3FileInfo(directory, fileName);} // This is in case of trouble parsing the tag table catch (Exception e) { IJ.showStatus(""); IJ.showMessage("DM3_Reader", "gDM3:"+e); return null; } // Write out Calculated Offset if reqd if(debugLevel>1) IJ.write("Calculated offset = "+fi.offset); if(debugLevel>1) IJ.write("Chosen image = "+chosenImage); // Open the image! FileOpener fo = new FileOpener(fi); ImagePlus imp = fo.open(false); //if(debugLevel>5) if(imp==null) IJ.write("Image load failed!"); // Write out the contents of the storedTags list // and set the value of notes StringBuffer notesBuffer=new StringBuffer(); for (int i = 0; i<storedTags.size();i++){ // Can decide whether I want to do this //IJ.log((String) storedTags.elementAt(i)); notesBuffer.append( (String) storedTags.elementAt(i) + "\n"); } notes=notesBuffer.toString(); if (!notes.equals("")) imp.setProperty("Info", notes); // Set (spatial) calibration // nb pass the current calibration in case that contains useful info // already (such as a brightness calibration) try { imp.setCalibration(getDM3CalibrationInfo(imp.getCalibration())); } catch (Exception e) { IJ.showStatus("No Calibration info in "+fileName); } // If this is a diffraction (ie reciprocal space) image then set the // FHT property so that ImageJ displays inverse scale String imagingMode = (String) tagHash.get(IMGLIST+chosenImage+".ImageTags.Microscope Info.Imaging Mode"); if (imagingMode!=null && imagingMode.toUpperCase().equals("DIFFRACTION")){ imp.setProperty("FHT", "Dummy FHT"); } // Set the min and max brightness for display purposes // from DM3 header info if required - ImageJ can do this // but is less robust if(useGatanMinMax) { // now searches through all tags // after bug report by <Charles.P.Daghlian<EMAIL>outh.EDU> double hiVal=0.0, loVal=0.0; // Iterate over components of the taglist // looking for the image brightness tag // all this because I don't know how to partially match a hash key for (Enumeration e = tagHash.keys() ; e.hasMoreElements() ;) { String thisElementString = (String) e.nextElement(); if( (thisElementString).endsWith("ImageDisplayInfo.HighLimit")) hiVal = ((Float) tagHash.get(thisElementString)).doubleValue(); if( (thisElementString).endsWith("ImageDisplayInfo.LowLimit")) loVal = ((Float) tagHash.get(thisElementString)).doubleValue(); } // If we found at least one, then set the min max brightness if (hiVal!=0.0 || loVal!=0.0) { // min,max are set through the image processor, so get it ImageProcessor ip = imp.getProcessor(); // set them - nb setMinMax expects raw pixel values // if a brightness calibration is in force then getRawValue() // does the appropriate conversion ip.setMinAndMax(imp.getCalibration().getRawValue(loVal),imp.getCalibration().getRawValue(hiVal)); } } return imp; } void parseDM3(String directory, String fileName) throws IOException { // This reads through the DM3 file, extracting useful tags // which allow one to determine the data offset etc. // alternative way to read from file - allows seeks! // and therefore keeps track of position (use long getFilePointer()) // also has DataInput Interface allowing // reading of specific types f = new RandomAccessFile(directory+fileName,"r"); if(debugLevel>0) IJ.write("Directory = "+directory); if(debugLevel>0) IJ.write("File = "+fileName); // Get the first 3 4byte ints from Header to find out // FileVersion (which must be 3) int fileVersion = f.readInt(); if (fileVersion!=3) throw new IOException("This does not seem to be a DM3 file"); if(debugLevel>5) IJ.write("File Version"+fileVersion); // ... file size int FileSize=f.readInt(); int lE=f.readInt(); if(debugLevel>5) IJ.write("lE "+lE); // ... and whether it was written in little endian (PC) format or not // (Mac and Java output are big endian) if(lE==1) { littleEndian=true; } else { if(lE==0) littleEndian=false; else { throw new IOException("This does not seem to be a DM3 file"); } } // The DM3 file has an unnamed root group which contains everything in the file curGroupNameAtLevelX[0] = "root"; // Set the name of the root group // Now go read it (and all of its sub groups. readTagGroup(); // Close the input stream f.close(); } FileInfo getDM3FileInfo(String directory, String fileName) throws IOException { // this gets the basic file information using the contents of the tag // tables created by parseDM3() // Set the basic file information FileInfo fi = new FileInfo(); fi.fileFormat = fi.RAW; fi.fileName = fileName; fi.directory = directory; // Originally forgot to do this - tells ImageJ what endian form the actual // image data is in fi.intelByteOrder=littleEndian; chosenImage = 0; // Look for largest Image and assume that is the one we want int i=0; // nb the first image is image = 0 long largestDataSizeSoFar=0; // Iterate over images keeping a note of the largest image so far while (true) { // The specific part of the key we are looking for String rString=".ImageData.Data.Size"; if(debugLevel>1) IJ.write("Looking for:"+IMGLIST+i+rString); // Can we find information for image i if(tagHash.containsKey(IMGLIST+i+rString)) { if(debugLevel>1) IJ.write("Found:"+IMGLIST+i+rString); // how big is this image? long dataSize = ((Long) tagHash.get(IMGLIST+i+rString)).longValue(); if(debugLevel>1) IJ.write("Current Data Size"+dataSize); // Is it the largest so far? if(dataSize>largestDataSizeSoFar) { // Choose this image largestDataSizeSoFar=dataSize; if(debugLevel>1) IJ.write("New Largest Data Size:"+largestDataSizeSoFar); chosenImage=i; if(debugLevel>1) IJ.write("New Chosen Image:"+chosenImage); } i++; // move on to the next image } else { break; // we ran out of images } } /* Here are the ImageData.DataType definitions from GatanDM3.h class DataType { public: enum Type { 0= NULL_DATA, 1= SIGNED_INT16_DATA, ... REAL4_DATA, COMPLEX8_DATA, OBSELETE_DATA, PACKED_DATA, UNSIGNED_INT8_DATA, SIGNED_INT32_DATA, RGB_DATA, SIGNED_INT8_DATA, UNSIGNED_INT16_DATA, UNSIGNED_INT32_DATA, REAL8_DATA, COMPLEX16_DATA, BINARY_DATA, RGB_UINT8_0_DATA, RGB_UINT8_1_DATA, RGB_UINT16_DATA, RGB_FLOAT32_DATA, RGB_FLOAT64_DATA, RGBA_UINT8_0_DATA, RGBA_UINT8_1_DATA, RGBA_UINT8_2_DATA, RGBA_UINT8_3_DATA, RGBA_UINT16_DATA, RGBA_FLOAT32_DATA, RGBA_FLOAT64_DATA, POINT2_SINT16_0_DATA, POINT2_SINT16_1_DATA, POINT2_SINT32_0_DATA, POINT2_FLOAT32_0_DATA, RECT_SINT16_1_DATA, RECT_SINT32_1_DATA, RECT_FLOAT32_1_DATA, RECT_FLOAT32_0_DATA, SIGNED_INT64_DATA, UNSIGNED_INT64_DATA, LAST_DATA }; }; */ // OK pick the DataType int dataType = ((Integer) tagHash.get(IMGLIST+chosenImage+".ImageData.DataType")).intValue(); // I have made my best guess for types 1-14 // ie SIGNED_INT16_DATA to BINARY_DATA // but I don't know how to implement the remainder switch(dataType){ case 1: // SIGNED_INT16_DATA fi.fileType=FileInfo.GRAY16_SIGNED; break; case 10: // UNSIGNED_INT16_DATA fi.fileType=FileInfo.GRAY16_UNSIGNED; break; case 2: // REAL4_DATA fi.fileType=FileInfo.GRAY32_FLOAT; break; //case 9: // or SIGNED_INT8_DATA // NB ImageJ only handles unsigned ints - initially was treating // these as unsigned, but in the end decided to remove for safety case 6: // UNSIGNED_INT8_DATA fi.fileType=FileInfo.GRAY8; break; case 7: // SIGNED_INT32_DATA fi.fileType=FileInfo.GRAY32_INT; break; case 11: // UNSIGNED_INT32_DATA fi.fileType=FileInfo.GRAY32_UNSIGNED; break; case 8: // RGB_DATA fi.fileType=FileInfo.RGB; break; case 14: // BINARY_DATA fi.fileType=FileInfo.BITMAP; break; case 23: // RGBA_UINT8_3_DATA // NB it is uncertain if this data type corresponds exactly to ImageJ's ARGB // A definitely comes first but the RGB values could be scrambled // (since they were all equal on my test image) fi.fileType=FileInfo.ARGB; break; default: throw new IOException("Unimplemented ImageData dataType="+dataType+" in DM3 file. See getDM3FileInfo() for details"); } // Get the dimensions of the image for the chosen image // I'm assuming they are ordered width then height fi.width = ((Integer) tagHash.get(IMGLIST+chosenImage+".ImageData.Dimensions.0")).intValue(); fi.height = ((Integer) tagHash.get(IMGLIST+chosenImage+".ImageData.Dimensions.1")).intValue(); // Get the offset of the Image Data for chosen image fi.offset = ((Long) tagHash.get(IMGLIST+chosenImage+".ImageData.Data.Offset")).intValue(); return fi; } Calibration getDM3CalibrationInfo(Calibration cal){ // get the spatial calibration information // could also do brightness // (actually a calibration fn is applied by ImageJ according // to the image Type - GRAY16_SIGNED has 32768 removed in calibration // Figure out what the units are - need to check if nm is correct and // if other units are likely // also will �m get corrupted? may be necessary to do a unicode comparison String unit = (String) tagHash.get(IMGLIST+chosenImage+".ImageData.Calibrations.Dimension.0.Units"); // Reciprocal space images - return the original unit - reciprocal // space will be handled by setting the FHT image property if (unit.startsWith("1/")) unit=unit.substring(2); if (unit.equals("�m")){ cal.setUnit("micron"); } else { cal.setUnit(unit); } if(debugLevel>0) IJ.write("Calibration unit: "+unit); cal.pixelWidth = ((Float) tagHash.get(IMGLIST+chosenImage+".ImageData.Calibrations.Dimension.0.Scale")).doubleValue(); cal.pixelHeight = ((Float) tagHash.get(IMGLIST+chosenImage+".ImageData.Calibrations.Dimension.1.Scale")).doubleValue(); // not yet implemented stacks - if they exist //cal.pixelDepth = return cal; } int readTagGroup() throws IOException { curGroupLevel+=1; // Go down a level since this is a new group curGroupAtLevelX[curGroupLevel]++; // Increment the group counter at this level // Set the number of current tag at this level to -1 // since the readTagEntry routine pre-increments // ie the first tag will be labelled tag 0 curTagAtLevelX[curGroupLevel]=-1; if(debugLevel>5) IJ.write("rTG: Current Group Level: "+curGroupLevel); int isSorted=f.readByte(); int isOpen=f.readByte(); int nTags=f.readInt(); if(debugLevel>5) IJ.write("rTG: Iterating over the "+nTags+" tag entries in this group"); // Iterate over the number of Tag Entries in this group for( int i = 0; i<nTags;i++) { readTagEntry(); } // Go back up a level now that we've finished reading this group curGroupLevel-=1; return 1; }; String makeGroupString() { // Produces a string which is the concatenation of the current group levels String tString = new String(""+curGroupAtLevelX[0]); for (int i=1; i<=curGroupLevel;i++){ tString += "."+curGroupAtLevelX[i]; } return tString; } int readTagEntry() throws IOException { int isData=f.readByte(); // Record that we've found a new tag at this level curTagAtLevelX[curGroupLevel]++; //Get the tag label if one exists int lenTagLabel=f.readShort(); String tagLabel; if(lenTagLabel!=0){ tagLabel=readString(lenTagLabel); } else { tagLabel=new String(""+curTagAtLevelX[curGroupLevel]); } // For debugging if(debugLevel>5) { IJ.write(curGroupLevel+"|"+makeGroupString()+": Tag label = "+tagLabel); } else if (debugLevel>0){ IJ.write(curGroupLevel+": Tag label = "+tagLabel); } // Figure out if the tag was data or a new group if (isData==21) { // this tag entry is data // OK settle what this piece of data will be called curTagName = new String(makeGroupNameString()+"."+tagLabel); // now get it readTagType(); } else { //this tag entry is a tag group // Slightly ugly that this can't be done in readTagGroup curGroupNameAtLevelX[curGroupLevel+1]=tagLabel; // Store the name of the group at the new level readTagGroup(); // which will actually increment curGroupLevel } return 1; }; String makeGroupNameString() { // A utility function: // Produces a string which is the concatenation of the current group names String tString = new String(curGroupNameAtLevelX[0]); for (int i=1; i<=curGroupLevel;i++){ tString += "."+curGroupNameAtLevelX[i]; } return tString; } int readTagType() throws IOException { int Delim=f.readInt(); // Should always start with %%%% if (Delim!=0x25252525) throw new IOException("Tag Type delimiter not %%%%"); // This is redundant info, so just ignore it. int nInTag=f.readInt(); readAnyData(); return 1; }; int readAnyData() throws IOException { // Higher level function which dispatches to functions // handling specific data types // This specifies what kind of type we are dealing with // eg short, long, struct, array etc. int encodedType = f.readInt(); // Figure out the size of the encodedType int etSize = encodedTypeSize(encodedType); if(debugLevel>5) IJ.write("rAnD, "+hexPosition()+": Tag Type = "+encodedType+", Tag Size = "+etSize); if(etSize>0){ // must be a regular data type, so read it and store a tag for ir storeTag( curTagName,readNativeData(encodedType,etSize) ); } // OK then, perhaps it's an array, struct or string. else if (encodedType==STRING) // String { // nb readStringData will also store tags internally int stringSize = f.readInt(); readStringData(stringSize); } else if (encodedType==STRUCT) // Struct { // This now stores fields (in curly braces) but does not store // field names. In fact the code will be break for non-zero // field names. Vector structTypes = readStructTypes(); readStructData(structTypes); } else if (encodedType==ARRAY) // Array { // This only stores a tag which I defined myself // to indicate the size of data chunks that are skipped Vector arrayTypes=readArrayTypes(); readArrayData(arrayTypes); } else { throw new IOException("rAnD, 0x"+hexPosition()+": Can't understand encoded type"); } return 1; } Object readNativeData(int encodedType,int etSize) throws IOException { // Does the actual reading of ordinary data types // since it starts as an object, it is not tied to a particular // data type Object val=null; if(encodedType==SHORT){ //short val = new Short(blreadShort()); } else if(encodedType==LONG){ //long val = new Integer(blreadInt()); } else if(encodedType==USHORT){ //u short val = new Short(blreadUShort()); } else if(encodedType==ULONG){ //u long val = new Integer(blreadInt()); } else if(encodedType==FLOAT){ //float val = new Float(blreadFloat()); } else if(encodedType==DOUBLE){ //double val = new Double(blreadDouble()); } else if(encodedType==BOOLEAN){ //boolean if (f.readByte()==0){ val = new Boolean(false); } else { val = new Boolean(true); } } else if(encodedType==CHAR){ //char val = new Character( (char) f.readByte() ); } else if(encodedType==OCTET){ //octet // what's the difference? val = new Byte( f.readByte() ); } else { // Not a known data type throw new IOException("rND, 0x"+hexPosition()+": Unknown data type "+encodedType); } // Print out the value if necessary if(debugLevel>3){ IJ.write("rND, 0x"+hexPosition()+": "+val); } else if(debugLevel>0) { IJ.write(""+val); } return val; } String readStringData(int stringSize) throws IOException { // Does the actual reading of string data types // These should be written as Unicode which can be directly // converted by the String constructor if(stringSize<=0) return new String(""); // Read the string data into a temporary byte buffer. byte[] temp = new byte[stringSize]; f.read(temp,0,stringSize); // Now convert these unicode bytes into a real string String rString; // Note that I can't get UTF encoding to work on MRJ 2.2.5 = // JDK 1.1.7 even though I think it should // so I have put together a kludge if(littleEndian){ // Use UTF-16LE encoding (this seems to fail with MacOS 9 Java 1.1.7) try { rString=new String(temp,"UTF-16LE"); } catch (Exception e) { // Manual conversion of the string if the above fails rString=""; for(int i=0;i<stringSize;i+=2) { rString+=new Character((char)((temp[i+1]&0xFF) <<8 | (temp[i] & 0xFF))); } } }else{ // use UTF-16BE encoding (this seems to fail with MacOS 9 Java 1.1.7) try { rString=new String(temp,"UTF-16BE"); } catch (Exception e) { // Manual conversion of the string if the above fails rString=""; for(int i=0;i<stringSize;i+=2) { rString+=new Character((char)((temp[i]&0xFF) <<8 | (temp[i+1] & 0xFF))); } } } if(debugLevel>0) IJ.write("StringVal: "+rString); // Store the value of this tag storeTag(curTagName,rString); return rString; } Vector readArrayTypes() throws IOException { // Figures out the data types in an array data type // complicated by the fact that the array type could be a struct! // Don't know if this will behave for arrays of strings or arrays int arrayType=f.readInt(); Vector itemTypes = new Vector(); if (arrayType==STRUCT) { // ie a Struct itemTypes = readStructTypes(); } else if (arrayType==ARRAY) { // ie a sub array itemTypes = readArrayTypes(); // not sure if this will work! } else { // assume its an array of simple types // add changed to addElement for Java 1.1.7 compatibility itemTypes.addElement(new Integer(arrayType)); } return itemTypes; } int readArrayData(Vector arrayTypes) throws IOException { // Reads in array data // First thing to do is get number of array elements int arraySize=f.readInt(); if(debugLevel>3) IJ.write("rArD, 0x"+hexPosition()+": Reading array of size = "+arraySize); // Now figure out the total width of each element in the array // nb these elements can have subelements if the array is an array // of STRUCTS etc. int itemSize=0; // Iterate over every type in arrayTypes - there may be more than // one type if this is an array of structs or arrays. int encodedType=0; for (int i = 0; i < arrayTypes.size(); i++) { // cast the ith Vector element to Integer and then get a regular int encodedType = ((Integer) arrayTypes.elementAt(i)).intValue(); int etSize=encodedTypeSize(encodedType); // Now add that size to our running total itemSize+=etSize; // For debugging if(debugLevel>5) IJ.write("rArD: Tag Type = "+encodedType+", Tag Size = "+etSize); //readNativeData(encodedType,etSize); } if(debugLevel>5) IJ.write("rArD: Array Item Size = "+itemSize); // OK now figure out what to do with this array // this would be the buffer size needed to accommodate ot long bufSize = (long) arraySize * (long) itemSize; // If this isn't image data but is an unsigned short array // of less than 256 bytes then it is probably a string if(!curTagName.endsWith("ImageData.Data") && arrayTypes.size() == 1 && encodedType == USHORT && arraySize <256) { // read in as string String val = readStringData((int) bufSize); } else { // treat as binary data // Make up my own tags to indicate data size storeTag(curTagName+".Size",new Long(bufSize)); // and current offset // nb for a while I had offset + 1but this was wrong! // and gave a peculiar staircase histogram because what I had // ended up doing was reading one byte each from a pair of pixels // rather than 2 bytes from a single pixel. Ugh! storeTag(curTagName+".Offset",new Long(f.getFilePointer())); // then go ahead and skip bufSize bytes from current position // without trying to read this data f.seek( f.getFilePointer()+bufSize); } return 1; } Vector readStructTypes() throws IOException { // Figures out the data types in a struct if(debugLevel>3) IJ.write("Reading Struct Types at Pos = "+f.getFilePointer()+", 0x"+hexPosition()); // nb GatanDM3 has longs - I think C++ long = 4 bytes, so use Java int int structNameLength=f.readInt(); int nFields=f.readInt(); if(debugLevel>5) IJ.write("nFields = "+nFields); if (nFields>100) throw new IOException("Too many fields"); Vector fieldTypes = new Vector(); int nameLength = 0; for (int i = 0; i<nFields; i++) { nameLength=f.readInt(); if(debugLevel>10) IJ.write(i+"th namelength = "+nameLength); int fieldType=f.readInt(); // add changed to addElement for Java 1.1.7 compatibility fieldTypes.addElement(new Integer(fieldType)); } return fieldTypes; } int readStructData(Vector structTypes) throws IOException { // Reads in struct data based on the type info in structTypes String structAsString=""; for (int i = 0; i < structTypes.size(); i++) { Integer iTagType = (Integer) structTypes.elementAt(i); int encodedType = iTagType.intValue(); int etSize=encodedTypeSize(encodedType); // For debugging if(debugLevel>5) IJ.write("Tag Type = "+encodedType+", Tag Size = "+etSize); // OK now get the data structAsString+=readNativeData(encodedType,etSize); // Add a comma to separate values unless this is the last entry if(i+1!=structTypes.size()) structAsString+=","; } storeTag(curTagName,"{"+structAsString+"}"); return 1; } int encodedTypeSize(int encodedType){ // returns the size in bytes of the data type // 030614 Replaced type numbers based on GatanDM3.h // so -1 will be the value returned for an unrecognised type // (which could include ARRAYs, STRUCTs, STRINGs) int width=-1; switch(encodedType){ case 0: // blank field? Do I need this? width = 0; break; case BOOLEAN: // boolean: data size = 1 case CHAR: // char: data size = 1 case OCTET: // octet: data size = 1 width=1; break; case SHORT: // 1. short: data size = 2 case USHORT: // 3. unsigned short: data size = 2 width=2; break; case LONG: // 2. long: data size = 4 case ULONG: // 4. unsigned long: data size = 4 case FLOAT: // 5. float: data size = 4 width=4; break; case DOUBLE: // double: data size = 8 width=8; break; } return(width); } // Store the value and key of the tag that we have just // read in a table void storeTag( String tagName, Object tagValue){ // add changed to addElement for Java 1.1.7 compatibility storedTags.addElement(new String(tagName+" = "+tagValue)); tagHash.put(tagName,tagValue); } // ******************************************************** // the bl methods will check value of littleEndian and read // from the RandomAccessFile f accordingly. // (bl for big/little - ie can cope with either endian format) // ******************************************************** short blreadShort() throws IOException { if (!littleEndian) return f.readShort(); byte b1 = f.readByte(); byte b2 = f.readByte(); return ( (short) (((b2 & 0xff) << 8) | (b1 & 0xff)) ); } short blreadUShort() throws IOException // Identical to blreadShort - is this correct? // not really - java uses signed shorts, but I think it's // too complicated to try and implement unsigned // In principle, one should add 65536 to negative values // to convert, but then they would have to be stored as 4 byte ints // or something. { if (!littleEndian) return (short) f.readUnsignedShort(); byte b1 = f.readByte(); byte b2 = f.readByte(); return ( (short) (((b2 & 0xff) << 8) | (b1 & 0xff)) ); } int blreadInt() throws IOException { if (!littleEndian) return f.readInt(); byte b1 = f.readByte(); byte b2 = f.readByte(); byte b3 = f.readByte(); byte b4 = f.readByte(); return ( (((b4 & 0xff) << 24) | ((b3 & 0xff) << 16) | ((b2 & 0xff) << 8) | (b1 & 0xff)) ); } long blreadLong() throws IOException // New fn, not quite sure if the little endian version is correct // OK Corrected now as far as I can tell { if (!littleEndian) return f.readLong(); int i1=blreadInt(); int i2=blreadInt(); // need to convert intermediates to long explicitly since the standard // is presumably just to work with them as int return ( ((long) (i2 & 0xffffffff) << 32) | (long) (i1 & 0xffffffff) ); } double blreadDouble() throws IOException // new fn to read 8 byte doubles using blreadLong as a base { if (!littleEndian) return f.readDouble(); long orig = blreadLong(); return (Double.longBitsToDouble(orig)); } float blreadFloat() throws IOException { if (!littleEndian) return f.readFloat(); int orig = blreadInt(); return (Float.intBitsToFloat(orig)); } // used to read in field labels String readString(int n) throws IOException{ // not sure if this readString limit is sensible or necessary if(n>2000) throw new IOException("Can't handle strings longer than 2000 chars, n = "+n+" at pos = "+f.getFilePointer()); byte[] temp = new byte[n]; f.read(temp,0,n); return new String(temp); } String hexPosition() throws IOException { // Utility fn to return current file position in hex return ( Long.toHexString( f.getFilePointer() ) ); } }
36,595
0.664583
0.647274
1,070
33.232712
25.503033
122
false
false
0
0
0
0
0
0
2.408411
false
false
13
dfbc988b47b624be412011105b5db282af2ce2c2
23,974,507,496,148
70d1ba202d220d4c40b326acf0dbb5f986c30830
/residencia-ejb/ejbModule/entity/Estudiante.java
18696a64fd34d98f4649cc66a8a487a684496d09
[]
no_license
vbuilvicente/seam
https://github.com/vbuilvicente/seam
ea9650f9973b9c4bed4069808a0cb2ef88e173a4
75deaa5379efb8998709d82134c40125a26f32e3
refs/heads/master
2019-06-14T16:45:39.220000
2016-05-12T02:02:38
2016-05-12T02:02:38
58,476,173
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package entity; // Generated 16-jun-2013 21:17:26 by Hibernate Tools 3.4.0.CR1 import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import org.hibernate.validator.Length; import org.hibernate.validator.NotNull; /** * Estudiante generated by hbm2java */ @Entity @Table(name = "estudiante", schema = "public") public class Estudiante implements java.io.Serializable { private int idEstudiante; private Apartamento apartamento; private Grupo grupo; private int solapin; private String nombre; private String apellidos; private String username; private Set<Cuarteleria> cuartelerias = new HashSet<Cuarteleria>(0); private Set<EvalEstudiante> evalEstudiantes = new HashSet<EvalEstudiante>(0); public Estudiante() { } public Estudiante(int idEstudiante, int solapin) { this.idEstudiante = idEstudiante; this.solapin = solapin; } public Estudiante(int idEstudiante, Apartamento apartamento, Grupo grupo, int solapin, String nombre, String apellidos, String username, Set<Cuarteleria> cuartelerias, Set<EvalEstudiante> evalEstudiantes) { this.idEstudiante = idEstudiante; this.apartamento = apartamento; this.grupo = grupo; this.solapin = solapin; this.nombre = nombre; this.apellidos = apellidos; this.username = username; this.cuartelerias = cuartelerias; this.evalEstudiantes = evalEstudiantes; } @Id @Column(name = "id_estudiante", unique = true, nullable = false) @NotNull @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen_est") @SequenceGenerator(name = "gen_est", sequenceName = "public.estudiante_id_estudiante_seq", allocationSize = 1) public int getIdEstudiante() { return this.idEstudiante; } public void setIdEstudiante(int idEstudiante) { this.idEstudiante = idEstudiante; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_apartamento") public Apartamento getApartamento() { return this.apartamento; } public void setApartamento(Apartamento apartamento) { this.apartamento = apartamento; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_grupo") public Grupo getGrupo() { return this.grupo; } public void setGrupo(Grupo grupo) { this.grupo = grupo; } @Column(name = "solapin", nullable = false) @NotNull public int getSolapin() { return this.solapin; } public void setSolapin(int solapin) { this.solapin = solapin; } @Column(name = "nombre", length = 25) @Length(max = 25) public String getNombre() { return this.nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @Column(name = "apellidos", length = 50) @Length(max = 50) public String getApellidos() { return this.apellidos; } public void setApellidos(String apellidos) { this.apellidos = apellidos; } @Column(name = "username", length = 18) @Length(max = 18) public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "estudiante") public Set<Cuarteleria> getCuartelerias() { return this.cuartelerias; } public void setCuartelerias(Set<Cuarteleria> cuartelerias) { this.cuartelerias = cuartelerias; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "estudiante") public Set<EvalEstudiante> getEvalEstudiantes() { return this.evalEstudiantes; } public void setEvalEstudiantes(Set<EvalEstudiante> evalEstudiantes) { this.evalEstudiantes = evalEstudiantes; } }
UTF-8
Java
3,993
java
Estudiante.java
Java
[ { "context": "\r\n\t\tthis.apellidos = apellidos;\r\n\t\tthis.username = username;\r\n\t\tthis.cuartelerias = cuartelerias;\r\n\t\tthis.eva", "end": 1708, "score": 0.9995227456092834, "start": 1700, "tag": "USERNAME", "value": "username" }, { "context": "is.apellidos = apellidos;\r\n...
null
[]
package entity; // Generated 16-jun-2013 21:17:26 by Hibernate Tools 3.4.0.CR1 import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import org.hibernate.validator.Length; import org.hibernate.validator.NotNull; /** * Estudiante generated by hbm2java */ @Entity @Table(name = "estudiante", schema = "public") public class Estudiante implements java.io.Serializable { private int idEstudiante; private Apartamento apartamento; private Grupo grupo; private int solapin; private String nombre; private String apellidos; private String username; private Set<Cuarteleria> cuartelerias = new HashSet<Cuarteleria>(0); private Set<EvalEstudiante> evalEstudiantes = new HashSet<EvalEstudiante>(0); public Estudiante() { } public Estudiante(int idEstudiante, int solapin) { this.idEstudiante = idEstudiante; this.solapin = solapin; } public Estudiante(int idEstudiante, Apartamento apartamento, Grupo grupo, int solapin, String nombre, String apellidos, String username, Set<Cuarteleria> cuartelerias, Set<EvalEstudiante> evalEstudiantes) { this.idEstudiante = idEstudiante; this.apartamento = apartamento; this.grupo = grupo; this.solapin = solapin; this.nombre = nombre; this.apellidos = apellidos; this.username = username; this.cuartelerias = cuartelerias; this.evalEstudiantes = evalEstudiantes; } @Id @Column(name = "id_estudiante", unique = true, nullable = false) @NotNull @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen_est") @SequenceGenerator(name = "gen_est", sequenceName = "public.estudiante_id_estudiante_seq", allocationSize = 1) public int getIdEstudiante() { return this.idEstudiante; } public void setIdEstudiante(int idEstudiante) { this.idEstudiante = idEstudiante; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_apartamento") public Apartamento getApartamento() { return this.apartamento; } public void setApartamento(Apartamento apartamento) { this.apartamento = apartamento; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_grupo") public Grupo getGrupo() { return this.grupo; } public void setGrupo(Grupo grupo) { this.grupo = grupo; } @Column(name = "solapin", nullable = false) @NotNull public int getSolapin() { return this.solapin; } public void setSolapin(int solapin) { this.solapin = solapin; } @Column(name = "nombre", length = 25) @Length(max = 25) public String getNombre() { return this.nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @Column(name = "apellidos", length = 50) @Length(max = 50) public String getApellidos() { return this.apellidos; } public void setApellidos(String apellidos) { this.apellidos = apellidos; } @Column(name = "username", length = 18) @Length(max = 18) public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "estudiante") public Set<Cuarteleria> getCuartelerias() { return this.cuartelerias; } public void setCuartelerias(Set<Cuarteleria> cuartelerias) { this.cuartelerias = cuartelerias; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "estudiante") public Set<EvalEstudiante> getEvalEstudiantes() { return this.evalEstudiantes; } public void setEvalEstudiantes(Set<EvalEstudiante> evalEstudiantes) { this.evalEstudiantes = evalEstudiantes; } }
3,993
0.721763
0.713749
151
24.443708
21.620642
111
false
false
0
0
0
0
0
0
1.384106
false
false
13
81a83cc1b8d3c08b2ff5ae50747426a903008fd5
4,604,204,980,057
1e1a56a925d5c0335df889d5975abc69a5ea153f
/mingrui-shop-parent/mingrui-shop-service-api/mingrui-shop-service-api-xxx/src/main/java/com/baidu/shop/service/BrandService.java
22c26787b0974bd3a466a61922e72ffe7ac292a0
[]
no_license
WorldNo1Jax/mr-shop
https://github.com/WorldNo1Jax/mr-shop
b272ab3d24eaa311d8ed2b344e53948209ac8bb2
b443130bd94563e660b3adcf3adf1457becfb73e
refs/heads/master
2023-01-23T12:31:45.339000
2020-12-02T10:30:49
2020-12-02T10:30:49
290,701,392
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.baidu.shop.service; import com.baidu.shop.base.Result; import com.baidu.shop.dto.BrandDTO; import com.baidu.shop.entity.BrandEntity; import com.baidu.shop.validate.group.MingruiOperation; import com.github.pagehelper.PageInfo; import com.google.gson.JsonObject; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.cloud.openfeign.SpringQueryMap; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; @Api(value = "品牌接口") public interface BrandService { @ApiOperation(value = "获取品牌信息") @GetMapping(value = "brand/getBrandInfo") Result<PageInfo<BrandEntity>> getBrandInfo(@SpringQueryMap BrandDTO brandDTO); @ApiOperation(value = "新增品牌信息") @PostMapping(value = "brand/saveBrandInfo") Result<JsonObject> saveBrandInfo(@Validated({MingruiOperation.Add.class}) @RequestBody BrandDTO brandDTO); @ApiOperation(value = "修改品牌信息") @PutMapping(value = "brand/saveBrandInfo") Result<JsonObject> editBrandInfo(@Validated({MingruiOperation.Update.class}) @RequestBody BrandDTO brandDTO); @ApiOperation(value = "删除品牌信息") @DeleteMapping(value = "brand/delete") Result<JsonObject> deleteBrand(Integer brandId); @ApiOperation(value = "通过cid获取品牌信息") @GetMapping(value = "brand/getBrandByCid") Result<BrandEntity> getBrandByCid(Integer cid); @ApiOperation(value = "通过品牌Id集合获取品牌信息") @GetMapping(value = "brand/getByBrandIdList") Result<List<BrandEntity>> getByBrandIdList(@RequestParam String brandsStr); }
UTF-8
Java
1,709
java
BrandService.java
Java
[]
null
[]
package com.baidu.shop.service; import com.baidu.shop.base.Result; import com.baidu.shop.dto.BrandDTO; import com.baidu.shop.entity.BrandEntity; import com.baidu.shop.validate.group.MingruiOperation; import com.github.pagehelper.PageInfo; import com.google.gson.JsonObject; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.cloud.openfeign.SpringQueryMap; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; @Api(value = "品牌接口") public interface BrandService { @ApiOperation(value = "获取品牌信息") @GetMapping(value = "brand/getBrandInfo") Result<PageInfo<BrandEntity>> getBrandInfo(@SpringQueryMap BrandDTO brandDTO); @ApiOperation(value = "新增品牌信息") @PostMapping(value = "brand/saveBrandInfo") Result<JsonObject> saveBrandInfo(@Validated({MingruiOperation.Add.class}) @RequestBody BrandDTO brandDTO); @ApiOperation(value = "修改品牌信息") @PutMapping(value = "brand/saveBrandInfo") Result<JsonObject> editBrandInfo(@Validated({MingruiOperation.Update.class}) @RequestBody BrandDTO brandDTO); @ApiOperation(value = "删除品牌信息") @DeleteMapping(value = "brand/delete") Result<JsonObject> deleteBrand(Integer brandId); @ApiOperation(value = "通过cid获取品牌信息") @GetMapping(value = "brand/getBrandByCid") Result<BrandEntity> getBrandByCid(Integer cid); @ApiOperation(value = "通过品牌Id集合获取品牌信息") @GetMapping(value = "brand/getByBrandIdList") Result<List<BrandEntity>> getByBrandIdList(@RequestParam String brandsStr); }
1,709
0.767514
0.767514
44
35.659092
27.305464
113
false
false
0
0
0
0
0
0
0.431818
false
false
13
96fc1cd53e23fc31384ed31fc6903788dec90ea5
4,604,204,980,459
d49f44a6264dae3d30cd6366015d16f06f297500
/CoursGraphique/src/SwingBase/MaJDialog.java
aad344476eeb5ccb4f77e391067ebf49b3eaae2d
[]
no_license
MarieLePanda/ExoJava
https://github.com/MarieLePanda/ExoJava
2a311c5355190ab455ccacfcbc8afadf6d4d6c91
32a6dd767ddc8f2750ca6ef346fe5552c037f4fe
refs/heads/master
2021-01-19T06:27:29.796000
2014-04-24T20:52:58
2014-04-24T20:52:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package SwingBase; import javax.swing.JDialog; /** * * @author lug13995 */ public class MaJDialog extends JDialog{ }
UTF-8
Java
227
java
MaJDialog.java
Java
[ { "context": "e;\n\nimport javax.swing.JDialog;\n\n/**\n *\n * @author lug13995\n */\npublic class MaJDialog extends JDialog{\n \n", "end": 175, "score": 0.9991167187690735, "start": 167, "tag": "USERNAME", "value": "lug13995" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package SwingBase; import javax.swing.JDialog; /** * * @author lug13995 */ public class MaJDialog extends JDialog{ }
227
0.687225
0.665198
15
14.133333
16.764513
52
false
false
0
0
0
0
0
0
0.266667
false
false
13
36d09cdee35937dda9920d9bb126bdeda1a88889
35,064,113,020,840
1483490008d3844dc269e471b083e9479c6a7634
/Logistics-SSM/src/main/java/com/yyk/dto/LineDTO/LineResDTO.java
3bae119c1059ccf18633730595721898715123d7
[]
no_license
SilenceLoveLt/Logistics-SSM
https://github.com/SilenceLoveLt/Logistics-SSM
129e09330755df6ccef5dc137bd79101d6ce6f18
97674a094e1c4a123fc0b235fdebf41d4f67fb53
refs/heads/master
2022-06-25T14:04:26.679000
2019-06-17T13:01:28
2019-06-17T13:01:28
178,534,098
0
0
null
false
2022-06-21T01:01:37
2019-03-30T08:46:22
2019-06-17T13:02:15
2022-06-21T01:01:37
101,984
0
0
3
Java
false
false
package com.yyk.dto.LineDTO; import java.util.HashMap; import java.util.List; import java.util.Map; import com.yyk.entity.SysLine; public class LineResDTO extends SysLine{ private Map<String, Object> state; private String code; private String codetype; private Integer pageNo; private Integer pageSize; private String lineTypeName; public String getLineTypeName() { return lineTypeName; } public void setLineTypeName(String lineTypeName) { this.lineTypeName = lineTypeName; } public String getCodetype() { return codetype; } public void setCodetype(String codetype) { this.codetype = codetype; } public Integer getPageNo() { return pageNo; } public void setPageNo(Integer pageNo) { this.pageNo = pageNo; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public static Map<String, Object> getStateMap() { return stateMap; } public static void setStateMap(Map<String, Object> stateMap) { LineResDTO.stateMap = stateMap; } public void setState(Map<String, Object> state) { this.state = state; } public void setCode(String code) { this.code = code; } private static Map<String, Object> stateMap = new HashMap<String, Object>(); static { stateMap.put("checked", true); } public Map<String, Object> getState() { return state; } public void setState() { this.state = stateMap; } public String getCode() { return code; } }
UTF-8
Java
1,531
java
LineResDTO.java
Java
[]
null
[]
package com.yyk.dto.LineDTO; import java.util.HashMap; import java.util.List; import java.util.Map; import com.yyk.entity.SysLine; public class LineResDTO extends SysLine{ private Map<String, Object> state; private String code; private String codetype; private Integer pageNo; private Integer pageSize; private String lineTypeName; public String getLineTypeName() { return lineTypeName; } public void setLineTypeName(String lineTypeName) { this.lineTypeName = lineTypeName; } public String getCodetype() { return codetype; } public void setCodetype(String codetype) { this.codetype = codetype; } public Integer getPageNo() { return pageNo; } public void setPageNo(Integer pageNo) { this.pageNo = pageNo; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public static Map<String, Object> getStateMap() { return stateMap; } public static void setStateMap(Map<String, Object> stateMap) { LineResDTO.stateMap = stateMap; } public void setState(Map<String, Object> state) { this.state = state; } public void setCode(String code) { this.code = code; } private static Map<String, Object> stateMap = new HashMap<String, Object>(); static { stateMap.put("checked", true); } public Map<String, Object> getState() { return state; } public void setState() { this.state = stateMap; } public String getCode() { return code; } }
1,531
0.694971
0.694971
92
15.641304
17.277519
77
false
false
0
0
0
0
0
0
1.163043
false
false
13
c9e31743f335f177b452068f5fdfb5b7298b9dbf
23,038,204,608,661
8bcfe1bcb1bca45ef0b0797b545995f8396b4a2c
/src/test/java/api/daos/memory/DepartmentDaoMemoryTest.java
fea7e7de5be3d387284cf627b796b816408d193f
[]
no_license
rploaiza/APAW-ECP2-RoberthLoaiza
https://github.com/rploaiza/APAW-ECP2-RoberthLoaiza
4de19623f9cc595787cbf6c94e08cd9e3ad74a1c
ca2244dece5818684d1d3ace724247ea88f4ec23
refs/heads/master
2021-07-09T16:26:25.338000
2017-10-08T17:43:43
2017-10-08T17:43:43
105,548,240
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package api.daos.memory; import api.entities.Department; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Before; import org.junit.Test; import api.daos.DaoFactory; public class DepartmentDaoMemoryTest { private Department department; @Before public void before() { DaoFactory.setFactory(new DaoMemoryFactory()); department = new Department("TICs", "Informatica"); DaoFactory.getFactory().getDepartmentDao().create(department); } @Test public void testReadDepartmentTitle() { assertEquals("TICs", DaoFactory.getFactory().getDepartmentDao().read(1L).getTitle()); } @Test public void testReadDepartmentCenter() { assertEquals("Informatica", DaoFactory.getFactory().getDepartmentDao().read(1L).getCenter()); } @Test public void testReadDepartmentId() { assertEquals(1L, DaoFactory.getFactory().getDepartmentDao().read(1L).getId()); } @Test public void testReadNonExistId() { assertNull(DaoFactory.getFactory().getDepartmentDao().read(2L)); } @Test public void testReadDepartmentToString() { assertEquals("{\"id\":1,\"title\":\"TICs,\"center\":\"Informatica\"}", DaoFactory.getFactory().getDepartmentDao().read(1L).toString()); } }
UTF-8
Java
1,235
java
DepartmentDaoMemoryTest.java
Java
[]
null
[]
package api.daos.memory; import api.entities.Department; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Before; import org.junit.Test; import api.daos.DaoFactory; public class DepartmentDaoMemoryTest { private Department department; @Before public void before() { DaoFactory.setFactory(new DaoMemoryFactory()); department = new Department("TICs", "Informatica"); DaoFactory.getFactory().getDepartmentDao().create(department); } @Test public void testReadDepartmentTitle() { assertEquals("TICs", DaoFactory.getFactory().getDepartmentDao().read(1L).getTitle()); } @Test public void testReadDepartmentCenter() { assertEquals("Informatica", DaoFactory.getFactory().getDepartmentDao().read(1L).getCenter()); } @Test public void testReadDepartmentId() { assertEquals(1L, DaoFactory.getFactory().getDepartmentDao().read(1L).getId()); } @Test public void testReadNonExistId() { assertNull(DaoFactory.getFactory().getDepartmentDao().read(2L)); } @Test public void testReadDepartmentToString() { assertEquals("{\"id\":1,\"title\":\"TICs,\"center\":\"Informatica\"}", DaoFactory.getFactory().getDepartmentDao().read(1L).toString()); } }
1,235
0.74413
0.738462
48
24.729166
30.253609
137
false
false
0
0
0
0
0
0
1.291667
false
false
13
93379974af71896d5bbb7f95eff3e290ba59f14e
16,475,494,593,971
2e2ca034ea94e3e998da8c9771fe01cd39e5e0dc
/src/main/java/br/com/model/Venda.java
b86c22a9b3d9b311b8e8ba9e1de34679abda98a3
[]
no_license
mandstoni/P2SistDis
https://github.com/mandstoni/P2SistDis
6f913e02ad0a549bb133ec91008adf7a8e4d4146
2184dde733f0dd0cf1bee18b78500ace592670a9
refs/heads/master
2023-06-02T12:42:43.660000
2021-06-16T22:50:12
2021-06-16T22:50:12
375,841,146
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.io.Serializable; import java.util.Date; @Document public class Venda implements Serializable { @Id private int _id; private float qtdProdutoVenda; private String formaPagamento; private String date; private Produto produto; public Venda() { } public Venda(int _id, float qtdProdutoVenda, String formaPagamento, String date, Produto produto) { this._id = _id; this.qtdProdutoVenda = qtdProdutoVenda; this.formaPagamento = formaPagamento; this.date = date; this.produto = produto; } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public float getQtdProdutoVenda() { return qtdProdutoVenda; } public void setQtdProdutoVenda(float qtdProdutoVenda) { this.qtdProdutoVenda = qtdProdutoVenda; } public Produto getProduto() { return produto; } public void setProduto(Produto produto) { this.produto = produto; } public String getFormaPagamento() { return formaPagamento; } public void setFormaPagamento(String formaPagamento) { this.formaPagamento = formaPagamento; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } }
UTF-8
Java
1,497
java
Venda.java
Java
[]
null
[]
package br.com.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.io.Serializable; import java.util.Date; @Document public class Venda implements Serializable { @Id private int _id; private float qtdProdutoVenda; private String formaPagamento; private String date; private Produto produto; public Venda() { } public Venda(int _id, float qtdProdutoVenda, String formaPagamento, String date, Produto produto) { this._id = _id; this.qtdProdutoVenda = qtdProdutoVenda; this.formaPagamento = formaPagamento; this.date = date; this.produto = produto; } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public float getQtdProdutoVenda() { return qtdProdutoVenda; } public void setQtdProdutoVenda(float qtdProdutoVenda) { this.qtdProdutoVenda = qtdProdutoVenda; } public Produto getProduto() { return produto; } public void setProduto(Produto produto) { this.produto = produto; } public String getFormaPagamento() { return formaPagamento; } public void setFormaPagamento(String formaPagamento) { this.formaPagamento = formaPagamento; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } }
1,497
0.645291
0.645291
70
20.385714
20.382971
104
false
false
0
0
0
0
0
0
0.414286
false
false
13
ac2e5a9079e76a7a4c86926a1731267dab7d1900
19,396,072,374,626
5e5c496cab552df965e2ac4458f7fd5b2f2b5337
/MonacaFramework/src/mobi/monaca/framework/transition/GoBackAnimationSet.java
54e8bffbd7c210aaffdfac444dde5f39d89492de
[ "Apache-2.0" ]
permissive
kruyvanna/monaca-framework-android
https://github.com/kruyvanna/monaca-framework-android
2b54211f4db461f0a332810f550136412ccfeac7
ed0e4444c43185bf5550b950a9b9b8a80d62c2bf
refs/heads/master
2021-01-15T18:40:15.012000
2012-12-11T14:42:59
2012-12-11T14:42:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mobi.monaca.framework.transition; import android.view.animation.*; /** This class provide animation set for the screen transition. */ public class GoBackAnimationSet { final public Animation goIn; final public Animation goOut; final public Animation backIn; final public Animation backOut; public GoBackAnimationSet(Animation goIn, Animation goOut, Animation backIn, Animation backOut) { this.goIn = goIn; this.goOut = goOut; this.backIn = backIn; this.backOut = backOut; } public GoBackAnimationSet(Animation goIn, Animation goOut) { this.goIn = goIn; this.goOut = goOut; this.backIn = goIn; this.backOut = goOut; } protected static Animation bindSettings(Animation anim, int duration) { anim.setDuration(duration); anim.restrictDuration(duration); anim.setZAdjustment(Animation.ZORDER_BOTTOM); anim.setInterpolator(new LinearInterpolator()); // anim.setInterpolator(new DecelerateInterpolator()); return anim; } public static GoBackAnimationSet alpha() { int duration = 300; return new GoBackAnimationSet(bindSettings(new AlphaAnimation(0.0f, 1.0f), duration), bindSettings(new AlphaAnimation(1.0f, 0.0f), duration)); } public static GoBackAnimationSet translate() { int duration = 400; return new GoBackAnimationSet(bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings( new TranslateAnimation(Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration)); } public static GoBackAnimationSet verticalTranslate() { int duration = 400; return new GoBackAnimationSet(bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -1.0f), duration), bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f), duration)); } public static GoBackAnimationSet modal() { int duration = 400; return new GoBackAnimationSet(bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings( new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f), duration)); } public static GoBackAnimationSet transit() { int duration = 500; return new GoBackAnimationSet(bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings( new TranslateAnimation(Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration)); } public static GoBackAnimationSet none() { return new GoBackAnimationSet(new AnimationSet(true), new AnimationSet( true), new AnimationSet(true), new AnimationSet(true)); } }
UTF-8
Java
6,101
java
GoBackAnimationSet.java
Java
[]
null
[]
package mobi.monaca.framework.transition; import android.view.animation.*; /** This class provide animation set for the screen transition. */ public class GoBackAnimationSet { final public Animation goIn; final public Animation goOut; final public Animation backIn; final public Animation backOut; public GoBackAnimationSet(Animation goIn, Animation goOut, Animation backIn, Animation backOut) { this.goIn = goIn; this.goOut = goOut; this.backIn = backIn; this.backOut = backOut; } public GoBackAnimationSet(Animation goIn, Animation goOut) { this.goIn = goIn; this.goOut = goOut; this.backIn = goIn; this.backOut = goOut; } protected static Animation bindSettings(Animation anim, int duration) { anim.setDuration(duration); anim.restrictDuration(duration); anim.setZAdjustment(Animation.ZORDER_BOTTOM); anim.setInterpolator(new LinearInterpolator()); // anim.setInterpolator(new DecelerateInterpolator()); return anim; } public static GoBackAnimationSet alpha() { int duration = 300; return new GoBackAnimationSet(bindSettings(new AlphaAnimation(0.0f, 1.0f), duration), bindSettings(new AlphaAnimation(1.0f, 0.0f), duration)); } public static GoBackAnimationSet translate() { int duration = 400; return new GoBackAnimationSet(bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings( new TranslateAnimation(Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration)); } public static GoBackAnimationSet verticalTranslate() { int duration = 400; return new GoBackAnimationSet(bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -1.0f), duration), bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f), duration)); } public static GoBackAnimationSet modal() { int duration = 400; return new GoBackAnimationSet(bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings( new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f), duration)); } public static GoBackAnimationSet transit() { int duration = 500; return new GoBackAnimationSet(bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings( new TranslateAnimation(Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration), bindSettings(new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f), duration)); } public static GoBackAnimationSet none() { return new GoBackAnimationSet(new AnimationSet(true), new AnimationSet( true), new AnimationSet(true), new AnimationSet(true)); } }
6,101
0.594493
0.577938
124
47.201614
27.211235
79
false
false
0
0
0
0
0
0
1.483871
false
false
13
0868ce485734f49bfa6635fb0eb76889dbf2c9b6
24,232,205,484,108
5a116c2f091f5806aecb021545a4cea4486ddd38
/SimpleEcommerce/src/main/java/br/edu/ifce/beans/Produto.java
e403ef8e80a05bdf411dcbe71b2ed20ef1751658
[]
no_license
FelipexxS/Tjw-ecommerce
https://github.com/FelipexxS/Tjw-ecommerce
f89a5b563112edd3f34415f490bc5244415836ae
6d0606d4f8d2665dc32c12b1cb2762c234b16a22
refs/heads/master
2023-03-07T02:06:44.124000
2021-02-19T01:55:43
2021-02-19T01:55:43
339,917,520
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.edu.ifce.beans; public class Produto { private int idproduto; private String nome_produto; private Double preco_produto; private String departamento; private int produto_indicado; public int getIdproduto() { return idproduto; } public void setIdproduto(int idproduto) { this.idproduto = idproduto; } public String getNome_produto() { return nome_produto; } public void setNome_produto(String nome_produto) { this.nome_produto = nome_produto; } public Double getPreco_produto() { return preco_produto; } public void setPreco_produto(Double preco_produto) { this.preco_produto = preco_produto; } public String getDepartamento() { return departamento; } public void setDepartamento(String departamento) { this.departamento = departamento; } public int getProduto_indicado() { return produto_indicado; } public void setProduto_indicado(int produto_indicado) { this.produto_indicado = produto_indicado; } }
UTF-8
Java
981
java
Produto.java
Java
[]
null
[]
package br.edu.ifce.beans; public class Produto { private int idproduto; private String nome_produto; private Double preco_produto; private String departamento; private int produto_indicado; public int getIdproduto() { return idproduto; } public void setIdproduto(int idproduto) { this.idproduto = idproduto; } public String getNome_produto() { return nome_produto; } public void setNome_produto(String nome_produto) { this.nome_produto = nome_produto; } public Double getPreco_produto() { return preco_produto; } public void setPreco_produto(Double preco_produto) { this.preco_produto = preco_produto; } public String getDepartamento() { return departamento; } public void setDepartamento(String departamento) { this.departamento = departamento; } public int getProduto_indicado() { return produto_indicado; } public void setProduto_indicado(int produto_indicado) { this.produto_indicado = produto_indicado; } }
981
0.732926
0.732926
50
18.620001
17.542965
56
false
false
0
0
0
0
0
0
1.44
false
false
13
10b80e4862a85918b7281c618df06e1006c13355
11,407,433,162,995
e0fca3faf05ba95b083d2289862359d2bd5fbb2f
/serepo-data-atom/src/main/java/ch/hsr/isf/serepo/data/atom/annotations/AtomId.java
623166850bd38ca5c9f61fa484011e932777c50f
[]
no_license
vsujeesh/serepo
https://github.com/vsujeesh/serepo
46f99f5431b951d10183aed665c1b748abf88bef
3b8af2e00e6696801d84cd973919819dd6549fcf
refs/heads/master
2023-03-18T03:34:27.223000
2017-08-30T21:29:24
2017-08-30T21:29:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch.hsr.isf.serepo.data.atom.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.net.URI; /** * {@link String}s as well as {@link URI}s are supported. * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface AtomId { }
UTF-8
Java
395
java
AtomId.java
Java
[]
null
[]
package ch.hsr.isf.serepo.data.atom.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.net.URI; /** * {@link String}s as well as {@link URI}s are supported. * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface AtomId { }
395
0.774684
0.774684
17
22.235294
19.331564
57
false
false
0
0
0
0
0
0
0.352941
false
false
13
b2e0dcb68756120619fa9dca042ba78763b56513
39,453,569,604,863
42af0b94af11634dd25fd61c7e1ee1364af15746
/src/main/java/org/puffinbasic/parser/PuffinBasicIRListener.java
06f2ca03d257affce7333bd29ec8e1df18b46993
[ "MIT" ]
permissive
artofcomputerprogramming/PuffinBASIC
https://github.com/artofcomputerprogramming/PuffinBASIC
94928eaba9c26891520f209af6f89bccee83e06d
89bf5ff371c0eee56f78270431e940d3c3b9b4a9
refs/heads/master
2022-12-04T06:57:35.659000
2020-08-25T02:40:24
2020-08-25T02:40:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.puffinbasic.parser; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import it.unimi.dsi.fastutil.objects.ObjectSet; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.misc.Interval; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeProperty; import org.antlr.v4.runtime.tree.TerminalNode; import org.jetbrains.annotations.Nullable; import org.puffinbasic.antlr4.PuffinBasicBaseListener; import org.puffinbasic.antlr4.PuffinBasicParser; import org.puffinbasic.antlr4.PuffinBasicParser.VariableContext; import org.puffinbasic.domain.STObjects; import org.puffinbasic.domain.STObjects.PuffinBasicDataType; import org.puffinbasic.domain.STObjects.STKind; import org.puffinbasic.domain.STObjects.STUDF; import org.puffinbasic.domain.STObjects.STVariable; import org.puffinbasic.domain.Variable; import org.puffinbasic.domain.Variable.VariableName; import org.puffinbasic.error.PuffinBasicInternalError; import org.puffinbasic.error.PuffinBasicSemanticError; import org.puffinbasic.file.PuffinBasicFile.FileAccessMode; import org.puffinbasic.file.PuffinBasicFile.FileOpenMode; import org.puffinbasic.file.PuffinBasicFile.LockMode; import org.puffinbasic.parser.PuffinBasicIR.Instruction; import org.puffinbasic.parser.PuffinBasicIR.OpCode; import org.puffinbasic.runtime.Numbers; import org.puffinbasic.runtime.Types; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.stream.Collectors; import static org.puffinbasic.domain.PuffinBasicSymbolTable.NULL_ID; import static org.puffinbasic.domain.STObjects.PuffinBasicDataType.DOUBLE; import static org.puffinbasic.domain.STObjects.PuffinBasicDataType.FLOAT; import static org.puffinbasic.domain.STObjects.PuffinBasicDataType.INT32; import static org.puffinbasic.domain.STObjects.PuffinBasicDataType.INT64; import static org.puffinbasic.domain.STObjects.PuffinBasicDataType.STRING; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.BAD_ARGUMENT; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.BAD_ASSIGNMENT; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.DATA_TYPE_MISMATCH; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.FOR_WITHOUT_NEXT; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.INSUFFICIENT_UDF_ARGS; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.NEXT_WITHOUT_FOR; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.NOT_DEFINED; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.WHILE_WITHOUT_WEND; import static org.puffinbasic.file.PuffinBasicFile.DEFAULT_RECORD_LEN; import static org.puffinbasic.parser.LinenumberListener.parseLinenum; import static org.puffinbasic.runtime.Types.assertNumeric; import static org.puffinbasic.runtime.Types.unquote; /** * <PRE> * Functions * ========= * ABS done * ASC done * ATN done * CDBL done * CHR$ done * CINT done * CLNG done * COS done * CSNG done * CVD done * CVI done * CVI done * CVL done * CVS done * ENVIRON$ NA * EOF done * EXP done * EXTERR NA * FIX done * FRE NA * HEX$ done * INP NA * INPUT$ done * INSTR done * INT done * IOCTL$ NA * LEFT$ done * LEN done * LOC done * LOF done * LOG done * LPOS NA * MID$ done * MKD$ done * MKI$ done * MKS$ done * MKL$ done * OCT$ done * PEEK NA * RND done * RIGHT$ done * SGN done * SIN done * SPACE$ done * SPC NA * SQR done * STR$ done * STRING$ done * TAB NA * TAN done * TIMER done * VAL done * VARPTR NA * VARPTR$ NA * * PEN NA * PLAY graphics * PMAP graphics * POINT graphics * POS graphics * SCREEN NA * STICK NA * * Statements * ========== * CALL NA * CHAIN NA * CLOSE done * CLS NA * COM(n) NA * COMMON NA * DATA done * DATE$ done * DEF FN done * DEFINT done * DEFDBL done * DEFLNG done * DEFSNG done * DEFSTR done * DEF SEG NA * DEF USR NA * DIM done * END done * ENVIRON NA * ERASE NA * ERROR NA * FIELD done * FOR-NEXT done * GET done * GOSUB-RETURN done * GOTO done * IF-THEN-ELSE done * INPUT done (not compatible) * INPUT# done * IOCTL NA * LET done * LINE INPUT done * LINE INPUT# done * LOCK NA * LPRINT NA * LPRINT USING NA * LSET done * MID$ done * ON ERROR GOTO NA * ON-GOSUB NA * ON-GOTO NA * OPEN done * OPEN COM(n) NA * OPTION BASE NA * OUT NA * ON COM(n) NA * PRINT done * PRINT USING done * PRINT# done * PRINT# USING done * PUT done * RANDOMIZE done * READ done * REM done * RESTORE done * RESUME NA * RSET done * SHELL NA * STOP NA * SWAP done * TIME$ done * UNLOCK NA * WAIT NA * WHILE-WEND done * WIDTH NA * WRITE done * WRTIE# done * * SCREEN done * CIRCLE done * COLOR done * LINE done * PAINT done * DRAW graphics * LOCATE graphics * BEEP NA * KEY NA * KEY(n) NA * ON KEY(n) NA * ON PEN(n) NA * ON PLAY(n) NA * ON STRIG(n) NA * ON TIMER(n) NA * PALETTE NA * PALETTE USING NA * PEN NA * PLAY graphics * PSET graphics * POKE NA * PRESET NA * STRIG NA * STRIG(n) NA * VIEW NA * VIEW PRINT NA * WINDOW NA * </PRE> */ public class PuffinBasicIRListener extends PuffinBasicBaseListener { private enum NumericOrString { NUMERIC, STRING } private final CharStream in; private final PuffinBasicIR ir; private final boolean graphics; private final ParseTreeProperty<Instruction> nodeToInstruction; private final Object2ObjectMap<Variable, UDFState> udfStateMap; private final LinkedList<WhileLoopState> whileLoopStateList; private final LinkedList<ForLoopState> forLoopStateList; private final ParseTreeProperty<IfState> nodeToIfState; private int currentLineNumber; private final ObjectSet<VariableName> varDefined; public PuffinBasicIRListener(CharStream in, PuffinBasicIR ir, boolean graphics) { this.in = in; this.ir = ir; this.graphics = graphics; this.nodeToInstruction = new ParseTreeProperty<>(); this.udfStateMap = new Object2ObjectOpenHashMap<>(); this.whileLoopStateList = new LinkedList<>(); this.forLoopStateList = new LinkedList<>(); this.nodeToIfState = new ParseTreeProperty<>(); this.varDefined = new ObjectOpenHashSet<>(); } public void semanticCheckAfterParsing() { if (!whileLoopStateList.isEmpty()) { throw new PuffinBasicSemanticError( WHILE_WITHOUT_WEND, "<UNKNOWN LINE>", "WHILE without WEND" ); } if (!forLoopStateList.isEmpty()) { throw new PuffinBasicSemanticError( FOR_WITHOUT_NEXT, "<UNKNOWN LINE>", "FOR without NEXT" ); } } private String getCtxString(ParserRuleContext ctx) { return in.getText(new Interval( ctx.start.getStartIndex(), ctx.stop.getStopIndex() )); } private Instruction lookupInstruction(ParserRuleContext ctx) { var exprInstruction = nodeToInstruction.get(ctx); if (exprInstruction == null) { throw new PuffinBasicInternalError( "Failed to find instruction for node: " + ctx.getText() ); } return exprInstruction; } @Override public void enterLine(PuffinBasicParser.LineContext ctx) { this.currentLineNumber = parseLinenum(ctx.linenum().DECIMAL().getText()); } // // Variable, Number, etc. // @Override public void exitNumber(PuffinBasicParser.NumberContext ctx) { final int id; if (ctx.integer() != null) { final boolean isLong = ctx.integer().AT() != null; final boolean isDouble = ctx.integer().HASH() != null; final boolean isFloat = ctx.integer().EXCLAMATION() != null; final String strValue; final int base; if (ctx.integer().HEXADECIMAL() != null) { strValue = ctx.integer().HEXADECIMAL().getText().substring(2); base = 16; } else if (ctx.integer().OCTAL() != null) { var octalStr = ctx.integer().OCTAL().getText(); strValue = (octalStr.startsWith("&O") ? octalStr.substring(2) : octalStr.substring(1)); base = 8; } else { strValue = ctx.integer().DECIMAL().getText(); base = 10; } if (isLong || isDouble) { long parsed = Numbers.parseInt64(strValue, base, () -> getCtxString(ctx)); id = ir.getSymbolTable().addTmp(isLong ? INT64 : DOUBLE, entry -> entry.getValue().setInt64(parsed)); } else { id = ir.getSymbolTable().addTmp(isFloat ? FLOAT : INT32, entry -> entry.getValue().setInt32(Numbers.parseInt32(strValue, base, () -> getCtxString(ctx)))); } } else if (ctx.FLOAT() != null) { var floatStr = ctx.FLOAT().getText(); if (floatStr.endsWith("!")) { floatStr = floatStr.substring(0, floatStr.length() - 1); } var floatValue = Numbers.parseFloat32(floatStr, () -> getCtxString(ctx)); id = ir.getSymbolTable().addTmp(FLOAT, entry -> entry.getValue().setFloat32(floatValue)); } else { var doubleStr = ctx.DOUBLE().getText(); if (doubleStr.endsWith("#")) { doubleStr = doubleStr.substring(0, doubleStr.length() - 1); } var doubleValue = Numbers.parseFloat64(doubleStr, () -> getCtxString(ctx)); id = ir.getSymbolTable().addTmp(DOUBLE, entry -> entry.getValue().setFloat64(doubleValue)); } var instr = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.VALUE, id, NULL_ID, id ); nodeToInstruction.put(ctx, instr); } @Override public void exitVariable(VariableContext ctx) { var varname = ctx.varname().VARNAME().getText(); var varsuffix = ctx.varsuffix() != null ? ctx.varsuffix().getText() : null; var dataType = ir.getSymbolTable().getDataTypeFor(varname, varsuffix); var variableName = new VariableName(varname, dataType); var idHolder = new AtomicInteger(); ir.getSymbolTable() .addVariableOrUDF( variableName, variableName1 -> Variable.of(variableName1, false, () -> getCtxString(ctx)), (varId, varEntry) -> { var variable = varEntry.getVariable(); idHolder.set(varId); if (variable.isScalar()) { // Scalar if (!ctx.expr().isEmpty()) { throw new PuffinBasicSemanticError( PuffinBasicSemanticError.ErrorCode.SCALAR_VARIABLE_CANNOT_BE_INDEXED, getCtxString(ctx), "Scalar variable cannot be indexed: " + variable); } } else if (variable.isArray()) { if (!ctx.expr().isEmpty()) { // Array ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RESET_ARRAY_IDX, varId, NULL_ID, NULL_ID); for (var exprCtx : ctx.expr()) { var exprInstr = lookupInstruction(exprCtx); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.SET_ARRAY_IDX, varId, exprInstr.result, NULL_ID); } var refId = ir.getSymbolTable().addArrayReference(varEntry); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAYREF, varId, refId, refId); idHolder.set(refId); } } else if (variable.isUDF()) { // UDF var udfEntry = (STUDF) varEntry; var udfState = udfStateMap.get(variable); // Create & Push Runtime scope var pushScopeInstr = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PUSH_RT_SCOPE, varId, NULL_ID, NULL_ID); // Copy caller params to Runtime scope if (ctx.expr().size() != udfEntry.getNumDeclaredParams()) { throw new PuffinBasicSemanticError( INSUFFICIENT_UDF_ARGS, getCtxString(ctx), variable + " expects " + udfEntry.getNumDeclaredParams() + ", #args passed: " + ctx.expr().size()); } int i = 0; for (var exprCtx : ctx.expr()) { var exprInstr = lookupInstruction(exprCtx); var declParamId = udfEntry.getDeclaraedParam(i++); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.COPY, declParamId, exprInstr.result, declParamId); } // GOTO labelFuncStart ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL, udfState.labelFuncStart.op1, NULL_ID, NULL_ID); // LABEL caller return address var labelCallerReturn = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID); // Patch address of the caller pushScopeInstr.patchOp2(labelCallerReturn.op1); // Pop Runtime scope ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.POP_RT_SCOPE, varId, NULL_ID, NULL_ID); } }); var refId = idHolder.get(); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.VARIABLE, refId, NULL_ID, refId )); } // // Expr // private void copyAndRegisterExprResult(ParserRuleContext ctx, Instruction instruction, boolean shouldCopy) { if (shouldCopy) { var copy = ir.getSymbolTable().addTmpCompatibleWith(instruction.result); instruction = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.COPY, copy, instruction.result, copy ); } nodeToInstruction.put(ctx, instruction); } @Override public void exitExprVariable(PuffinBasicParser.ExprVariableContext ctx) { var instruction = nodeToInstruction.get(ctx.variable()); var varEntry = ir.getSymbolTable().get(instruction.result); boolean copy = (varEntry instanceof STVariable) && ((STVariable) varEntry).getVariable().isUDF(); if (ctx.MINUS() != null) { if (ir.getSymbolTable().get(instruction.result).getValue().getDataType() == STRING) { throw new PuffinBasicSemanticError( DATA_TYPE_MISMATCH, getCtxString(ctx), "Unary minus cannot be used with a String!" ); } instruction = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.UNARY_MINUS, instruction.result, NULL_ID, ir.getSymbolTable().addTmpCompatibleWith(instruction.result) ); copy = true; } copyAndRegisterExprResult(ctx, instruction, copy); } @Override public void exitExprParen(PuffinBasicParser.ExprParenContext ctx) { nodeToInstruction.put(ctx, lookupInstruction(ctx.expr())); } @Override public void exitExprNumber(PuffinBasicParser.ExprNumberContext ctx) { var instruction = nodeToInstruction.get(ctx.number()); if (ctx.MINUS() != null) { instruction = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.UNARY_MINUS, instruction.result, NULL_ID, ir.getSymbolTable().addTmpCompatibleWith(instruction.result) ); } copyAndRegisterExprResult(ctx, instruction, false); } @Override public void exitExprFunc(PuffinBasicParser.ExprFuncContext ctx) { var instruction = nodeToInstruction.get(ctx.func()); if (ctx.MINUS() != null) { instruction = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.UNARY_MINUS, instruction.result, NULL_ID, ir.getSymbolTable().addTmpCompatibleWith(instruction.result) ); } copyAndRegisterExprResult(ctx, instruction, false); } @Override public void exitExprString(PuffinBasicParser.ExprStringContext ctx) { var text = unquote(ctx.string().STRING().getText()); var id = ir.getSymbolTable().addTmp(STRING, entry -> entry.getValue().setString(text)); copyAndRegisterExprResult(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.VALUE, id, NULL_ID, id ), false); } @Override public void exitExprExp(PuffinBasicParser.ExprExpContext ctx) { addArithmeticOpExpr(ctx, OpCode.EXP, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprMul(PuffinBasicParser.ExprMulContext ctx) { addArithmeticOpExpr(ctx, OpCode.MUL, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprIntDiv(PuffinBasicParser.ExprIntDivContext ctx) { addArithmeticOpExpr(ctx, OpCode.IDIV, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprFloatDiv(PuffinBasicParser.ExprFloatDivContext ctx) { addArithmeticOpExpr(ctx, OpCode.FDIV, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprMod(PuffinBasicParser.ExprModContext ctx) { addArithmeticOpExpr(ctx, OpCode.MOD, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprPlus(PuffinBasicParser.ExprPlusContext ctx) { var expr1 = ctx.expr(0); var expr2 = ctx.expr(1); int instr1res = lookupInstruction(expr1).result; int instr2res = lookupInstruction(expr2).result; var dt1 = ir.getSymbolTable().get(instr1res).getValue().getDataType(); var dt2 = ir.getSymbolTable().get(instr2res).getValue().getDataType(); if (dt1 == STRING && dt2 == STRING) { nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CONCAT, instr1res, instr2res, ir.getSymbolTable().addTmp(STRING, e -> {}) )); } else { addArithmeticOpExpr(ctx, OpCode.ADD, expr1, expr2); } } @Override public void exitExprMinus(PuffinBasicParser.ExprMinusContext ctx) { addArithmeticOpExpr(ctx, OpCode.SUB, ctx.expr(0), ctx.expr(1)); } private void addArithmeticOpExpr( ParserRuleContext parent, OpCode opCode, PuffinBasicParser.ExprContext exprLeft, PuffinBasicParser.ExprContext exprRight) { var exprL = lookupInstruction(exprLeft); var exprR = lookupInstruction(exprRight); var dt1 = ir.getSymbolTable().get(exprL.result).getValue().getDataType(); var dt2 = ir.getSymbolTable().get(exprR.result).getValue().getDataType(); Types.assertNumeric(dt1, dt2, () -> getCtxString(parent)); var result = ir.getSymbolTable().addTmp( Types.upcast(dt1, ir.getSymbolTable().get(exprR.result).getValue().getDataType(), () -> getCtxString(parent)), e -> {}); nodeToInstruction.put(parent, ir.addInstruction( currentLineNumber, parent.start.getStartIndex(), parent.stop.getStopIndex(), opCode, exprL.result, exprR.result, result )); } @Override public void exitExprRelEq(PuffinBasicParser.ExprRelEqContext ctx) { addRelationalOpExpr(ctx, OpCode.EQ, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprRelNeq(PuffinBasicParser.ExprRelNeqContext ctx) { addRelationalOpExpr(ctx, OpCode.NE, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprRelLt(PuffinBasicParser.ExprRelLtContext ctx) { addRelationalOpExpr(ctx, OpCode.LT, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprRelLe(PuffinBasicParser.ExprRelLeContext ctx) { addRelationalOpExpr(ctx, OpCode.LE, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprRelGt(PuffinBasicParser.ExprRelGtContext ctx) { addRelationalOpExpr(ctx, OpCode.GT, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprRelGe(PuffinBasicParser.ExprRelGeContext ctx) { addRelationalOpExpr(ctx, OpCode.GE, ctx.expr(0), ctx.expr(1)); } private void addRelationalOpExpr( ParserRuleContext parent, OpCode opCode, PuffinBasicParser.ExprContext exprLeft, PuffinBasicParser.ExprContext exprRight) { var exprL = lookupInstruction(exprLeft); var exprR = lookupInstruction(exprRight); checkDataTypeMatch(exprL.result, exprR.result, () -> getCtxString(parent)); var result = ir.getSymbolTable().addTmp(INT64, e -> {}); nodeToInstruction.put(parent, ir.addInstruction( currentLineNumber, parent.start.getStartIndex(), parent.stop.getStopIndex(), opCode, exprL.result, exprR.result, result )); } @Override public void exitExprLogNot(PuffinBasicParser.ExprLogNotContext ctx) { var expr = lookupInstruction(ctx.expr()); Types.assertNumeric( ir.getSymbolTable().get(expr.result).getValue().getDataType(), () -> getCtxString(ctx) ); var result = ir.getSymbolTable().addTmp(INT64, e -> {}); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.NOT, expr.result, NULL_ID, result )); } @Override public void exitExprLogAnd(PuffinBasicParser.ExprLogAndContext ctx) { addLogicalOpExpr(ctx, OpCode.AND, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprLogOr(PuffinBasicParser.ExprLogOrContext ctx) { addLogicalOpExpr(ctx, OpCode.OR, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprLogXor(PuffinBasicParser.ExprLogXorContext ctx) { addLogicalOpExpr(ctx, OpCode.XOR, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprLogEqv(PuffinBasicParser.ExprLogEqvContext ctx) { addLogicalOpExpr(ctx, OpCode.EQV, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprLogImp(PuffinBasicParser.ExprLogImpContext ctx) { addLogicalOpExpr(ctx, OpCode.IMP, ctx.expr(0), ctx.expr(1)); } private void addLogicalOpExpr( ParserRuleContext parent, OpCode opCode, PuffinBasicParser.ExprContext exprLeft, PuffinBasicParser.ExprContext exprRight) { var exprL = lookupInstruction(exprLeft); var exprR = lookupInstruction(exprRight); Types.assertNumeric( ir.getSymbolTable().get(exprL.result).getValue().getDataType(), ir.getSymbolTable().get(exprR.result).getValue().getDataType(), () -> getCtxString(parent) ); var result = ir.getSymbolTable().addTmp(INT64, e -> {}); nodeToInstruction.put(parent, ir.addInstruction( currentLineNumber, parent.start.getStartIndex(), parent.stop.getStopIndex(), opCode, exprL.result, exprR.result, result )); } // // Functions // @Override public void exitFuncAbs(PuffinBasicParser.FuncAbsContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.ABS, ctx, ctx.expr(), NumericOrString.NUMERIC)); } @Override public void exitFuncAsc(PuffinBasicParser.FuncAscContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.ASC, ctx, ctx.expr(), NumericOrString.STRING, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncSin(PuffinBasicParser.FuncSinContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.SIN, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncCos(PuffinBasicParser.FuncCosContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.COS, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncTan(PuffinBasicParser.FuncTanContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.TAN, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncASin(PuffinBasicParser.FuncASinContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.ASIN, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncACos(PuffinBasicParser.FuncACosContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.ACOS, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncAtn(PuffinBasicParser.FuncAtnContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.ATN, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncSinh(PuffinBasicParser.FuncSinhContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.SINH, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncCosh(PuffinBasicParser.FuncCoshContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.COSH, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncTanh(PuffinBasicParser.FuncTanhContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.TANH, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncExp(PuffinBasicParser.FuncExpContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.EEXP, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncLog10(PuffinBasicParser.FuncLog10Context ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.LOG10, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncToRad(PuffinBasicParser.FuncToRadContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.TORAD, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncToDeg(PuffinBasicParser.FuncToDegContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.TODEG, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncFloor(PuffinBasicParser.FuncFloorContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.FLOOR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncCeil(PuffinBasicParser.FuncCeilContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CEIL, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncRound(PuffinBasicParser.FuncRoundContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.ROUND, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncSqr(PuffinBasicParser.FuncSqrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.SQR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncCint(PuffinBasicParser.FuncCintContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CINT, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncClng(PuffinBasicParser.FuncClngContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CLNG, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(INT64, c -> {}))); } @Override public void exitFuncCsng(PuffinBasicParser.FuncCsngContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CSNG, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(FLOAT, c -> {}))); } @Override public void exitFuncCdbl(PuffinBasicParser.FuncCdblContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CDBL, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncCvi(PuffinBasicParser.FuncCviContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CVI, ctx, ctx.expr(), NumericOrString.STRING, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncCvl(PuffinBasicParser.FuncCvlContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CVL, ctx, ctx.expr(), NumericOrString.STRING, ir.getSymbolTable().addTmp(INT64, c -> {}))); } @Override public void exitFuncCvs(PuffinBasicParser.FuncCvsContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CVS, ctx, ctx.expr(), NumericOrString.STRING, ir.getSymbolTable().addTmp(FLOAT, c -> {}))); } @Override public void exitFuncCvd(PuffinBasicParser.FuncCvdContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CVD, ctx, ctx.expr(), NumericOrString.STRING, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncMkiDlr(PuffinBasicParser.FuncMkiDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.MKIDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncMklDlr(PuffinBasicParser.FuncMklDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.MKLDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncMksDlr(PuffinBasicParser.FuncMksDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.MKSDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncMkdDlr(PuffinBasicParser.FuncMkdDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.MKDDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncSpaceDlr(PuffinBasicParser.FuncSpaceDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.SPACEDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncStrDlr(PuffinBasicParser.FuncStrDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.STRDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncVal(PuffinBasicParser.FuncValContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.VAL , ctx, ctx.expr(), NumericOrString.STRING, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncInt(PuffinBasicParser.FuncIntContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.INT, ctx, ctx.expr(), NumericOrString.NUMERIC)); } @Override public void exitFuncFix(PuffinBasicParser.FuncFixContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.FIX, ctx, ctx.expr(), NumericOrString.NUMERIC)); } @Override public void exitFuncLog(PuffinBasicParser.FuncLogContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.LOG, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncLen(PuffinBasicParser.FuncLenContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.LEN, ctx, ctx.expr(), NumericOrString.STRING, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncChrDlr(PuffinBasicParser.FuncChrDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CHRDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncHexDlr(PuffinBasicParser.FuncHexDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.HEXDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncOctDlr(PuffinBasicParser.FuncOctDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.OCTDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncLeftDlr(PuffinBasicParser.FuncLeftDlrContext ctx) { var xdlr = lookupInstruction(ctx.expr(0)); var n = lookupInstruction(ctx.expr(1)); Types.assertString(ir.getSymbolTable().get(xdlr.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(n.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LEFTDLR, xdlr.result, n.result, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncRightDlr(PuffinBasicParser.FuncRightDlrContext ctx) { var xdlr = lookupInstruction(ctx.expr(0)); var n = lookupInstruction(ctx.expr(1)); Types.assertString(ir.getSymbolTable().get(xdlr.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(n.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RIGHTDLR, xdlr.result, n.result, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncInstr(PuffinBasicParser.FuncInstrContext ctx) { int xdlr, ydlr, n; if (ctx.expr().size() == 3) { // n, x$, y$ n = lookupInstruction(ctx.expr(0)).result; xdlr = lookupInstruction(ctx.expr(1)).result; ydlr = lookupInstruction(ctx.expr(2)).result; Types.assertNumeric(ir.getSymbolTable().get(n).getValue().getDataType(), () -> getCtxString(ctx)); } else { // x$, y$ n = ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(1)); xdlr = lookupInstruction(ctx.expr(0)).result; ydlr = lookupInstruction(ctx.expr(1)).result; } Types.assertString(ir.getSymbolTable().get(xdlr).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertString(ir.getSymbolTable().get(ydlr).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INSTR0, xdlr, ydlr, NULL_ID); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INSTR, n, NULL_ID, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncMidDlr(PuffinBasicParser.FuncMidDlrContext ctx) { int xdlr, n, m; if (ctx.expr().size() == 3) { // x$, n, m xdlr = lookupInstruction(ctx.expr(0)).result; n = lookupInstruction(ctx.expr(1)).result; m = lookupInstruction(ctx.expr(2)).result; Types.assertNumeric(ir.getSymbolTable().get(m).getValue().getDataType(), () -> getCtxString(ctx)); } else { // x$, n xdlr = lookupInstruction(ctx.expr(0)).result; n = lookupInstruction(ctx.expr(1)).result; m = ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(Integer.MAX_VALUE)); } Types.assertString(ir.getSymbolTable().get(xdlr).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(n).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.MIDDLR0, xdlr, n, NULL_ID); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.MIDDLR, m, NULL_ID, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncRnd(PuffinBasicParser.FuncRndContext ctx) { nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RND, NULL_ID, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncSgn(PuffinBasicParser.FuncSgnContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.SGN, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncTimer(PuffinBasicParser.FuncTimerContext ctx) { nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.TIMER, NULL_ID, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncStringDlr(PuffinBasicParser.FuncStringDlrContext ctx) { int n = lookupInstruction(ctx.expr(0)).result; int jOrxdlr = lookupInstruction(ctx.expr(1)).result; Types.assertNumeric(ir.getSymbolTable().get(n).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.STRINGDLR, n, jOrxdlr, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncLoc(PuffinBasicParser.FuncLocContext ctx) { var fileNumber = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(fileNumber.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LOC, fileNumber.result, NULL_ID, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncLof(PuffinBasicParser.FuncLofContext ctx) { var fileNumber = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(fileNumber.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LOF, fileNumber.result, NULL_ID, ir.getSymbolTable().addTmp(INT64, c -> {}))); } @Override public void exitFuncEof(PuffinBasicParser.FuncEofContext ctx) { var fileNumber = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(fileNumber.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.EOF, fileNumber.result, NULL_ID, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncEnvironDlr(PuffinBasicParser.FuncEnvironDlrContext ctx) { var expr = lookupInstruction(ctx.expr()); Types.assertString(ir.getSymbolTable().get(expr.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ENVIRONDLR, expr.result, NULL_ID, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncInputDlr(PuffinBasicParser.FuncInputDlrContext ctx) { var x = lookupInstruction(ctx.expr(0)); Types.assertNumeric(ir.getSymbolTable().get(x.result).getValue().getDataType(), () -> getCtxString(ctx)); int fileNumberId; if (ctx.expr().size() == 2) { var fileNumber = lookupInstruction(ctx.expr(1)); Types.assertNumeric(ir.getSymbolTable().get(fileNumber.result).getValue().getDataType(), () -> getCtxString(ctx)); fileNumberId = fileNumber.result; } else { fileNumberId = ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(-1)); } nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INPUTDLR, x.result, fileNumberId, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncInkeyDlr(PuffinBasicParser.FuncInkeyDlrContext ctx) { assertGraphics(); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INKEYDLR, NULL_ID, NULL_ID, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncE(PuffinBasicParser.FuncEContext ctx) { nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.E, NULL_ID, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncPI(PuffinBasicParser.FuncPIContext ctx) { nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PI, NULL_ID, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncMin(PuffinBasicParser.FuncMinContext ctx) { var expr1 = lookupInstruction(ctx.expr(0)); var expr2 = lookupInstruction(ctx.expr(1)); var dt1 = ir.getSymbolTable().get(expr1.result).getValue().getDataType(); var dt2 = ir.getSymbolTable().get(expr2.result).getValue().getDataType(); Types.assertNumeric(dt1, () -> getCtxString(ctx)); Types.assertNumeric(dt2, () -> getCtxString(ctx)); var resdt = Types.upcast(dt1, dt2, () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.MIN, expr1.result, expr2.result, ir.getSymbolTable().addTmp(resdt, e -> {}))); } @Override public void exitFuncMax(PuffinBasicParser.FuncMaxContext ctx) { var expr1 = lookupInstruction(ctx.expr(0)); var expr2 = lookupInstruction(ctx.expr(1)); var dt1 = ir.getSymbolTable().get(expr1.result).getValue().getDataType(); var dt2 = ir.getSymbolTable().get(expr2.result).getValue().getDataType(); Types.assertNumeric(dt1, () -> getCtxString(ctx)); Types.assertNumeric(dt2, () -> getCtxString(ctx)); var resdt = Types.upcast(dt1, dt2, () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.MAX, expr1.result, expr2.result, ir.getSymbolTable().addTmp(resdt, e -> {}))); } @Override public void exitFuncArrayNDFill(PuffinBasicParser.FuncArrayNDFillContext ctx) { var varInstr = getArrayNdVariableInstruction(ctx, ctx.variable()); var expr = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(expr.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAYFILL, varInstr.result, expr.result, ir.getSymbolTable().addTmp(INT32, e -> {}))); } private Instruction getArray1dVariableInstruction(ParserRuleContext ctx, VariableContext varCtx, boolean numeric) { var varInstr = lookupInstruction(varCtx); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); var varEntry = (STVariable) ir.getSymbolTable().get(varInstr.result); assertVariableDefined(varEntry.getVariable().getVariableName(), () -> getCtxString(ctx)); assert1DArray(varEntry, () -> getCtxString(ctx)); if (numeric) { assertNumeric(varEntry.getValue().getDataType(), () -> getCtxString(ctx)); } return varInstr; } private Instruction getArray2dVariableInstruction(ParserRuleContext ctx, VariableContext varCtx) { var varInstr = lookupInstruction(varCtx); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); var varEntry = (STVariable) ir.getSymbolTable().get(varInstr.result); assertVariableDefined(varEntry.getVariable().getVariableName(), () -> getCtxString(ctx)); assert2DArray(varEntry, () -> getCtxString(ctx)); return varInstr; } private Instruction getArrayNdVariableInstruction(ParserRuleContext ctx, VariableContext varCtx) { var varInstr = lookupInstruction(varCtx); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); var varEntry = (STVariable) ir.getSymbolTable().get(varInstr.result); assertVariableDefined(varEntry.getVariable().getVariableName(), () -> getCtxString(ctx)); assertNDArray(varEntry, () -> getCtxString(ctx)); return varInstr; } @Override public void exitFuncArray1DMean(PuffinBasicParser.FuncArray1DMeanContext ctx) { var var1Instr = getArray1dVariableInstruction(ctx, ctx.variable(), true); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DMEAN, var1Instr.result, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, e -> {}))); } @Override public void exitFuncArray1DStd(PuffinBasicParser.FuncArray1DStdContext ctx) { var var1Instr = getArray1dVariableInstruction(ctx, ctx.variable(), true); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DSTD, var1Instr.result, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, e -> {}))); } @Override public void exitFuncArray1DMedian(PuffinBasicParser.FuncArray1DMedianContext ctx) { var var1Instr = getArray1dVariableInstruction(ctx, ctx.variable(), true); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DMEDIAN, var1Instr.result, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, e -> {}))); } @Override public void exitFuncArray1DSort(PuffinBasicParser.FuncArray1DSortContext ctx) { var var1Instr = getArray1dVariableInstruction(ctx, ctx.variable(), false); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DSORT, var1Instr.result, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, e -> {}))); } @Override public void exitFuncArray1DBinSearch(PuffinBasicParser.FuncArray1DBinSearchContext ctx) { var var1Instr = getArray1dVariableInstruction(ctx, ctx.variable(), false); var expr = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(expr.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DBINSEARCH, var1Instr.result, expr.result, ir.getSymbolTable().addTmp(DOUBLE, e -> {}))); } @Override public void exitFuncArray1DPct(PuffinBasicParser.FuncArray1DPctContext ctx) { var var1Instr = getArray1dVariableInstruction(ctx, ctx.variable(), true); var expr = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(expr.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DPCT, var1Instr.result, expr.result, ir.getSymbolTable().addTmp(DOUBLE, e -> {}))); } @Override public void exitFuncArrayNDCopy(PuffinBasicParser.FuncArrayNDCopyContext ctx) { var var1Instr = getArrayNdVariableInstruction(ctx, ctx.variable(0)); var var2Instr = getArrayNdVariableInstruction(ctx, ctx.variable(1)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAYCOPY, var1Instr.result, var2Instr.result, ir.getSymbolTable().addTmp(INT32, e -> {}))); } @Override public void exitFuncArray1DCopy(PuffinBasicParser.FuncArray1DCopyContext ctx) { var var1Instr = getArray1dVariableInstruction(ctx, ctx.variable(0), false); var var2Instr = getArray1dVariableInstruction(ctx, ctx.variable(1), false); var src0 = lookupInstruction(ctx.src0); Types.assertNumeric(ir.getSymbolTable().get(src0.result).getValue().getDataType(), () -> getCtxString(ctx)); var dst0 = lookupInstruction(ctx.dst0); Types.assertNumeric(ir.getSymbolTable().get(dst0.result).getValue().getDataType(), () -> getCtxString(ctx)); var len = lookupInstruction(ctx.len); Types.assertNumeric(ir.getSymbolTable().get(len.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DCOPYSRC, var1Instr.result, src0.result, ir.getSymbolTable().addTmp(INT32, e -> {}))); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DCOPYDST, var2Instr.result, dst0.result, ir.getSymbolTable().addTmp(INT32, e -> {}))); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DCOPY, len.result, NULL_ID, ir.getSymbolTable().addTmp(INT32, e -> {}))); } @Override public void exitFuncArray2DShiftHor(PuffinBasicParser.FuncArray2DShiftHorContext ctx) { var varInstr = getArray2dVariableInstruction(ctx, ctx.variable()); var expr = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(expr.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY2DSHIFTHOR, varInstr.result, expr.result, ir.getSymbolTable().addTmp(INT32, e -> {}))); } @Override public void exitFuncArray2DShiftVer(PuffinBasicParser.FuncArray2DShiftVerContext ctx) { var varInstr = getArray2dVariableInstruction(ctx, ctx.variable()); var expr = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(expr.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY2DSHIFTVER, varInstr.result, expr.result, ir.getSymbolTable().addTmp(INT32, e -> {}))); } private Instruction addFuncWithExprInstruction( OpCode opCode, ParserRuleContext parent, PuffinBasicParser.ExprContext expr, NumericOrString numericOrString) { var exprInstruction = lookupInstruction(expr); assertNumericOrString(exprInstruction.result, parent, numericOrString); return ir.addInstruction( currentLineNumber, parent.start.getStartIndex(), parent.stop.getStopIndex(), opCode, exprInstruction.result, NULL_ID, ir.getSymbolTable().addTmpCompatibleWith(exprInstruction.result) ); } private Instruction addFuncWithExprInstruction( OpCode opCode, ParserRuleContext parent, PuffinBasicParser.ExprContext expr, NumericOrString numericOrString, int result) { var exprInstruction = lookupInstruction(expr); assertNumericOrString(exprInstruction.result, parent, numericOrString); return ir.addInstruction( currentLineNumber, parent.start.getStartIndex(), parent.stop.getStopIndex(), opCode, exprInstruction.result, NULL_ID, result ); } private void assertNumericOrString(int id, ParserRuleContext parent, NumericOrString numericOrString) { var dt = ir.getSymbolTable().get(id).getValue().getDataType(); if (numericOrString == NumericOrString.NUMERIC) { Types.assertNumeric(dt, () -> getCtxString(parent)); } else { Types.assertString(dt, () -> getCtxString(parent)); } } // // Stmt // @Override public void exitComment(PuffinBasicParser.CommentContext ctx) { ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.COMMENT, NULL_ID, NULL_ID, NULL_ID ); } @Override public void exitLetstmt(PuffinBasicParser.LetstmtContext ctx) { var varname = ctx.variable().varname().VARNAME().getText(); var varsuffix = ctx.variable().varsuffix() != null ? ctx.variable().varsuffix().getText() : null; var dataType = ir.getSymbolTable().getDataTypeFor(varname, varsuffix); var variableName = new VariableName(varname, dataType); var exprInstruction = lookupInstruction(ctx.expr()); final int varId = ir.getSymbolTable().addVariableOrUDF( variableName, variableName1 -> Variable.of(variableName1, false, () -> getCtxString(ctx)), (id, varEntry) -> { var variable = varEntry.getVariable(); if (variable.isUDF()) { throw new PuffinBasicSemanticError( BAD_ASSIGNMENT, getCtxString(ctx), "Can't assign to UDF: " + variable ); } checkDataTypeMatch(varEntry.getValue(), exprInstruction.result, () -> getCtxString(ctx)); }); var varInstr = lookupInstruction(ctx.variable()); var assignInstruction = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ASSIGN, varInstr.result, exprInstruction.result, varInstr.result ); nodeToInstruction.put(ctx, assignInstruction); varDefined.add(variableName); } @Override public void exitPrintstmt(PuffinBasicParser.PrintstmtContext ctx) { handlePrintstmt(ctx, ctx.printlist().children, null); } @Override public void exitPrinthashstmt(PuffinBasicParser.PrinthashstmtContext ctx) { var fileNumber = lookupInstruction(ctx.filenum); handlePrintstmt(ctx, ctx.printlist().children, fileNumber); } private void handlePrintstmt( ParserRuleContext ctx, List<ParseTree> children, @Nullable Instruction fileNumber) { boolean endsWithNewline = true; for (ParseTree child : children) { if (child instanceof PuffinBasicParser.ExprContext) { var exprInstruction = lookupInstruction((PuffinBasicParser.ExprContext) child); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PRINT, exprInstruction.result, NULL_ID, NULL_ID ); endsWithNewline = true; } else { endsWithNewline = false; } } if (endsWithNewline || fileNumber != null) { var newlineId = ir.getSymbolTable().addTmp(STRING, entry -> entry.getValue().setString(System.lineSeparator())); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PRINT, newlineId, NULL_ID, NULL_ID ); } final int fileNumberId; if (fileNumber != null) { Types.assertNumeric(ir.getSymbolTable().get(fileNumber.result).getValue().getDataType(), () -> getCtxString(ctx)); fileNumberId = fileNumber.result; } else { fileNumberId = NULL_ID; } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.FLUSH, fileNumberId, NULL_ID, NULL_ID ); } @Override public void exitPrintusingstmt(PuffinBasicParser.PrintusingstmtContext ctx) { handlePrintusing(ctx, ctx.format, ctx.printlist().children, null); } @Override public void exitPrinthashusingstmt(PuffinBasicParser.PrinthashusingstmtContext ctx) { var fileNumber = lookupInstruction(ctx.filenum); handlePrintusing(ctx, ctx.format, ctx.printlist().children, fileNumber); } private void handlePrintusing( ParserRuleContext ctx, PuffinBasicParser.ExprContext formatCtx, List<ParseTree> children, Instruction fileNumber) { var format = lookupInstruction(formatCtx); boolean endsWithNewline = true; for (ParseTree child : children) { if (child instanceof PuffinBasicParser.ExprContext) { var exprInstruction = lookupInstruction((PuffinBasicParser.ExprContext) child); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PRINTUSING, format.result, exprInstruction.result, NULL_ID ); endsWithNewline = true; } else { endsWithNewline = false; } } if (endsWithNewline || fileNumber != null) { var newlineId = ir.getSymbolTable().addTmp(STRING, entry -> entry.getValue().setString(System.lineSeparator())); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PRINT, newlineId, NULL_ID, NULL_ID ); } final int fileNumberId; if (fileNumber != null) { Types.assertNumeric(ir.getSymbolTable().get(fileNumber.result).getValue().getDataType(), () -> getCtxString(ctx)); fileNumberId = fileNumber.result; } else { fileNumberId = NULL_ID; } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.FLUSH, fileNumberId, NULL_ID, NULL_ID ); } @Override public void exitDimstmt(PuffinBasicParser.DimstmtContext ctx) { IntList dims = new IntArrayList(ctx.DECIMAL().size()); for (var dimMax : ctx.DECIMAL()) { int dimSize = Numbers.parseInt32(dimMax.getText(), () -> getCtxString(ctx)); dims.add(dimSize); } var varname = ctx.varname().VARNAME().getText(); var varsuffix = ctx.varsuffix() != null ? ctx.varsuffix().getText() : null; var dataType = ir.getSymbolTable().getDataTypeFor(varname, varsuffix); var variableName = new VariableName(varname, dataType); ir.getSymbolTable().addVariableOrUDF( variableName, variableName1 -> Variable.of(variableName1, true, () -> getCtxString(ctx)), (id, entry) -> entry.getValue().setArrayDimensions(dims)); varDefined.add(variableName); } @Override public void enterDeffnstmt(PuffinBasicParser.DeffnstmtContext ctx) { var varname = ctx.varname().getText(); var varsuffix = ctx.varsuffix() != null ? ctx.varsuffix().getText() : null; var dataType = ir.getSymbolTable().getDataTypeFor(varname, varsuffix); var variableName = new VariableName(varname, dataType); ir.getSymbolTable().addVariableOrUDF(variableName, variableName1 -> Variable.of(variableName1, false, () -> getCtxString(ctx)), (varId, varEntry) -> { var udfState = new UDFState(); udfStateMap.put(varEntry.getVariable(), udfState); // GOTO postFuncDecl udfState.gotoPostFuncDecl = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL, ir.getSymbolTable().addGotoTarget(), NULL_ID, NULL_ID ); // LABEL FuncStart udfState.labelFuncStart = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); // Push child scope ir.getSymbolTable().pushDeclarationScope(varId); }); } @Override public void exitDeffnstmt(PuffinBasicParser.DeffnstmtContext ctx) { var varname = ctx.varname().getText(); var varsuffix = ctx.varsuffix() != null ? ctx.varsuffix().getText() : null; var dataType = ir.getSymbolTable().getDataTypeFor(varname, varsuffix); var variableName = new VariableName(varname, dataType); ir.getSymbolTable().addVariableOrUDF(variableName, variableName1 -> Variable.of(variableName1, false, () -> getCtxString(ctx)), (varId, varEntry) -> { var udfEntry = (STUDF) varEntry; var udfState = udfStateMap.get(varEntry.getVariable()); for (VariableContext fnParamCtx : ctx.variable()) { var fnParamInstr = lookupInstruction(fnParamCtx); udfEntry.declareParam(fnParamInstr.result); } var exprInstr = lookupInstruction(ctx.expr()); checkDataTypeMatch(varId, exprInstr.result, () -> getCtxString(ctx)); // Copy expr to result ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.COPY, varId, exprInstr.result, varId ); // Pop declaration scope ir.getSymbolTable().popScope(); // GOTO Caller ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_CALLER, NULL_ID, NULL_ID, NULL_ID ); // LABEL postFuncDecl var labelPostFuncDecl = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); // Patch GOTO postFuncDecl udfState.gotoPostFuncDecl.patchOp1(labelPostFuncDecl.op1); }); } @Override public void exitEndstmt(PuffinBasicParser.EndstmtContext ctx) { ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.END, NULL_ID, NULL_ID,NULL_ID ); } @Override public void enterWhilestmt(PuffinBasicParser.WhilestmtContext ctx) { var whileLoopState = new WhileLoopState(); // LABEL beforeWhile whileLoopState.labelBeforeWhile = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); whileLoopStateList.add(whileLoopState); } @Override public void exitWhilestmt(PuffinBasicParser.WhilestmtContext ctx) { var whileLoopState = whileLoopStateList.getLast(); // expr() var expr = lookupInstruction(ctx.expr()); // NOT expr() var notExpr = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.NOT, expr.result, NULL_ID, ir.getSymbolTable().addTmp(INT64, e -> {}) ); // If expr is false, GOTO afterWend whileLoopState.gotoAfterWend = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL_IF, notExpr.result, ir.getSymbolTable().addLabel(), NULL_ID ); } @Override public void exitWendstmt(PuffinBasicParser.WendstmtContext ctx) { if (whileLoopStateList.isEmpty()) { throw new PuffinBasicSemanticError( PuffinBasicSemanticError.ErrorCode.WEND_WITHOUT_WHILE, getCtxString(ctx), "Wend without while"); } var whileLoopState = whileLoopStateList.removeLast(); // GOTO LABEL beforeWhile ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL, whileLoopState.labelBeforeWhile.op1, NULL_ID, NULL_ID); // LABEL afterWend var labelAfterWend = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); // Patch GOTO afterWend whileLoopState.gotoAfterWend.patchOp2(labelAfterWend.op1); } @Override public void exitForstmt(PuffinBasicParser.ForstmtContext ctx) { var var = lookupInstruction(ctx.variable()); var init = lookupInstruction(ctx.expr(0)); var end = lookupInstruction(ctx.expr(1)); Types.assertNumeric(ir.getSymbolTable().get(init.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(end.result).getValue().getDataType(), () -> getCtxString(ctx)); var forLoopState = new ForLoopState(); forLoopState.variable = ((STVariable) ir.getSymbolTable().get(var.result)).getVariable(); // stepCopy = step or 1 (default) Instruction stepCopy; if (ctx.expr(2) != null) { var step = lookupInstruction(ctx.expr(2)); Types.assertNumeric(ir.getSymbolTable().get(step.result).getValue().getDataType(), () -> getCtxString(ctx)); var tmpStep = ir.getSymbolTable().addTmpCompatibleWith(step.result); stepCopy = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.COPY, tmpStep, step.result, tmpStep ); } else { var tmpStep = ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(1)); stepCopy = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.VALUE, tmpStep, NULL_ID, tmpStep ); } // var=init ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ASSIGN, var.result, init.result, var.result ); // endCopy=end var tmpEnd = ir.getSymbolTable().addTmpCompatibleWith(end.result); var endCopy = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ASSIGN, tmpEnd, end.result, tmpEnd ); // GOTO LABEL CHECK var gotoLabelCheck = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL, ir.getSymbolTable().addGotoTarget(), NULL_ID, NULL_ID ); // APPLY STEP // JUMP here from NEXT forLoopState.labelApplyStep = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); var tmpAdd = ir.getSymbolTable().addTmpCompatibleWith(var.result); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ADD, var.result, stepCopy.result, tmpAdd ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ASSIGN, var.result, tmpAdd, var.result ); // CHECK // If (step >= 0 and var > end) or (step < 0 and var < end) GOTO after "next" // step >= 0 var labelCheck = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); var zero = ir.getSymbolTable().addTmp(INT32, e -> {}); var t1 = ir.getSymbolTable().addTmp(INT32, e -> {}); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GE, stepCopy.result, zero, t1 ); // Patch GOTO LABEL Check gotoLabelCheck.patchOp1(labelCheck.op1); // var > end var t2 = ir.getSymbolTable().addTmp(INT32, e -> {}); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GT, var.result, endCopy.result, t2 ); // (step >= 0 and var > end) var t3 = ir.getSymbolTable().addTmp(INT32, e -> {}); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.AND, t1, t2, t3 ); // step < 0 var t4 = ir.getSymbolTable().addTmp(INT32, e -> {}); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LT, stepCopy.result, zero, t4 ); // var < end var t5 = ir.getSymbolTable().addTmp(INT32, e -> {}); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LT, var.result, endCopy.result, t5 ); // (step < 0 and var < end) var t6 = ir.getSymbolTable().addTmp(INT32, e -> {}); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.AND, t4, t5, t6 ); var t7 = ir.getSymbolTable().addTmp(INT32, e -> {}); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.OR, t3, t6, t7 ); // if (true) GOTO after NEXT // set linenumber on exitNext(). forLoopState.gotoAfterNext = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL_IF, t7, ir.getSymbolTable().addLabel(), NULL_ID ); forLoopStateList.add(forLoopState); } @Override public void exitNextstmt(PuffinBasicParser.NextstmtContext ctx) { List<ForLoopState> states = new ArrayList<>(1); if (ctx.variable().isEmpty()) { if (!forLoopStateList.isEmpty()) { states.add(forLoopStateList.removeLast()); } else { throw new PuffinBasicSemanticError( NEXT_WITHOUT_FOR, getCtxString(ctx), "NEXT without FOR" ); } } else { for (var varCtx : ctx.variable()) { var varname = varCtx.varname().VARNAME().getText(); var varsuffix = varCtx.varsuffix() != null ? varCtx.varsuffix().getText() : null; var dataType = ir.getSymbolTable().getDataTypeFor(varname, varsuffix); var variableName = new VariableName(varname, dataType); int id = ir.getSymbolTable().addVariableOrUDF( variableName, variableName1 -> Variable.of(variableName1, false, () -> getCtxString(ctx)), (id1, e1) -> {}); var variable = ((STVariable) ir.getSymbolTable().get(id)).getVariable(); var state = forLoopStateList.removeLast(); if (state.variable.equals(variable)) { states.add(state); } else { throw new PuffinBasicSemanticError( NEXT_WITHOUT_FOR, getCtxString(ctx), "Next " + variable + " without FOR" ); } } } for (ForLoopState state : states) { // GOTO APPLY STEP ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL, state.labelApplyStep.op1, NULL_ID, NULL_ID ); // LABEL afterNext var labelAfterNext = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); state.gotoAfterNext.patchOp2(labelAfterNext.op1); } } /* * condition * GOTOIF condition labelBeforeThen * GOTO labelAfterThen|labelBeforeElse * labelBeforeThen * ThenStmts * GOTO labelAfterThen|labelAfterElse * labelAfterThen * ElseStmts * labelAfterElse */ @Override public void enterIfThenElse(PuffinBasicParser.IfThenElseContext ctx) { nodeToIfState.put(ctx, new IfState()); } @Override public void exitIfThenElse(PuffinBasicParser.IfThenElseContext ctx) { var ifState = nodeToIfState.get(ctx); boolean noElseStmt = ifState.labelBeforeElse == null; var condition = lookupInstruction(ctx.expr()); // Patch IF true: condition ifState.gotoIfConditionTrue.patchOp1(condition.result); // Patch IF true: GOTO labelBeforeThen ifState.gotoIfConditionTrue.patchOp2(ifState.labelBeforeThen.op1); // Patch IF false: GOTO labelAfterThen|labelBeforeElse ifState.gotoIfConditionFalse.patchOp1( noElseStmt ? ifState.labelAfterThen.op1 : ifState.labelBeforeElse.op1 ); // Patch THEN: GOTO labelAfterThen|labelAfterElse ifState.gotoFromThenAfterIf.patchOp1( noElseStmt ? ifState.labelAfterThen.op1 : ifState.labelAfterElse.op1 ); } @Override public void enterThen(PuffinBasicParser.ThenContext ctx) { var ifState = nodeToIfState.get(ctx.getParent()); // IF condition is true, GOTO labelBeforeThen ifState.gotoIfConditionTrue = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL_IF, ir.getSymbolTable().addGotoTarget(), NULL_ID, NULL_ID ); // IF condition is false, GOTO labelAfterThen|labelBeforeElse ifState.gotoIfConditionFalse = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL, ir.getSymbolTable().addGotoTarget(), NULL_ID, NULL_ID ); ifState.labelBeforeThen = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); } @Override public void exitThen(PuffinBasicParser.ThenContext ctx) { // Add instruction for: // THEN GOTO linenum | THEN linenum if (ctx.linenum() != null) { var gotoLinenum = parseLinenum(ctx.linenum().getText()); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LINENUM, getGotoLineNumberOp1(gotoLinenum), NULL_ID, NULL_ID ); } var ifState = nodeToIfState.get(ctx.getParent()); // GOTO labelAfterThen|labelAfterElse ifState.gotoFromThenAfterIf = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); ifState.labelAfterThen = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); } @Override public void enterElsestmt(PuffinBasicParser.ElsestmtContext ctx) { var ifState = nodeToIfState.get(ctx.getParent()); ifState.labelBeforeElse = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); } @Override public void exitElsestmt(PuffinBasicParser.ElsestmtContext ctx) { // Add instruction for: // ELSE linenum if (ctx.linenum() != null) { var gotoLinenum = parseLinenum(ctx.linenum().getText()); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LINENUM, getGotoLineNumberOp1(gotoLinenum), NULL_ID, NULL_ID ); } var ifState = nodeToIfState.get(ctx.getParent()); ifState.labelAfterElse = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); } @Override public void exitGosubstmt(PuffinBasicParser.GosubstmtContext ctx) { var gotoLinenum = parseLinenum(ctx.linenum().getText()); var pushReturnLabel = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PUSH_RETLABEL, ir.getSymbolTable().addGotoTarget(), NULL_ID, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LINENUM, getGotoLineNumberOp1(gotoLinenum), NULL_ID, NULL_ID ); var labelReturn = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); pushReturnLabel.patchOp1(labelReturn.op1); } @Override public void exitReturnstmt(PuffinBasicParser.ReturnstmtContext ctx) { if (ctx.linenum() != null) { var gotoLinenum = parseLinenum(ctx.linenum().getText()); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RETURN, getGotoLineNumberOp1(gotoLinenum), NULL_ID, NULL_ID ); } else { ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RETURN, NULL_ID, NULL_ID, NULL_ID ); } } @Override public void exitGotostmt(PuffinBasicParser.GotostmtContext ctx) { var gotoLinenum = parseLinenum(ctx.linenum().getText()); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LINENUM, getGotoLineNumberOp1(gotoLinenum), NULL_ID, NULL_ID ); } @Override public void exitSwapstmt(PuffinBasicParser.SwapstmtContext ctx) { var var1 = lookupInstruction(ctx.variable(0)); var var2 = lookupInstruction(ctx.variable(1)); var dt1 = ir.getSymbolTable().get(var1.result).getValue().getDataType(); var dt2 = ir.getSymbolTable().get(var2.result).getValue().getDataType(); if (dt1 != dt2) { throw new PuffinBasicSemanticError( DATA_TYPE_MISMATCH, getCtxString(ctx), dt1 + " doesn't match " + dt2 ); } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.SWAP, var1.result, var2.result, NULL_ID ); } @Override public void exitOpen1stmt(PuffinBasicParser.Open1stmtContext ctx) { var filenameInstr = lookupInstruction(ctx.filename); var fileOpenMode = getFileOpenMode(ctx.filemode1()); var accessMode = getFileAccessMode(null); var lockMode = getLockMode(null); var fileNumber = Numbers.parseInt32(ctx.filenum.getText(), () -> getCtxString(ctx)); var recordLenInstrId = ctx.reclen != null ? lookupInstruction(ctx.reclen).result : ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(DEFAULT_RECORD_LEN)); Types.assertString(ir.getSymbolTable().get(filenameInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(recordLenInstrId).getValue().getDataType(), () -> getCtxString(ctx)); // fileName, fileNumber ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.OPEN_FN_FN_0, filenameInstr.result, ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(fileNumber)), NULL_ID ); // openMode, accessMode ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.OPEN_OM_AM_1, ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString(fileOpenMode.name())), ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString(accessMode.name())), NULL_ID ); // lockMode, recordLen ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.OPEN_LM_RL_2, ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString(lockMode.name())), recordLenInstrId, NULL_ID ); } @Override public void exitOpen2stmt(PuffinBasicParser.Open2stmtContext ctx) { var filenameInstr = lookupInstruction(ctx.filename); var fileOpenMode = getFileOpenMode(ctx.filemode2()); var accessMode = getFileAccessMode(ctx.access()); var lockMode = getLockMode(ctx.lock()); var fileNumber = Numbers.parseInt32(ctx.filenum.getText(), () -> getCtxString(ctx)); var recordLenInstrId = ctx.reclen != null ? lookupInstruction(ctx.reclen).result : ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(DEFAULT_RECORD_LEN)); Types.assertString(ir.getSymbolTable().get(filenameInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(recordLenInstrId).getValue().getDataType(), () -> getCtxString(ctx)); // fileName, fileNumber ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.OPEN_FN_FN_0, filenameInstr.result, ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(fileNumber)), NULL_ID ); // openMode, accessMode ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.OPEN_OM_AM_1, ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString(fileOpenMode.name())), ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString(accessMode.name())), NULL_ID ); // lockMode, recordLen ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.OPEN_LM_RL_2, ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString(lockMode.name())), recordLenInstrId, NULL_ID ); } @Override public void exitClosestmt(PuffinBasicParser.ClosestmtContext ctx) { var fileNumbers = ctx.DECIMAL().stream().map( fileNumberCtx -> Numbers.parseInt32(fileNumberCtx.getText(), () -> getCtxString(ctx)) ).collect(Collectors.toList()); if (fileNumbers.isEmpty()) { ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CLOSE_ALL, NULL_ID, NULL_ID, NULL_ID ); } else { fileNumbers.forEach(fileNumber -> ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CLOSE, ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(fileNumber)), NULL_ID, NULL_ID )); } } @Override public void exitFieldstmt(PuffinBasicParser.FieldstmtContext ctx) { var fileNumberInstr = lookupInstruction(ctx.filenum); Types.assertNumeric(ir.getSymbolTable().get(fileNumberInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); var numEntries = ctx.variable().size(); for (int i = 0; i < numEntries; i++) { var recordPartLen = Numbers.parseInt32(ctx.DECIMAL(i).getText(), () -> getCtxString(ctx)); var varInstr = lookupInstruction(ctx.variable(i)); var kind = ir.getSymbolTable().get(varInstr.result).getKind(); assertVariable(kind, () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.FIELD_I, varInstr.result, ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(recordPartLen)), NULL_ID ); } // FileNumber, #fields ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.FIELD, fileNumberInstr.result, ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(numEntries)), NULL_ID ); } private void assertVariable(STKind kind, Supplier<String> line) { if (kind != STKind.VARIABLE && kind != STKind.ARRAYREF) { throw new PuffinBasicSemanticError( BAD_ARGUMENT, line.get(), "Expected variable, but found: " + kind ); } } private void assertVariableDefined(VariableName variableName, Supplier<String> line) { if (!varDefined.contains(variableName)) { throw new PuffinBasicSemanticError( NOT_DEFINED, line.get(), "Variable: " + variableName + " used before it is defined!" ); } } private void assert1DArray(STVariable variable, Supplier<String> line) { if (!variable.getVariable().isArray() || variable.getValue().getNumArrayDimensions() != 1) { throw new PuffinBasicSemanticError( BAD_ARGUMENT, line.get(), "Variable: " + variable.getVariable().getVariableName() + " is not array1d" ); } } private void assert2DArray(STVariable variable, Supplier<String> line) { if (!variable.getVariable().isArray() || variable.getValue().getNumArrayDimensions() != 2) { throw new PuffinBasicSemanticError( BAD_ARGUMENT, line.get(), "Variable: " + variable.getVariable().getVariableName() + " is not array2d" ); } } private void assertNDArray(STVariable variable, Supplier<String> line) { if (!variable.getVariable().isArray()) { throw new PuffinBasicSemanticError( BAD_ARGUMENT, line.get(), "Variable: " + variable.getVariable().getVariableName() + " is not array" ); } } @Override public void exitPutstmt(PuffinBasicParser.PutstmtContext ctx) { var fileNumberInstr = Numbers.parseInt32(ctx.filenum.getText(), () -> getCtxString(ctx)); final int exprId; if (ctx.expr() != null) { exprId = lookupInstruction(ctx.expr()).result; Types.assertNumeric(ir.getSymbolTable().get(exprId).getValue().getDataType(), () -> getCtxString(ctx)); } else { exprId = NULL_ID; } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PUTF, ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(fileNumberInstr)), exprId, NULL_ID ); } @Override public void exitMiddlrstmt(PuffinBasicParser.MiddlrstmtContext ctx) { var varInstr = lookupInstruction(ctx.variable()); var nInstr = lookupInstruction(ctx.expr(0)); var mInstrId = ctx.expr().size() == 3 ? lookupInstruction(ctx.expr(1)).result : ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(-1)); var replacement = ctx.expr().size() == 3 ? lookupInstruction(ctx.expr(2)) : lookupInstruction(ctx.expr(1)); Types.assertString(ir.getSymbolTable().get(varInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertString(ir.getSymbolTable().get(replacement.result).getValue().getDataType(), () -> getCtxString(ctx)); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); assertVariableDefined(((STVariable) ir.getSymbolTable().get(varInstr.result)).getVariable().getVariableName(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(nInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(mInstrId).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.MIDDLR0, varInstr.result, nInstr.result, NULL_ID); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.MIDDLR_STMT, mInstrId, replacement.result, NULL_ID); } @Override public void exitGetstmt(PuffinBasicParser.GetstmtContext ctx) { var fileNumberInstr = Numbers.parseInt32(ctx.filenum.getText(), () -> getCtxString(ctx)); final int exprId; if (ctx.expr() != null) { exprId = lookupInstruction(ctx.expr()).result; Types.assertNumeric(ir.getSymbolTable().get(exprId).getValue().getDataType(), () -> getCtxString(ctx)); } else { exprId = NULL_ID; } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GETF, ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(fileNumberInstr)), exprId, NULL_ID ); } @Override public void exitRandomizestmt(PuffinBasicParser.RandomizestmtContext ctx) { var exprId = lookupInstruction(ctx.expr()).result; Types.assertNumeric(ir.getSymbolTable().get(exprId).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RANDOMIZE, exprId, NULL_ID, NULL_ID ); } @Override public void exitRandomizetimerstmt(PuffinBasicParser.RandomizetimerstmtContext ctx) { ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RANDOMIZE_TIMER, NULL_ID, NULL_ID, NULL_ID ); } @Override public void exitDefintstmt(PuffinBasicParser.DefintstmtContext ctx) { handleDefTypeStmt(ctx.LETTERRANGE(), INT32); } @Override public void exitDeflngstmt(PuffinBasicParser.DeflngstmtContext ctx) { handleDefTypeStmt(ctx.LETTERRANGE(), INT64); } @Override public void exitDefsngstmt(PuffinBasicParser.DefsngstmtContext ctx) { handleDefTypeStmt(ctx.LETTERRANGE(), FLOAT); } @Override public void exitDefdblstmt(PuffinBasicParser.DefdblstmtContext ctx) { handleDefTypeStmt(ctx.LETTERRANGE(), DOUBLE); } @Override public void exitDefstrstmt(PuffinBasicParser.DefstrstmtContext ctx) { handleDefTypeStmt(ctx.LETTERRANGE(), STRING); } @Override public void exitLsetstmt(PuffinBasicParser.LsetstmtContext ctx) { var varInstr = lookupInstruction(ctx.variable()); var exprInstr = lookupInstruction(ctx.expr()); var varEntry = ir.getSymbolTable().get(varInstr.result); assertVariable(varEntry.getKind(), () -> getCtxString(ctx)); Types.assertString(varEntry.getValue().getDataType(), () -> getCtxString(ctx)); Types.assertString(ir.getSymbolTable().get(exprInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LSET, varInstr.result, exprInstr.result, NULL_ID ); } @Override public void exitRsetstmt(PuffinBasicParser.RsetstmtContext ctx) { var varInstr = lookupInstruction(ctx.variable()); var exprInstr = lookupInstruction(ctx.expr()); var varEntry = ir.getSymbolTable().get(varInstr.result); assertVariable(varEntry.getKind(), () -> getCtxString(ctx)); assertVariableDefined(((STVariable) varEntry).getVariable().getVariableName(), () -> getCtxString(ctx)); Types.assertString(varEntry.getValue().getDataType(), () -> getCtxString(ctx)); Types.assertString(ir.getSymbolTable().get(exprInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RSET, varInstr.result, exprInstr.result, NULL_ID ); } @Override public void exitInputstmt(PuffinBasicParser.InputstmtContext ctx) { for (var varCtx : ctx.variable()) { var varInstr = lookupInstruction(varCtx); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INPUT_VAR, varInstr.result, NULL_ID, NULL_ID ); } int promptId; if (ctx.expr() != null) { promptId = lookupInstruction(ctx.expr()).result; Types.assertString(ir.getSymbolTable().get(promptId).getValue().getDataType(), () -> getCtxString(ctx)); } else { promptId = ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString("?")); } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INPUT, promptId, NULL_ID, NULL_ID ); } @Override public void exitInputhashstmt(PuffinBasicParser.InputhashstmtContext ctx) { for (var varCtx : ctx.variable()) { var varInstr = lookupInstruction(varCtx); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INPUT_VAR, varInstr.result, NULL_ID, NULL_ID ); } var fileNumInstr = lookupInstruction(ctx.filenum); Types.assertNumeric(ir.getSymbolTable().get(fileNumInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INPUT, NULL_ID, fileNumInstr.result, NULL_ID ); } @Override public void exitLineinputstmt(PuffinBasicParser.LineinputstmtContext ctx) { var varInstr = lookupInstruction(ctx.variable()); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INPUT_VAR, varInstr.result, NULL_ID, NULL_ID ); int promptId; if (ctx.expr() != null) { promptId = lookupInstruction(ctx.expr()).result; Types.assertString(ir.getSymbolTable().get(promptId).getValue().getDataType(), () -> getCtxString(ctx)); } else { promptId = ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString("")); } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LINE_INPUT, promptId, NULL_ID, NULL_ID ); } @Override public void exitLineinputhashstmt(PuffinBasicParser.LineinputhashstmtContext ctx) { var varInstr = lookupInstruction(ctx.variable()); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INPUT_VAR, varInstr.result, NULL_ID, NULL_ID ); var fileNumInstr = lookupInstruction(ctx.filenum); Types.assertNumeric(ir.getSymbolTable().get(fileNumInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LINE_INPUT, NULL_ID, fileNumInstr.result, NULL_ID ); } @Override public void exitWritestmt(PuffinBasicParser.WritestmtContext ctx) { handleWritestmt(ctx, ctx.expr(), null); } @Override public void exitWritehashstmt(PuffinBasicParser.WritehashstmtContext ctx) { var fileNumInstr = lookupInstruction(ctx.filenum); handleWritestmt(ctx, ctx.expr(), fileNumInstr); } public void handleWritestmt( ParserRuleContext ctx, List<PuffinBasicParser.ExprContext> exprs, @Nullable Instruction fileNumber) { // if fileNumber != null, skip first instruction for (int i = fileNumber == null ? 0 : 1; i < exprs.size(); i++) { var exprCtx = exprs.get(i); var exprInstr = lookupInstruction(exprCtx); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.WRITE, exprInstr.result, NULL_ID, NULL_ID ); if (i + 1 < exprs.size()) { var commaId = ir.getSymbolTable().addTmp(STRING, entry -> entry.getValue().setString(",")); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PRINT, commaId, NULL_ID, NULL_ID ); } } var newlineId = ir.getSymbolTable().addTmp(STRING, entry -> entry.getValue().setString(System.lineSeparator())); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PRINT, newlineId, NULL_ID, NULL_ID ); final int fileNumberId; if (fileNumber != null) { Types.assertNumeric(ir.getSymbolTable().get(fileNumber.result).getValue().getDataType(), () -> getCtxString(ctx)); fileNumberId = fileNumber.result; } else { fileNumberId = NULL_ID; } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.FLUSH, fileNumberId, NULL_ID, NULL_ID ); } @Override public void exitReadstmt(PuffinBasicParser.ReadstmtContext ctx) { for (var varCtx : ctx.variable()) { var varInstr = lookupInstruction(varCtx); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.READ, varInstr.result, NULL_ID, NULL_ID ); } } @Override public void exitRestorestmt(PuffinBasicParser.RestorestmtContext ctx) { ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RESTORE, NULL_ID, NULL_ID, NULL_ID ); } @Override public void exitDatastmt(PuffinBasicParser.DatastmtContext ctx) { var children = ctx.children; for (int i = 1; i < children.size(); i += 2) { var child = children.get(i); int valueId; if (child instanceof PuffinBasicParser.NumberContext) { valueId = lookupInstruction((PuffinBasicParser.NumberContext) child).result; } else { var text = unquote(child.getText()); valueId = ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString(text)); } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.DATA, valueId, NULL_ID, NULL_ID ); } } // GraphicsRuntime @Override public void exitScreenstmt(PuffinBasicParser.ScreenstmtContext ctx) { assertGraphics(); var title = lookupInstruction(ctx.expr(0)); var w = lookupInstruction(ctx.expr(1)); var h = lookupInstruction(ctx.expr(2)); var manualRepaint = ctx.mr != null; Types.assertString(ir.getSymbolTable().get(title.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(w.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(h.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.SCREEN0, w.result, h.result, NULL_ID ); var repaint = ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32( manualRepaint ? 0 : -1)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.SCREEN, title.result, repaint, NULL_ID ); } @Override public void exitRepaintstmt(PuffinBasicParser.RepaintstmtContext ctx) { assertGraphics(); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.REPAINT, NULL_ID, NULL_ID, NULL_ID ); } @Override public void exitCirclestmt(PuffinBasicParser.CirclestmtContext ctx) { assertGraphics(); var x = lookupInstruction(ctx.x); var y = lookupInstruction(ctx.y); var r1 = lookupInstruction(ctx.r1); var r2 = lookupInstruction(ctx.r2); var s = ctx.s != null ? lookupInstruction(ctx.s) : null; var e = ctx.e != null ? lookupInstruction(ctx.e) : null; var fill = ctx.fill != null ? lookupInstruction(ctx.fill) : null; Types.assertNumeric(ir.getSymbolTable().get(x.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(r1.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(r2.result).getValue().getDataType(), () -> getCtxString(ctx)); if (s != null) { Types.assertNumeric(ir.getSymbolTable().get(s.result).getValue().getDataType(), () -> getCtxString(ctx)); } if (e != null) { Types.assertNumeric(ir.getSymbolTable().get(e.result).getValue().getDataType(), () -> getCtxString(ctx)); } if (fill != null) { Types.assertString(ir.getSymbolTable().get(fill.result).getValue().getDataType(), () -> getCtxString(ctx)); } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CIRCLE_XY, x.result, y.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CIRCLE_SE, s != null ? s.result : NULL_ID, e != null ? e.result : NULL_ID, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CIRCLE_FILL, fill != null ? fill.result : NULL_ID, NULL_ID, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CIRCLE, r1.result, r2.result, NULL_ID ); } @Override public void exitLinestmt(PuffinBasicParser.LinestmtContext ctx) { assertGraphics(); var x1 = lookupInstruction(ctx.x1); var y1 = lookupInstruction(ctx.y1); var x2 = lookupInstruction(ctx.x2); var y2 = lookupInstruction(ctx.y2); Types.assertNumeric(ir.getSymbolTable().get(x1.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y1.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(x2.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y2.result).getValue().getDataType(), () -> getCtxString(ctx)); Instruction bf = null; if (ctx.bf != null){ bf = lookupInstruction(ctx.bf); Types.assertString(ir.getSymbolTable().get(bf.result).getValue().getDataType(), () -> getCtxString(ctx)); } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LINE_x1y1, x1.result, y1.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LINE_x2y2, x2.result, y2.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LINE, bf != null ? bf.result : NULL_ID, NULL_ID, NULL_ID ); } @Override public void exitColorstmt(PuffinBasicParser.ColorstmtContext ctx) { var r = lookupInstruction(ctx.r); var g = lookupInstruction(ctx.g); var b = lookupInstruction(ctx.b); Types.assertNumeric(ir.getSymbolTable().get(r.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(g.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(b.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.COLOR_RG, r.result, g.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.COLOR, b.result, NULL_ID, NULL_ID ); } @Override public void exitPaintstmt(PuffinBasicParser.PaintstmtContext ctx) { assertGraphics(); var x = lookupInstruction(ctx.x); var y = lookupInstruction(ctx.y); var r = lookupInstruction(ctx.r); var g = lookupInstruction(ctx.g); var b = lookupInstruction(ctx.b); Types.assertNumeric(ir.getSymbolTable().get(x.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(r.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(g.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(b.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PAINT_RG, r.result, g.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PAINT_B, b.result, NULL_ID, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PAINT, x.result, y.result, NULL_ID ); } @Override public void exitPsetstmt(PuffinBasicParser.PsetstmtContext ctx) { assertGraphics(); var x = lookupInstruction(ctx.x); var y = lookupInstruction(ctx.y); int rId = NULL_ID, gId = NULL_ID, bId = NULL_ID; if (ctx.r != null) { rId = lookupInstruction(ctx.r).result; Types.assertNumeric(ir.getSymbolTable().get(rId).getValue().getDataType(), () -> getCtxString(ctx)); } if (ctx.g != null) { gId = lookupInstruction(ctx.g).result; Types.assertNumeric(ir.getSymbolTable().get(gId).getValue().getDataType(), () -> getCtxString(ctx)); } if (ctx.b != null) { bId = lookupInstruction(ctx.b).result; Types.assertNumeric(ir.getSymbolTable().get(bId).getValue().getDataType(), () -> getCtxString(ctx)); } Types.assertNumeric(ir.getSymbolTable().get(x.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PSET_RG, rId, gId, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PSET_B, bId, NULL_ID, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PSET, x.result, y.result, NULL_ID ); } @Override public void exitGraphicsgetstmt(PuffinBasicParser.GraphicsgetstmtContext ctx) { assertGraphics(); var x1 = lookupInstruction(ctx.x1); var y1 = lookupInstruction(ctx.y1); var x2 = lookupInstruction(ctx.x2); var y2 = lookupInstruction(ctx.y2); var varInstr = lookupInstruction(ctx.variable()); Types.assertNumeric(ir.getSymbolTable().get(x1.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y1.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(x2.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y2.result).getValue().getDataType(), () -> getCtxString(ctx)); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); assertVariableDefined(((STVariable) ir.getSymbolTable().get(varInstr.result)).getVariable().getVariableName(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GGET_X1Y1, x1.result, y1.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GGET_X2Y2, x2.result, y2.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GGET, varInstr.result, NULL_ID, NULL_ID ); } @Override public void exitGraphicsputstmt(PuffinBasicParser.GraphicsputstmtContext ctx) { assertGraphics(); var x = lookupInstruction(ctx.x); var y = lookupInstruction(ctx.y); var varInstr = lookupInstruction(ctx.variable()); var action = ctx.action != null ? lookupInstruction(ctx.action) : null; Types.assertNumeric(ir.getSymbolTable().get(x.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y.result).getValue().getDataType(), () -> getCtxString(ctx)); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); assertVariableDefined(((STVariable) ir.getSymbolTable().get(varInstr.result)).getVariable().getVariableName(), () -> getCtxString(ctx)); if (action != null) { Types.assertString(ir.getSymbolTable().get(action.result).getValue().getDataType(), () -> getCtxString(ctx)); } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GPUT_XY, x.result, y.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GPUT, action != null ? action.result : NULL_ID, varInstr.result, NULL_ID ); } @Override public void exitDrawstmt(PuffinBasicParser.DrawstmtContext ctx) { assertGraphics(); var str = lookupInstruction(ctx.expr()); Types.assertString(ir.getSymbolTable().get(str.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.DRAW, str.result, NULL_ID, NULL_ID ); } @Override public void exitFontstmt(PuffinBasicParser.FontstmtContext ctx) { assertGraphics(); var name = lookupInstruction(ctx.name); var style = lookupInstruction(ctx.style); var size = lookupInstruction(ctx.size); Types.assertString(ir.getSymbolTable().get(style.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(size.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertString(ir.getSymbolTable().get(name.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.FONT_SS, style.result, size.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.FONT, name.result, NULL_ID, NULL_ID ); } @Override public void exitDrawstrstmt(PuffinBasicParser.DrawstrstmtContext ctx) { var str = lookupInstruction(ctx.str); var x = lookupInstruction(ctx.x); var y = lookupInstruction(ctx.y); Types.assertNumeric(ir.getSymbolTable().get(x.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertString(ir.getSymbolTable().get(str.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.DRAWSTR_XY, x.result, y.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.DRAWSTR, str.result, NULL_ID, NULL_ID ); } @Override public void exitLoadimgstmt(PuffinBasicParser.LoadimgstmtContext ctx) { assertGraphics(); var path = lookupInstruction(ctx.path); var varInstr = lookupInstruction(ctx.variable()); Types.assertString(ir.getSymbolTable().get(path.result).getValue().getDataType(), () -> getCtxString(ctx)); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); assertVariableDefined(((STVariable) ir.getSymbolTable().get(varInstr.result)).getVariable().getVariableName(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LOADIMG, path.result, varInstr.result, NULL_ID ); } @Override public void exitClsstmt(PuffinBasicParser.ClsstmtContext ctx) { assertGraphics(); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CLS, NULL_ID, NULL_ID, NULL_ID ); } @Override public void exitSleepstmt(PuffinBasicParser.SleepstmtContext ctx) { var millis = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(millis.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.SLEEP, millis.result, NULL_ID, NULL_ID ); } @Override public void exitBeepstmt(PuffinBasicParser.BeepstmtContext ctx) { assertGraphics(); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.BEEP, NULL_ID, NULL_ID, NULL_ID ); } private void assertGraphics() { if (!graphics) { throw new PuffinBasicInternalError( "GraphicsRuntime is not enabled!" ); } } private void handleDefTypeStmt( List<TerminalNode> letterRanges, PuffinBasicDataType dataType) { List<Character> defs = new ArrayList<>(); letterRanges.stream().map(ParseTree::getText).forEach(lr -> { for (char i = lr.charAt(0); i <= lr.charAt(2); i++) { defs.add(i); } }); defs.forEach(def -> ir.getSymbolTable().setDefaultDataType(def, dataType)); } private static FileOpenMode getFileOpenMode(PuffinBasicParser.Filemode1Context filemode1) { var mode = filemode1 != null ? unquote(filemode1.getText()) : null; if (mode == null || mode.equalsIgnoreCase("r")) { return FileOpenMode.RANDOM; } else if (mode.equalsIgnoreCase("i")) { return FileOpenMode.INPUT; } else if (mode.equalsIgnoreCase("o")) { return FileOpenMode.OUTPUT; } else { return FileOpenMode.APPEND; } } private static FileOpenMode getFileOpenMode(PuffinBasicParser.Filemode2Context filemode2) { if (filemode2 == null || filemode2.RANDOM() != null) { return FileOpenMode.RANDOM; } else if (filemode2.INPUT() != null) { return FileOpenMode.INPUT; } else if (filemode2.OUTPUT() != null) { return FileOpenMode.OUTPUT; } else { return FileOpenMode.APPEND; } } private static FileAccessMode getFileAccessMode(PuffinBasicParser.AccessContext access) { if (access == null || (access.READ() != null && access.WRITE() != null)) { return FileAccessMode.READ_WRITE; } else if (access.READ() != null) { return FileAccessMode.READ_ONLY; } else { return FileAccessMode.WRITE_ONLY; } } private static LockMode getLockMode(PuffinBasicParser.LockContext lock) { if (lock == null) { return LockMode.DEFAULT; } else if (lock.SHARED() != null) { return LockMode.SHARED; } else if (lock.READ() != null && lock.WRITE() != null) { return LockMode.READ_WRITE; } else if (lock.READ() != null) { return LockMode.READ; } else { return LockMode.WRITE; } } private int getGotoLineNumberOp1(int lineNumber) { return ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(lineNumber)); } private void checkDataTypeMatch(int id1, int id2, Supplier<String> lineSupplier) { checkDataTypeMatch(ir.getSymbolTable().get(id1).getValue(), id2, lineSupplier); } private void checkDataTypeMatch(STObjects.STValue entry1, int id2, Supplier<String> lineSupplier) { var entry2 = ir.getSymbolTable().get(id2).getValue(); if ((entry1.getDataType() == STRING && entry2.getDataType() != STRING) || (entry1.getDataType() != STRING && entry2.getDataType() == STRING)) { throw new PuffinBasicSemanticError( DATA_TYPE_MISMATCH, lineSupplier.get(), "Data type " + entry1.getDataType() + " mismatches with " + entry2.getDataType() ); } } private static final class UDFState { public Instruction gotoPostFuncDecl; public Instruction labelFuncStart; } private static final class WhileLoopState { public Instruction labelBeforeWhile; public Instruction gotoAfterWend; } private static final class ForLoopState { public Variable variable; public Instruction labelApplyStep; public Instruction gotoAfterNext; } private static final class IfState { public Instruction gotoIfConditionTrue; public Instruction gotoIfConditionFalse; public Instruction gotoFromThenAfterIf; public Instruction labelBeforeThen; public Instruction labelAfterThen; public Instruction labelBeforeElse; public Instruction labelAfterElse; } }
UTF-8
Java
134,794
java
PuffinBasicIRListener.java
Java
[]
null
[]
package org.puffinbasic.parser; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import it.unimi.dsi.fastutil.objects.ObjectSet; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.misc.Interval; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeProperty; import org.antlr.v4.runtime.tree.TerminalNode; import org.jetbrains.annotations.Nullable; import org.puffinbasic.antlr4.PuffinBasicBaseListener; import org.puffinbasic.antlr4.PuffinBasicParser; import org.puffinbasic.antlr4.PuffinBasicParser.VariableContext; import org.puffinbasic.domain.STObjects; import org.puffinbasic.domain.STObjects.PuffinBasicDataType; import org.puffinbasic.domain.STObjects.STKind; import org.puffinbasic.domain.STObjects.STUDF; import org.puffinbasic.domain.STObjects.STVariable; import org.puffinbasic.domain.Variable; import org.puffinbasic.domain.Variable.VariableName; import org.puffinbasic.error.PuffinBasicInternalError; import org.puffinbasic.error.PuffinBasicSemanticError; import org.puffinbasic.file.PuffinBasicFile.FileAccessMode; import org.puffinbasic.file.PuffinBasicFile.FileOpenMode; import org.puffinbasic.file.PuffinBasicFile.LockMode; import org.puffinbasic.parser.PuffinBasicIR.Instruction; import org.puffinbasic.parser.PuffinBasicIR.OpCode; import org.puffinbasic.runtime.Numbers; import org.puffinbasic.runtime.Types; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.stream.Collectors; import static org.puffinbasic.domain.PuffinBasicSymbolTable.NULL_ID; import static org.puffinbasic.domain.STObjects.PuffinBasicDataType.DOUBLE; import static org.puffinbasic.domain.STObjects.PuffinBasicDataType.FLOAT; import static org.puffinbasic.domain.STObjects.PuffinBasicDataType.INT32; import static org.puffinbasic.domain.STObjects.PuffinBasicDataType.INT64; import static org.puffinbasic.domain.STObjects.PuffinBasicDataType.STRING; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.BAD_ARGUMENT; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.BAD_ASSIGNMENT; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.DATA_TYPE_MISMATCH; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.FOR_WITHOUT_NEXT; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.INSUFFICIENT_UDF_ARGS; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.NEXT_WITHOUT_FOR; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.NOT_DEFINED; import static org.puffinbasic.error.PuffinBasicSemanticError.ErrorCode.WHILE_WITHOUT_WEND; import static org.puffinbasic.file.PuffinBasicFile.DEFAULT_RECORD_LEN; import static org.puffinbasic.parser.LinenumberListener.parseLinenum; import static org.puffinbasic.runtime.Types.assertNumeric; import static org.puffinbasic.runtime.Types.unquote; /** * <PRE> * Functions * ========= * ABS done * ASC done * ATN done * CDBL done * CHR$ done * CINT done * CLNG done * COS done * CSNG done * CVD done * CVI done * CVI done * CVL done * CVS done * ENVIRON$ NA * EOF done * EXP done * EXTERR NA * FIX done * FRE NA * HEX$ done * INP NA * INPUT$ done * INSTR done * INT done * IOCTL$ NA * LEFT$ done * LEN done * LOC done * LOF done * LOG done * LPOS NA * MID$ done * MKD$ done * MKI$ done * MKS$ done * MKL$ done * OCT$ done * PEEK NA * RND done * RIGHT$ done * SGN done * SIN done * SPACE$ done * SPC NA * SQR done * STR$ done * STRING$ done * TAB NA * TAN done * TIMER done * VAL done * VARPTR NA * VARPTR$ NA * * PEN NA * PLAY graphics * PMAP graphics * POINT graphics * POS graphics * SCREEN NA * STICK NA * * Statements * ========== * CALL NA * CHAIN NA * CLOSE done * CLS NA * COM(n) NA * COMMON NA * DATA done * DATE$ done * DEF FN done * DEFINT done * DEFDBL done * DEFLNG done * DEFSNG done * DEFSTR done * DEF SEG NA * DEF USR NA * DIM done * END done * ENVIRON NA * ERASE NA * ERROR NA * FIELD done * FOR-NEXT done * GET done * GOSUB-RETURN done * GOTO done * IF-THEN-ELSE done * INPUT done (not compatible) * INPUT# done * IOCTL NA * LET done * LINE INPUT done * LINE INPUT# done * LOCK NA * LPRINT NA * LPRINT USING NA * LSET done * MID$ done * ON ERROR GOTO NA * ON-GOSUB NA * ON-GOTO NA * OPEN done * OPEN COM(n) NA * OPTION BASE NA * OUT NA * ON COM(n) NA * PRINT done * PRINT USING done * PRINT# done * PRINT# USING done * PUT done * RANDOMIZE done * READ done * REM done * RESTORE done * RESUME NA * RSET done * SHELL NA * STOP NA * SWAP done * TIME$ done * UNLOCK NA * WAIT NA * WHILE-WEND done * WIDTH NA * WRITE done * WRTIE# done * * SCREEN done * CIRCLE done * COLOR done * LINE done * PAINT done * DRAW graphics * LOCATE graphics * BEEP NA * KEY NA * KEY(n) NA * ON KEY(n) NA * ON PEN(n) NA * ON PLAY(n) NA * ON STRIG(n) NA * ON TIMER(n) NA * PALETTE NA * PALETTE USING NA * PEN NA * PLAY graphics * PSET graphics * POKE NA * PRESET NA * STRIG NA * STRIG(n) NA * VIEW NA * VIEW PRINT NA * WINDOW NA * </PRE> */ public class PuffinBasicIRListener extends PuffinBasicBaseListener { private enum NumericOrString { NUMERIC, STRING } private final CharStream in; private final PuffinBasicIR ir; private final boolean graphics; private final ParseTreeProperty<Instruction> nodeToInstruction; private final Object2ObjectMap<Variable, UDFState> udfStateMap; private final LinkedList<WhileLoopState> whileLoopStateList; private final LinkedList<ForLoopState> forLoopStateList; private final ParseTreeProperty<IfState> nodeToIfState; private int currentLineNumber; private final ObjectSet<VariableName> varDefined; public PuffinBasicIRListener(CharStream in, PuffinBasicIR ir, boolean graphics) { this.in = in; this.ir = ir; this.graphics = graphics; this.nodeToInstruction = new ParseTreeProperty<>(); this.udfStateMap = new Object2ObjectOpenHashMap<>(); this.whileLoopStateList = new LinkedList<>(); this.forLoopStateList = new LinkedList<>(); this.nodeToIfState = new ParseTreeProperty<>(); this.varDefined = new ObjectOpenHashSet<>(); } public void semanticCheckAfterParsing() { if (!whileLoopStateList.isEmpty()) { throw new PuffinBasicSemanticError( WHILE_WITHOUT_WEND, "<UNKNOWN LINE>", "WHILE without WEND" ); } if (!forLoopStateList.isEmpty()) { throw new PuffinBasicSemanticError( FOR_WITHOUT_NEXT, "<UNKNOWN LINE>", "FOR without NEXT" ); } } private String getCtxString(ParserRuleContext ctx) { return in.getText(new Interval( ctx.start.getStartIndex(), ctx.stop.getStopIndex() )); } private Instruction lookupInstruction(ParserRuleContext ctx) { var exprInstruction = nodeToInstruction.get(ctx); if (exprInstruction == null) { throw new PuffinBasicInternalError( "Failed to find instruction for node: " + ctx.getText() ); } return exprInstruction; } @Override public void enterLine(PuffinBasicParser.LineContext ctx) { this.currentLineNumber = parseLinenum(ctx.linenum().DECIMAL().getText()); } // // Variable, Number, etc. // @Override public void exitNumber(PuffinBasicParser.NumberContext ctx) { final int id; if (ctx.integer() != null) { final boolean isLong = ctx.integer().AT() != null; final boolean isDouble = ctx.integer().HASH() != null; final boolean isFloat = ctx.integer().EXCLAMATION() != null; final String strValue; final int base; if (ctx.integer().HEXADECIMAL() != null) { strValue = ctx.integer().HEXADECIMAL().getText().substring(2); base = 16; } else if (ctx.integer().OCTAL() != null) { var octalStr = ctx.integer().OCTAL().getText(); strValue = (octalStr.startsWith("&O") ? octalStr.substring(2) : octalStr.substring(1)); base = 8; } else { strValue = ctx.integer().DECIMAL().getText(); base = 10; } if (isLong || isDouble) { long parsed = Numbers.parseInt64(strValue, base, () -> getCtxString(ctx)); id = ir.getSymbolTable().addTmp(isLong ? INT64 : DOUBLE, entry -> entry.getValue().setInt64(parsed)); } else { id = ir.getSymbolTable().addTmp(isFloat ? FLOAT : INT32, entry -> entry.getValue().setInt32(Numbers.parseInt32(strValue, base, () -> getCtxString(ctx)))); } } else if (ctx.FLOAT() != null) { var floatStr = ctx.FLOAT().getText(); if (floatStr.endsWith("!")) { floatStr = floatStr.substring(0, floatStr.length() - 1); } var floatValue = Numbers.parseFloat32(floatStr, () -> getCtxString(ctx)); id = ir.getSymbolTable().addTmp(FLOAT, entry -> entry.getValue().setFloat32(floatValue)); } else { var doubleStr = ctx.DOUBLE().getText(); if (doubleStr.endsWith("#")) { doubleStr = doubleStr.substring(0, doubleStr.length() - 1); } var doubleValue = Numbers.parseFloat64(doubleStr, () -> getCtxString(ctx)); id = ir.getSymbolTable().addTmp(DOUBLE, entry -> entry.getValue().setFloat64(doubleValue)); } var instr = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.VALUE, id, NULL_ID, id ); nodeToInstruction.put(ctx, instr); } @Override public void exitVariable(VariableContext ctx) { var varname = ctx.varname().VARNAME().getText(); var varsuffix = ctx.varsuffix() != null ? ctx.varsuffix().getText() : null; var dataType = ir.getSymbolTable().getDataTypeFor(varname, varsuffix); var variableName = new VariableName(varname, dataType); var idHolder = new AtomicInteger(); ir.getSymbolTable() .addVariableOrUDF( variableName, variableName1 -> Variable.of(variableName1, false, () -> getCtxString(ctx)), (varId, varEntry) -> { var variable = varEntry.getVariable(); idHolder.set(varId); if (variable.isScalar()) { // Scalar if (!ctx.expr().isEmpty()) { throw new PuffinBasicSemanticError( PuffinBasicSemanticError.ErrorCode.SCALAR_VARIABLE_CANNOT_BE_INDEXED, getCtxString(ctx), "Scalar variable cannot be indexed: " + variable); } } else if (variable.isArray()) { if (!ctx.expr().isEmpty()) { // Array ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RESET_ARRAY_IDX, varId, NULL_ID, NULL_ID); for (var exprCtx : ctx.expr()) { var exprInstr = lookupInstruction(exprCtx); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.SET_ARRAY_IDX, varId, exprInstr.result, NULL_ID); } var refId = ir.getSymbolTable().addArrayReference(varEntry); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAYREF, varId, refId, refId); idHolder.set(refId); } } else if (variable.isUDF()) { // UDF var udfEntry = (STUDF) varEntry; var udfState = udfStateMap.get(variable); // Create & Push Runtime scope var pushScopeInstr = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PUSH_RT_SCOPE, varId, NULL_ID, NULL_ID); // Copy caller params to Runtime scope if (ctx.expr().size() != udfEntry.getNumDeclaredParams()) { throw new PuffinBasicSemanticError( INSUFFICIENT_UDF_ARGS, getCtxString(ctx), variable + " expects " + udfEntry.getNumDeclaredParams() + ", #args passed: " + ctx.expr().size()); } int i = 0; for (var exprCtx : ctx.expr()) { var exprInstr = lookupInstruction(exprCtx); var declParamId = udfEntry.getDeclaraedParam(i++); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.COPY, declParamId, exprInstr.result, declParamId); } // GOTO labelFuncStart ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL, udfState.labelFuncStart.op1, NULL_ID, NULL_ID); // LABEL caller return address var labelCallerReturn = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID); // Patch address of the caller pushScopeInstr.patchOp2(labelCallerReturn.op1); // Pop Runtime scope ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.POP_RT_SCOPE, varId, NULL_ID, NULL_ID); } }); var refId = idHolder.get(); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.VARIABLE, refId, NULL_ID, refId )); } // // Expr // private void copyAndRegisterExprResult(ParserRuleContext ctx, Instruction instruction, boolean shouldCopy) { if (shouldCopy) { var copy = ir.getSymbolTable().addTmpCompatibleWith(instruction.result); instruction = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.COPY, copy, instruction.result, copy ); } nodeToInstruction.put(ctx, instruction); } @Override public void exitExprVariable(PuffinBasicParser.ExprVariableContext ctx) { var instruction = nodeToInstruction.get(ctx.variable()); var varEntry = ir.getSymbolTable().get(instruction.result); boolean copy = (varEntry instanceof STVariable) && ((STVariable) varEntry).getVariable().isUDF(); if (ctx.MINUS() != null) { if (ir.getSymbolTable().get(instruction.result).getValue().getDataType() == STRING) { throw new PuffinBasicSemanticError( DATA_TYPE_MISMATCH, getCtxString(ctx), "Unary minus cannot be used with a String!" ); } instruction = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.UNARY_MINUS, instruction.result, NULL_ID, ir.getSymbolTable().addTmpCompatibleWith(instruction.result) ); copy = true; } copyAndRegisterExprResult(ctx, instruction, copy); } @Override public void exitExprParen(PuffinBasicParser.ExprParenContext ctx) { nodeToInstruction.put(ctx, lookupInstruction(ctx.expr())); } @Override public void exitExprNumber(PuffinBasicParser.ExprNumberContext ctx) { var instruction = nodeToInstruction.get(ctx.number()); if (ctx.MINUS() != null) { instruction = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.UNARY_MINUS, instruction.result, NULL_ID, ir.getSymbolTable().addTmpCompatibleWith(instruction.result) ); } copyAndRegisterExprResult(ctx, instruction, false); } @Override public void exitExprFunc(PuffinBasicParser.ExprFuncContext ctx) { var instruction = nodeToInstruction.get(ctx.func()); if (ctx.MINUS() != null) { instruction = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.UNARY_MINUS, instruction.result, NULL_ID, ir.getSymbolTable().addTmpCompatibleWith(instruction.result) ); } copyAndRegisterExprResult(ctx, instruction, false); } @Override public void exitExprString(PuffinBasicParser.ExprStringContext ctx) { var text = unquote(ctx.string().STRING().getText()); var id = ir.getSymbolTable().addTmp(STRING, entry -> entry.getValue().setString(text)); copyAndRegisterExprResult(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.VALUE, id, NULL_ID, id ), false); } @Override public void exitExprExp(PuffinBasicParser.ExprExpContext ctx) { addArithmeticOpExpr(ctx, OpCode.EXP, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprMul(PuffinBasicParser.ExprMulContext ctx) { addArithmeticOpExpr(ctx, OpCode.MUL, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprIntDiv(PuffinBasicParser.ExprIntDivContext ctx) { addArithmeticOpExpr(ctx, OpCode.IDIV, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprFloatDiv(PuffinBasicParser.ExprFloatDivContext ctx) { addArithmeticOpExpr(ctx, OpCode.FDIV, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprMod(PuffinBasicParser.ExprModContext ctx) { addArithmeticOpExpr(ctx, OpCode.MOD, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprPlus(PuffinBasicParser.ExprPlusContext ctx) { var expr1 = ctx.expr(0); var expr2 = ctx.expr(1); int instr1res = lookupInstruction(expr1).result; int instr2res = lookupInstruction(expr2).result; var dt1 = ir.getSymbolTable().get(instr1res).getValue().getDataType(); var dt2 = ir.getSymbolTable().get(instr2res).getValue().getDataType(); if (dt1 == STRING && dt2 == STRING) { nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CONCAT, instr1res, instr2res, ir.getSymbolTable().addTmp(STRING, e -> {}) )); } else { addArithmeticOpExpr(ctx, OpCode.ADD, expr1, expr2); } } @Override public void exitExprMinus(PuffinBasicParser.ExprMinusContext ctx) { addArithmeticOpExpr(ctx, OpCode.SUB, ctx.expr(0), ctx.expr(1)); } private void addArithmeticOpExpr( ParserRuleContext parent, OpCode opCode, PuffinBasicParser.ExprContext exprLeft, PuffinBasicParser.ExprContext exprRight) { var exprL = lookupInstruction(exprLeft); var exprR = lookupInstruction(exprRight); var dt1 = ir.getSymbolTable().get(exprL.result).getValue().getDataType(); var dt2 = ir.getSymbolTable().get(exprR.result).getValue().getDataType(); Types.assertNumeric(dt1, dt2, () -> getCtxString(parent)); var result = ir.getSymbolTable().addTmp( Types.upcast(dt1, ir.getSymbolTable().get(exprR.result).getValue().getDataType(), () -> getCtxString(parent)), e -> {}); nodeToInstruction.put(parent, ir.addInstruction( currentLineNumber, parent.start.getStartIndex(), parent.stop.getStopIndex(), opCode, exprL.result, exprR.result, result )); } @Override public void exitExprRelEq(PuffinBasicParser.ExprRelEqContext ctx) { addRelationalOpExpr(ctx, OpCode.EQ, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprRelNeq(PuffinBasicParser.ExprRelNeqContext ctx) { addRelationalOpExpr(ctx, OpCode.NE, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprRelLt(PuffinBasicParser.ExprRelLtContext ctx) { addRelationalOpExpr(ctx, OpCode.LT, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprRelLe(PuffinBasicParser.ExprRelLeContext ctx) { addRelationalOpExpr(ctx, OpCode.LE, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprRelGt(PuffinBasicParser.ExprRelGtContext ctx) { addRelationalOpExpr(ctx, OpCode.GT, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprRelGe(PuffinBasicParser.ExprRelGeContext ctx) { addRelationalOpExpr(ctx, OpCode.GE, ctx.expr(0), ctx.expr(1)); } private void addRelationalOpExpr( ParserRuleContext parent, OpCode opCode, PuffinBasicParser.ExprContext exprLeft, PuffinBasicParser.ExprContext exprRight) { var exprL = lookupInstruction(exprLeft); var exprR = lookupInstruction(exprRight); checkDataTypeMatch(exprL.result, exprR.result, () -> getCtxString(parent)); var result = ir.getSymbolTable().addTmp(INT64, e -> {}); nodeToInstruction.put(parent, ir.addInstruction( currentLineNumber, parent.start.getStartIndex(), parent.stop.getStopIndex(), opCode, exprL.result, exprR.result, result )); } @Override public void exitExprLogNot(PuffinBasicParser.ExprLogNotContext ctx) { var expr = lookupInstruction(ctx.expr()); Types.assertNumeric( ir.getSymbolTable().get(expr.result).getValue().getDataType(), () -> getCtxString(ctx) ); var result = ir.getSymbolTable().addTmp(INT64, e -> {}); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.NOT, expr.result, NULL_ID, result )); } @Override public void exitExprLogAnd(PuffinBasicParser.ExprLogAndContext ctx) { addLogicalOpExpr(ctx, OpCode.AND, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprLogOr(PuffinBasicParser.ExprLogOrContext ctx) { addLogicalOpExpr(ctx, OpCode.OR, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprLogXor(PuffinBasicParser.ExprLogXorContext ctx) { addLogicalOpExpr(ctx, OpCode.XOR, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprLogEqv(PuffinBasicParser.ExprLogEqvContext ctx) { addLogicalOpExpr(ctx, OpCode.EQV, ctx.expr(0), ctx.expr(1)); } @Override public void exitExprLogImp(PuffinBasicParser.ExprLogImpContext ctx) { addLogicalOpExpr(ctx, OpCode.IMP, ctx.expr(0), ctx.expr(1)); } private void addLogicalOpExpr( ParserRuleContext parent, OpCode opCode, PuffinBasicParser.ExprContext exprLeft, PuffinBasicParser.ExprContext exprRight) { var exprL = lookupInstruction(exprLeft); var exprR = lookupInstruction(exprRight); Types.assertNumeric( ir.getSymbolTable().get(exprL.result).getValue().getDataType(), ir.getSymbolTable().get(exprR.result).getValue().getDataType(), () -> getCtxString(parent) ); var result = ir.getSymbolTable().addTmp(INT64, e -> {}); nodeToInstruction.put(parent, ir.addInstruction( currentLineNumber, parent.start.getStartIndex(), parent.stop.getStopIndex(), opCode, exprL.result, exprR.result, result )); } // // Functions // @Override public void exitFuncAbs(PuffinBasicParser.FuncAbsContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.ABS, ctx, ctx.expr(), NumericOrString.NUMERIC)); } @Override public void exitFuncAsc(PuffinBasicParser.FuncAscContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.ASC, ctx, ctx.expr(), NumericOrString.STRING, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncSin(PuffinBasicParser.FuncSinContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.SIN, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncCos(PuffinBasicParser.FuncCosContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.COS, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncTan(PuffinBasicParser.FuncTanContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.TAN, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncASin(PuffinBasicParser.FuncASinContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.ASIN, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncACos(PuffinBasicParser.FuncACosContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.ACOS, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncAtn(PuffinBasicParser.FuncAtnContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.ATN, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncSinh(PuffinBasicParser.FuncSinhContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.SINH, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncCosh(PuffinBasicParser.FuncCoshContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.COSH, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncTanh(PuffinBasicParser.FuncTanhContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.TANH, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncExp(PuffinBasicParser.FuncExpContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.EEXP, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncLog10(PuffinBasicParser.FuncLog10Context ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.LOG10, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncToRad(PuffinBasicParser.FuncToRadContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.TORAD, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncToDeg(PuffinBasicParser.FuncToDegContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.TODEG, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncFloor(PuffinBasicParser.FuncFloorContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.FLOOR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncCeil(PuffinBasicParser.FuncCeilContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CEIL, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncRound(PuffinBasicParser.FuncRoundContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.ROUND, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncSqr(PuffinBasicParser.FuncSqrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.SQR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncCint(PuffinBasicParser.FuncCintContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CINT, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncClng(PuffinBasicParser.FuncClngContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CLNG, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(INT64, c -> {}))); } @Override public void exitFuncCsng(PuffinBasicParser.FuncCsngContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CSNG, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(FLOAT, c -> {}))); } @Override public void exitFuncCdbl(PuffinBasicParser.FuncCdblContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CDBL, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncCvi(PuffinBasicParser.FuncCviContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CVI, ctx, ctx.expr(), NumericOrString.STRING, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncCvl(PuffinBasicParser.FuncCvlContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CVL, ctx, ctx.expr(), NumericOrString.STRING, ir.getSymbolTable().addTmp(INT64, c -> {}))); } @Override public void exitFuncCvs(PuffinBasicParser.FuncCvsContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CVS, ctx, ctx.expr(), NumericOrString.STRING, ir.getSymbolTable().addTmp(FLOAT, c -> {}))); } @Override public void exitFuncCvd(PuffinBasicParser.FuncCvdContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CVD, ctx, ctx.expr(), NumericOrString.STRING, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncMkiDlr(PuffinBasicParser.FuncMkiDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.MKIDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncMklDlr(PuffinBasicParser.FuncMklDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.MKLDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncMksDlr(PuffinBasicParser.FuncMksDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.MKSDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncMkdDlr(PuffinBasicParser.FuncMkdDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.MKDDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncSpaceDlr(PuffinBasicParser.FuncSpaceDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.SPACEDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncStrDlr(PuffinBasicParser.FuncStrDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.STRDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncVal(PuffinBasicParser.FuncValContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.VAL , ctx, ctx.expr(), NumericOrString.STRING, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncInt(PuffinBasicParser.FuncIntContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.INT, ctx, ctx.expr(), NumericOrString.NUMERIC)); } @Override public void exitFuncFix(PuffinBasicParser.FuncFixContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.FIX, ctx, ctx.expr(), NumericOrString.NUMERIC)); } @Override public void exitFuncLog(PuffinBasicParser.FuncLogContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.LOG, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncLen(PuffinBasicParser.FuncLenContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.LEN, ctx, ctx.expr(), NumericOrString.STRING, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncChrDlr(PuffinBasicParser.FuncChrDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.CHRDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncHexDlr(PuffinBasicParser.FuncHexDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.HEXDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncOctDlr(PuffinBasicParser.FuncOctDlrContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.OCTDLR, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncLeftDlr(PuffinBasicParser.FuncLeftDlrContext ctx) { var xdlr = lookupInstruction(ctx.expr(0)); var n = lookupInstruction(ctx.expr(1)); Types.assertString(ir.getSymbolTable().get(xdlr.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(n.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LEFTDLR, xdlr.result, n.result, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncRightDlr(PuffinBasicParser.FuncRightDlrContext ctx) { var xdlr = lookupInstruction(ctx.expr(0)); var n = lookupInstruction(ctx.expr(1)); Types.assertString(ir.getSymbolTable().get(xdlr.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(n.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RIGHTDLR, xdlr.result, n.result, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncInstr(PuffinBasicParser.FuncInstrContext ctx) { int xdlr, ydlr, n; if (ctx.expr().size() == 3) { // n, x$, y$ n = lookupInstruction(ctx.expr(0)).result; xdlr = lookupInstruction(ctx.expr(1)).result; ydlr = lookupInstruction(ctx.expr(2)).result; Types.assertNumeric(ir.getSymbolTable().get(n).getValue().getDataType(), () -> getCtxString(ctx)); } else { // x$, y$ n = ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(1)); xdlr = lookupInstruction(ctx.expr(0)).result; ydlr = lookupInstruction(ctx.expr(1)).result; } Types.assertString(ir.getSymbolTable().get(xdlr).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertString(ir.getSymbolTable().get(ydlr).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INSTR0, xdlr, ydlr, NULL_ID); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INSTR, n, NULL_ID, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncMidDlr(PuffinBasicParser.FuncMidDlrContext ctx) { int xdlr, n, m; if (ctx.expr().size() == 3) { // x$, n, m xdlr = lookupInstruction(ctx.expr(0)).result; n = lookupInstruction(ctx.expr(1)).result; m = lookupInstruction(ctx.expr(2)).result; Types.assertNumeric(ir.getSymbolTable().get(m).getValue().getDataType(), () -> getCtxString(ctx)); } else { // x$, n xdlr = lookupInstruction(ctx.expr(0)).result; n = lookupInstruction(ctx.expr(1)).result; m = ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(Integer.MAX_VALUE)); } Types.assertString(ir.getSymbolTable().get(xdlr).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(n).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.MIDDLR0, xdlr, n, NULL_ID); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.MIDDLR, m, NULL_ID, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncRnd(PuffinBasicParser.FuncRndContext ctx) { nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RND, NULL_ID, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncSgn(PuffinBasicParser.FuncSgnContext ctx) { nodeToInstruction.put(ctx, addFuncWithExprInstruction(OpCode.SGN, ctx, ctx.expr(), NumericOrString.NUMERIC, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncTimer(PuffinBasicParser.FuncTimerContext ctx) { nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.TIMER, NULL_ID, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncStringDlr(PuffinBasicParser.FuncStringDlrContext ctx) { int n = lookupInstruction(ctx.expr(0)).result; int jOrxdlr = lookupInstruction(ctx.expr(1)).result; Types.assertNumeric(ir.getSymbolTable().get(n).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.STRINGDLR, n, jOrxdlr, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncLoc(PuffinBasicParser.FuncLocContext ctx) { var fileNumber = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(fileNumber.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LOC, fileNumber.result, NULL_ID, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncLof(PuffinBasicParser.FuncLofContext ctx) { var fileNumber = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(fileNumber.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LOF, fileNumber.result, NULL_ID, ir.getSymbolTable().addTmp(INT64, c -> {}))); } @Override public void exitFuncEof(PuffinBasicParser.FuncEofContext ctx) { var fileNumber = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(fileNumber.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.EOF, fileNumber.result, NULL_ID, ir.getSymbolTable().addTmp(INT32, c -> {}))); } @Override public void exitFuncEnvironDlr(PuffinBasicParser.FuncEnvironDlrContext ctx) { var expr = lookupInstruction(ctx.expr()); Types.assertString(ir.getSymbolTable().get(expr.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ENVIRONDLR, expr.result, NULL_ID, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncInputDlr(PuffinBasicParser.FuncInputDlrContext ctx) { var x = lookupInstruction(ctx.expr(0)); Types.assertNumeric(ir.getSymbolTable().get(x.result).getValue().getDataType(), () -> getCtxString(ctx)); int fileNumberId; if (ctx.expr().size() == 2) { var fileNumber = lookupInstruction(ctx.expr(1)); Types.assertNumeric(ir.getSymbolTable().get(fileNumber.result).getValue().getDataType(), () -> getCtxString(ctx)); fileNumberId = fileNumber.result; } else { fileNumberId = ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(-1)); } nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INPUTDLR, x.result, fileNumberId, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncInkeyDlr(PuffinBasicParser.FuncInkeyDlrContext ctx) { assertGraphics(); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INKEYDLR, NULL_ID, NULL_ID, ir.getSymbolTable().addTmp(STRING, c -> {}))); } @Override public void exitFuncE(PuffinBasicParser.FuncEContext ctx) { nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.E, NULL_ID, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncPI(PuffinBasicParser.FuncPIContext ctx) { nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PI, NULL_ID, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, c -> {}))); } @Override public void exitFuncMin(PuffinBasicParser.FuncMinContext ctx) { var expr1 = lookupInstruction(ctx.expr(0)); var expr2 = lookupInstruction(ctx.expr(1)); var dt1 = ir.getSymbolTable().get(expr1.result).getValue().getDataType(); var dt2 = ir.getSymbolTable().get(expr2.result).getValue().getDataType(); Types.assertNumeric(dt1, () -> getCtxString(ctx)); Types.assertNumeric(dt2, () -> getCtxString(ctx)); var resdt = Types.upcast(dt1, dt2, () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.MIN, expr1.result, expr2.result, ir.getSymbolTable().addTmp(resdt, e -> {}))); } @Override public void exitFuncMax(PuffinBasicParser.FuncMaxContext ctx) { var expr1 = lookupInstruction(ctx.expr(0)); var expr2 = lookupInstruction(ctx.expr(1)); var dt1 = ir.getSymbolTable().get(expr1.result).getValue().getDataType(); var dt2 = ir.getSymbolTable().get(expr2.result).getValue().getDataType(); Types.assertNumeric(dt1, () -> getCtxString(ctx)); Types.assertNumeric(dt2, () -> getCtxString(ctx)); var resdt = Types.upcast(dt1, dt2, () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.MAX, expr1.result, expr2.result, ir.getSymbolTable().addTmp(resdt, e -> {}))); } @Override public void exitFuncArrayNDFill(PuffinBasicParser.FuncArrayNDFillContext ctx) { var varInstr = getArrayNdVariableInstruction(ctx, ctx.variable()); var expr = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(expr.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAYFILL, varInstr.result, expr.result, ir.getSymbolTable().addTmp(INT32, e -> {}))); } private Instruction getArray1dVariableInstruction(ParserRuleContext ctx, VariableContext varCtx, boolean numeric) { var varInstr = lookupInstruction(varCtx); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); var varEntry = (STVariable) ir.getSymbolTable().get(varInstr.result); assertVariableDefined(varEntry.getVariable().getVariableName(), () -> getCtxString(ctx)); assert1DArray(varEntry, () -> getCtxString(ctx)); if (numeric) { assertNumeric(varEntry.getValue().getDataType(), () -> getCtxString(ctx)); } return varInstr; } private Instruction getArray2dVariableInstruction(ParserRuleContext ctx, VariableContext varCtx) { var varInstr = lookupInstruction(varCtx); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); var varEntry = (STVariable) ir.getSymbolTable().get(varInstr.result); assertVariableDefined(varEntry.getVariable().getVariableName(), () -> getCtxString(ctx)); assert2DArray(varEntry, () -> getCtxString(ctx)); return varInstr; } private Instruction getArrayNdVariableInstruction(ParserRuleContext ctx, VariableContext varCtx) { var varInstr = lookupInstruction(varCtx); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); var varEntry = (STVariable) ir.getSymbolTable().get(varInstr.result); assertVariableDefined(varEntry.getVariable().getVariableName(), () -> getCtxString(ctx)); assertNDArray(varEntry, () -> getCtxString(ctx)); return varInstr; } @Override public void exitFuncArray1DMean(PuffinBasicParser.FuncArray1DMeanContext ctx) { var var1Instr = getArray1dVariableInstruction(ctx, ctx.variable(), true); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DMEAN, var1Instr.result, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, e -> {}))); } @Override public void exitFuncArray1DStd(PuffinBasicParser.FuncArray1DStdContext ctx) { var var1Instr = getArray1dVariableInstruction(ctx, ctx.variable(), true); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DSTD, var1Instr.result, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, e -> {}))); } @Override public void exitFuncArray1DMedian(PuffinBasicParser.FuncArray1DMedianContext ctx) { var var1Instr = getArray1dVariableInstruction(ctx, ctx.variable(), true); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DMEDIAN, var1Instr.result, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, e -> {}))); } @Override public void exitFuncArray1DSort(PuffinBasicParser.FuncArray1DSortContext ctx) { var var1Instr = getArray1dVariableInstruction(ctx, ctx.variable(), false); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DSORT, var1Instr.result, NULL_ID, ir.getSymbolTable().addTmp(DOUBLE, e -> {}))); } @Override public void exitFuncArray1DBinSearch(PuffinBasicParser.FuncArray1DBinSearchContext ctx) { var var1Instr = getArray1dVariableInstruction(ctx, ctx.variable(), false); var expr = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(expr.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DBINSEARCH, var1Instr.result, expr.result, ir.getSymbolTable().addTmp(DOUBLE, e -> {}))); } @Override public void exitFuncArray1DPct(PuffinBasicParser.FuncArray1DPctContext ctx) { var var1Instr = getArray1dVariableInstruction(ctx, ctx.variable(), true); var expr = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(expr.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DPCT, var1Instr.result, expr.result, ir.getSymbolTable().addTmp(DOUBLE, e -> {}))); } @Override public void exitFuncArrayNDCopy(PuffinBasicParser.FuncArrayNDCopyContext ctx) { var var1Instr = getArrayNdVariableInstruction(ctx, ctx.variable(0)); var var2Instr = getArrayNdVariableInstruction(ctx, ctx.variable(1)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAYCOPY, var1Instr.result, var2Instr.result, ir.getSymbolTable().addTmp(INT32, e -> {}))); } @Override public void exitFuncArray1DCopy(PuffinBasicParser.FuncArray1DCopyContext ctx) { var var1Instr = getArray1dVariableInstruction(ctx, ctx.variable(0), false); var var2Instr = getArray1dVariableInstruction(ctx, ctx.variable(1), false); var src0 = lookupInstruction(ctx.src0); Types.assertNumeric(ir.getSymbolTable().get(src0.result).getValue().getDataType(), () -> getCtxString(ctx)); var dst0 = lookupInstruction(ctx.dst0); Types.assertNumeric(ir.getSymbolTable().get(dst0.result).getValue().getDataType(), () -> getCtxString(ctx)); var len = lookupInstruction(ctx.len); Types.assertNumeric(ir.getSymbolTable().get(len.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DCOPYSRC, var1Instr.result, src0.result, ir.getSymbolTable().addTmp(INT32, e -> {}))); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DCOPYDST, var2Instr.result, dst0.result, ir.getSymbolTable().addTmp(INT32, e -> {}))); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY1DCOPY, len.result, NULL_ID, ir.getSymbolTable().addTmp(INT32, e -> {}))); } @Override public void exitFuncArray2DShiftHor(PuffinBasicParser.FuncArray2DShiftHorContext ctx) { var varInstr = getArray2dVariableInstruction(ctx, ctx.variable()); var expr = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(expr.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY2DSHIFTHOR, varInstr.result, expr.result, ir.getSymbolTable().addTmp(INT32, e -> {}))); } @Override public void exitFuncArray2DShiftVer(PuffinBasicParser.FuncArray2DShiftVerContext ctx) { var varInstr = getArray2dVariableInstruction(ctx, ctx.variable()); var expr = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(expr.result).getValue().getDataType(), () -> getCtxString(ctx)); nodeToInstruction.put(ctx, ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ARRAY2DSHIFTVER, varInstr.result, expr.result, ir.getSymbolTable().addTmp(INT32, e -> {}))); } private Instruction addFuncWithExprInstruction( OpCode opCode, ParserRuleContext parent, PuffinBasicParser.ExprContext expr, NumericOrString numericOrString) { var exprInstruction = lookupInstruction(expr); assertNumericOrString(exprInstruction.result, parent, numericOrString); return ir.addInstruction( currentLineNumber, parent.start.getStartIndex(), parent.stop.getStopIndex(), opCode, exprInstruction.result, NULL_ID, ir.getSymbolTable().addTmpCompatibleWith(exprInstruction.result) ); } private Instruction addFuncWithExprInstruction( OpCode opCode, ParserRuleContext parent, PuffinBasicParser.ExprContext expr, NumericOrString numericOrString, int result) { var exprInstruction = lookupInstruction(expr); assertNumericOrString(exprInstruction.result, parent, numericOrString); return ir.addInstruction( currentLineNumber, parent.start.getStartIndex(), parent.stop.getStopIndex(), opCode, exprInstruction.result, NULL_ID, result ); } private void assertNumericOrString(int id, ParserRuleContext parent, NumericOrString numericOrString) { var dt = ir.getSymbolTable().get(id).getValue().getDataType(); if (numericOrString == NumericOrString.NUMERIC) { Types.assertNumeric(dt, () -> getCtxString(parent)); } else { Types.assertString(dt, () -> getCtxString(parent)); } } // // Stmt // @Override public void exitComment(PuffinBasicParser.CommentContext ctx) { ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.COMMENT, NULL_ID, NULL_ID, NULL_ID ); } @Override public void exitLetstmt(PuffinBasicParser.LetstmtContext ctx) { var varname = ctx.variable().varname().VARNAME().getText(); var varsuffix = ctx.variable().varsuffix() != null ? ctx.variable().varsuffix().getText() : null; var dataType = ir.getSymbolTable().getDataTypeFor(varname, varsuffix); var variableName = new VariableName(varname, dataType); var exprInstruction = lookupInstruction(ctx.expr()); final int varId = ir.getSymbolTable().addVariableOrUDF( variableName, variableName1 -> Variable.of(variableName1, false, () -> getCtxString(ctx)), (id, varEntry) -> { var variable = varEntry.getVariable(); if (variable.isUDF()) { throw new PuffinBasicSemanticError( BAD_ASSIGNMENT, getCtxString(ctx), "Can't assign to UDF: " + variable ); } checkDataTypeMatch(varEntry.getValue(), exprInstruction.result, () -> getCtxString(ctx)); }); var varInstr = lookupInstruction(ctx.variable()); var assignInstruction = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ASSIGN, varInstr.result, exprInstruction.result, varInstr.result ); nodeToInstruction.put(ctx, assignInstruction); varDefined.add(variableName); } @Override public void exitPrintstmt(PuffinBasicParser.PrintstmtContext ctx) { handlePrintstmt(ctx, ctx.printlist().children, null); } @Override public void exitPrinthashstmt(PuffinBasicParser.PrinthashstmtContext ctx) { var fileNumber = lookupInstruction(ctx.filenum); handlePrintstmt(ctx, ctx.printlist().children, fileNumber); } private void handlePrintstmt( ParserRuleContext ctx, List<ParseTree> children, @Nullable Instruction fileNumber) { boolean endsWithNewline = true; for (ParseTree child : children) { if (child instanceof PuffinBasicParser.ExprContext) { var exprInstruction = lookupInstruction((PuffinBasicParser.ExprContext) child); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PRINT, exprInstruction.result, NULL_ID, NULL_ID ); endsWithNewline = true; } else { endsWithNewline = false; } } if (endsWithNewline || fileNumber != null) { var newlineId = ir.getSymbolTable().addTmp(STRING, entry -> entry.getValue().setString(System.lineSeparator())); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PRINT, newlineId, NULL_ID, NULL_ID ); } final int fileNumberId; if (fileNumber != null) { Types.assertNumeric(ir.getSymbolTable().get(fileNumber.result).getValue().getDataType(), () -> getCtxString(ctx)); fileNumberId = fileNumber.result; } else { fileNumberId = NULL_ID; } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.FLUSH, fileNumberId, NULL_ID, NULL_ID ); } @Override public void exitPrintusingstmt(PuffinBasicParser.PrintusingstmtContext ctx) { handlePrintusing(ctx, ctx.format, ctx.printlist().children, null); } @Override public void exitPrinthashusingstmt(PuffinBasicParser.PrinthashusingstmtContext ctx) { var fileNumber = lookupInstruction(ctx.filenum); handlePrintusing(ctx, ctx.format, ctx.printlist().children, fileNumber); } private void handlePrintusing( ParserRuleContext ctx, PuffinBasicParser.ExprContext formatCtx, List<ParseTree> children, Instruction fileNumber) { var format = lookupInstruction(formatCtx); boolean endsWithNewline = true; for (ParseTree child : children) { if (child instanceof PuffinBasicParser.ExprContext) { var exprInstruction = lookupInstruction((PuffinBasicParser.ExprContext) child); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PRINTUSING, format.result, exprInstruction.result, NULL_ID ); endsWithNewline = true; } else { endsWithNewline = false; } } if (endsWithNewline || fileNumber != null) { var newlineId = ir.getSymbolTable().addTmp(STRING, entry -> entry.getValue().setString(System.lineSeparator())); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PRINT, newlineId, NULL_ID, NULL_ID ); } final int fileNumberId; if (fileNumber != null) { Types.assertNumeric(ir.getSymbolTable().get(fileNumber.result).getValue().getDataType(), () -> getCtxString(ctx)); fileNumberId = fileNumber.result; } else { fileNumberId = NULL_ID; } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.FLUSH, fileNumberId, NULL_ID, NULL_ID ); } @Override public void exitDimstmt(PuffinBasicParser.DimstmtContext ctx) { IntList dims = new IntArrayList(ctx.DECIMAL().size()); for (var dimMax : ctx.DECIMAL()) { int dimSize = Numbers.parseInt32(dimMax.getText(), () -> getCtxString(ctx)); dims.add(dimSize); } var varname = ctx.varname().VARNAME().getText(); var varsuffix = ctx.varsuffix() != null ? ctx.varsuffix().getText() : null; var dataType = ir.getSymbolTable().getDataTypeFor(varname, varsuffix); var variableName = new VariableName(varname, dataType); ir.getSymbolTable().addVariableOrUDF( variableName, variableName1 -> Variable.of(variableName1, true, () -> getCtxString(ctx)), (id, entry) -> entry.getValue().setArrayDimensions(dims)); varDefined.add(variableName); } @Override public void enterDeffnstmt(PuffinBasicParser.DeffnstmtContext ctx) { var varname = ctx.varname().getText(); var varsuffix = ctx.varsuffix() != null ? ctx.varsuffix().getText() : null; var dataType = ir.getSymbolTable().getDataTypeFor(varname, varsuffix); var variableName = new VariableName(varname, dataType); ir.getSymbolTable().addVariableOrUDF(variableName, variableName1 -> Variable.of(variableName1, false, () -> getCtxString(ctx)), (varId, varEntry) -> { var udfState = new UDFState(); udfStateMap.put(varEntry.getVariable(), udfState); // GOTO postFuncDecl udfState.gotoPostFuncDecl = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL, ir.getSymbolTable().addGotoTarget(), NULL_ID, NULL_ID ); // LABEL FuncStart udfState.labelFuncStart = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); // Push child scope ir.getSymbolTable().pushDeclarationScope(varId); }); } @Override public void exitDeffnstmt(PuffinBasicParser.DeffnstmtContext ctx) { var varname = ctx.varname().getText(); var varsuffix = ctx.varsuffix() != null ? ctx.varsuffix().getText() : null; var dataType = ir.getSymbolTable().getDataTypeFor(varname, varsuffix); var variableName = new VariableName(varname, dataType); ir.getSymbolTable().addVariableOrUDF(variableName, variableName1 -> Variable.of(variableName1, false, () -> getCtxString(ctx)), (varId, varEntry) -> { var udfEntry = (STUDF) varEntry; var udfState = udfStateMap.get(varEntry.getVariable()); for (VariableContext fnParamCtx : ctx.variable()) { var fnParamInstr = lookupInstruction(fnParamCtx); udfEntry.declareParam(fnParamInstr.result); } var exprInstr = lookupInstruction(ctx.expr()); checkDataTypeMatch(varId, exprInstr.result, () -> getCtxString(ctx)); // Copy expr to result ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.COPY, varId, exprInstr.result, varId ); // Pop declaration scope ir.getSymbolTable().popScope(); // GOTO Caller ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_CALLER, NULL_ID, NULL_ID, NULL_ID ); // LABEL postFuncDecl var labelPostFuncDecl = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); // Patch GOTO postFuncDecl udfState.gotoPostFuncDecl.patchOp1(labelPostFuncDecl.op1); }); } @Override public void exitEndstmt(PuffinBasicParser.EndstmtContext ctx) { ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.END, NULL_ID, NULL_ID,NULL_ID ); } @Override public void enterWhilestmt(PuffinBasicParser.WhilestmtContext ctx) { var whileLoopState = new WhileLoopState(); // LABEL beforeWhile whileLoopState.labelBeforeWhile = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); whileLoopStateList.add(whileLoopState); } @Override public void exitWhilestmt(PuffinBasicParser.WhilestmtContext ctx) { var whileLoopState = whileLoopStateList.getLast(); // expr() var expr = lookupInstruction(ctx.expr()); // NOT expr() var notExpr = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.NOT, expr.result, NULL_ID, ir.getSymbolTable().addTmp(INT64, e -> {}) ); // If expr is false, GOTO afterWend whileLoopState.gotoAfterWend = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL_IF, notExpr.result, ir.getSymbolTable().addLabel(), NULL_ID ); } @Override public void exitWendstmt(PuffinBasicParser.WendstmtContext ctx) { if (whileLoopStateList.isEmpty()) { throw new PuffinBasicSemanticError( PuffinBasicSemanticError.ErrorCode.WEND_WITHOUT_WHILE, getCtxString(ctx), "Wend without while"); } var whileLoopState = whileLoopStateList.removeLast(); // GOTO LABEL beforeWhile ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL, whileLoopState.labelBeforeWhile.op1, NULL_ID, NULL_ID); // LABEL afterWend var labelAfterWend = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); // Patch GOTO afterWend whileLoopState.gotoAfterWend.patchOp2(labelAfterWend.op1); } @Override public void exitForstmt(PuffinBasicParser.ForstmtContext ctx) { var var = lookupInstruction(ctx.variable()); var init = lookupInstruction(ctx.expr(0)); var end = lookupInstruction(ctx.expr(1)); Types.assertNumeric(ir.getSymbolTable().get(init.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(end.result).getValue().getDataType(), () -> getCtxString(ctx)); var forLoopState = new ForLoopState(); forLoopState.variable = ((STVariable) ir.getSymbolTable().get(var.result)).getVariable(); // stepCopy = step or 1 (default) Instruction stepCopy; if (ctx.expr(2) != null) { var step = lookupInstruction(ctx.expr(2)); Types.assertNumeric(ir.getSymbolTable().get(step.result).getValue().getDataType(), () -> getCtxString(ctx)); var tmpStep = ir.getSymbolTable().addTmpCompatibleWith(step.result); stepCopy = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.COPY, tmpStep, step.result, tmpStep ); } else { var tmpStep = ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(1)); stepCopy = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.VALUE, tmpStep, NULL_ID, tmpStep ); } // var=init ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ASSIGN, var.result, init.result, var.result ); // endCopy=end var tmpEnd = ir.getSymbolTable().addTmpCompatibleWith(end.result); var endCopy = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ASSIGN, tmpEnd, end.result, tmpEnd ); // GOTO LABEL CHECK var gotoLabelCheck = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL, ir.getSymbolTable().addGotoTarget(), NULL_ID, NULL_ID ); // APPLY STEP // JUMP here from NEXT forLoopState.labelApplyStep = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); var tmpAdd = ir.getSymbolTable().addTmpCompatibleWith(var.result); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ADD, var.result, stepCopy.result, tmpAdd ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.ASSIGN, var.result, tmpAdd, var.result ); // CHECK // If (step >= 0 and var > end) or (step < 0 and var < end) GOTO after "next" // step >= 0 var labelCheck = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); var zero = ir.getSymbolTable().addTmp(INT32, e -> {}); var t1 = ir.getSymbolTable().addTmp(INT32, e -> {}); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GE, stepCopy.result, zero, t1 ); // Patch GOTO LABEL Check gotoLabelCheck.patchOp1(labelCheck.op1); // var > end var t2 = ir.getSymbolTable().addTmp(INT32, e -> {}); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GT, var.result, endCopy.result, t2 ); // (step >= 0 and var > end) var t3 = ir.getSymbolTable().addTmp(INT32, e -> {}); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.AND, t1, t2, t3 ); // step < 0 var t4 = ir.getSymbolTable().addTmp(INT32, e -> {}); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LT, stepCopy.result, zero, t4 ); // var < end var t5 = ir.getSymbolTable().addTmp(INT32, e -> {}); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LT, var.result, endCopy.result, t5 ); // (step < 0 and var < end) var t6 = ir.getSymbolTable().addTmp(INT32, e -> {}); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.AND, t4, t5, t6 ); var t7 = ir.getSymbolTable().addTmp(INT32, e -> {}); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.OR, t3, t6, t7 ); // if (true) GOTO after NEXT // set linenumber on exitNext(). forLoopState.gotoAfterNext = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL_IF, t7, ir.getSymbolTable().addLabel(), NULL_ID ); forLoopStateList.add(forLoopState); } @Override public void exitNextstmt(PuffinBasicParser.NextstmtContext ctx) { List<ForLoopState> states = new ArrayList<>(1); if (ctx.variable().isEmpty()) { if (!forLoopStateList.isEmpty()) { states.add(forLoopStateList.removeLast()); } else { throw new PuffinBasicSemanticError( NEXT_WITHOUT_FOR, getCtxString(ctx), "NEXT without FOR" ); } } else { for (var varCtx : ctx.variable()) { var varname = varCtx.varname().VARNAME().getText(); var varsuffix = varCtx.varsuffix() != null ? varCtx.varsuffix().getText() : null; var dataType = ir.getSymbolTable().getDataTypeFor(varname, varsuffix); var variableName = new VariableName(varname, dataType); int id = ir.getSymbolTable().addVariableOrUDF( variableName, variableName1 -> Variable.of(variableName1, false, () -> getCtxString(ctx)), (id1, e1) -> {}); var variable = ((STVariable) ir.getSymbolTable().get(id)).getVariable(); var state = forLoopStateList.removeLast(); if (state.variable.equals(variable)) { states.add(state); } else { throw new PuffinBasicSemanticError( NEXT_WITHOUT_FOR, getCtxString(ctx), "Next " + variable + " without FOR" ); } } } for (ForLoopState state : states) { // GOTO APPLY STEP ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL, state.labelApplyStep.op1, NULL_ID, NULL_ID ); // LABEL afterNext var labelAfterNext = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); state.gotoAfterNext.patchOp2(labelAfterNext.op1); } } /* * condition * GOTOIF condition labelBeforeThen * GOTO labelAfterThen|labelBeforeElse * labelBeforeThen * ThenStmts * GOTO labelAfterThen|labelAfterElse * labelAfterThen * ElseStmts * labelAfterElse */ @Override public void enterIfThenElse(PuffinBasicParser.IfThenElseContext ctx) { nodeToIfState.put(ctx, new IfState()); } @Override public void exitIfThenElse(PuffinBasicParser.IfThenElseContext ctx) { var ifState = nodeToIfState.get(ctx); boolean noElseStmt = ifState.labelBeforeElse == null; var condition = lookupInstruction(ctx.expr()); // Patch IF true: condition ifState.gotoIfConditionTrue.patchOp1(condition.result); // Patch IF true: GOTO labelBeforeThen ifState.gotoIfConditionTrue.patchOp2(ifState.labelBeforeThen.op1); // Patch IF false: GOTO labelAfterThen|labelBeforeElse ifState.gotoIfConditionFalse.patchOp1( noElseStmt ? ifState.labelAfterThen.op1 : ifState.labelBeforeElse.op1 ); // Patch THEN: GOTO labelAfterThen|labelAfterElse ifState.gotoFromThenAfterIf.patchOp1( noElseStmt ? ifState.labelAfterThen.op1 : ifState.labelAfterElse.op1 ); } @Override public void enterThen(PuffinBasicParser.ThenContext ctx) { var ifState = nodeToIfState.get(ctx.getParent()); // IF condition is true, GOTO labelBeforeThen ifState.gotoIfConditionTrue = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL_IF, ir.getSymbolTable().addGotoTarget(), NULL_ID, NULL_ID ); // IF condition is false, GOTO labelAfterThen|labelBeforeElse ifState.gotoIfConditionFalse = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL, ir.getSymbolTable().addGotoTarget(), NULL_ID, NULL_ID ); ifState.labelBeforeThen = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); } @Override public void exitThen(PuffinBasicParser.ThenContext ctx) { // Add instruction for: // THEN GOTO linenum | THEN linenum if (ctx.linenum() != null) { var gotoLinenum = parseLinenum(ctx.linenum().getText()); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LINENUM, getGotoLineNumberOp1(gotoLinenum), NULL_ID, NULL_ID ); } var ifState = nodeToIfState.get(ctx.getParent()); // GOTO labelAfterThen|labelAfterElse ifState.gotoFromThenAfterIf = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); ifState.labelAfterThen = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); } @Override public void enterElsestmt(PuffinBasicParser.ElsestmtContext ctx) { var ifState = nodeToIfState.get(ctx.getParent()); ifState.labelBeforeElse = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); } @Override public void exitElsestmt(PuffinBasicParser.ElsestmtContext ctx) { // Add instruction for: // ELSE linenum if (ctx.linenum() != null) { var gotoLinenum = parseLinenum(ctx.linenum().getText()); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LINENUM, getGotoLineNumberOp1(gotoLinenum), NULL_ID, NULL_ID ); } var ifState = nodeToIfState.get(ctx.getParent()); ifState.labelAfterElse = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); } @Override public void exitGosubstmt(PuffinBasicParser.GosubstmtContext ctx) { var gotoLinenum = parseLinenum(ctx.linenum().getText()); var pushReturnLabel = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PUSH_RETLABEL, ir.getSymbolTable().addGotoTarget(), NULL_ID, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LINENUM, getGotoLineNumberOp1(gotoLinenum), NULL_ID, NULL_ID ); var labelReturn = ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LABEL, ir.getSymbolTable().addLabel(), NULL_ID, NULL_ID ); pushReturnLabel.patchOp1(labelReturn.op1); } @Override public void exitReturnstmt(PuffinBasicParser.ReturnstmtContext ctx) { if (ctx.linenum() != null) { var gotoLinenum = parseLinenum(ctx.linenum().getText()); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RETURN, getGotoLineNumberOp1(gotoLinenum), NULL_ID, NULL_ID ); } else { ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RETURN, NULL_ID, NULL_ID, NULL_ID ); } } @Override public void exitGotostmt(PuffinBasicParser.GotostmtContext ctx) { var gotoLinenum = parseLinenum(ctx.linenum().getText()); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GOTO_LINENUM, getGotoLineNumberOp1(gotoLinenum), NULL_ID, NULL_ID ); } @Override public void exitSwapstmt(PuffinBasicParser.SwapstmtContext ctx) { var var1 = lookupInstruction(ctx.variable(0)); var var2 = lookupInstruction(ctx.variable(1)); var dt1 = ir.getSymbolTable().get(var1.result).getValue().getDataType(); var dt2 = ir.getSymbolTable().get(var2.result).getValue().getDataType(); if (dt1 != dt2) { throw new PuffinBasicSemanticError( DATA_TYPE_MISMATCH, getCtxString(ctx), dt1 + " doesn't match " + dt2 ); } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.SWAP, var1.result, var2.result, NULL_ID ); } @Override public void exitOpen1stmt(PuffinBasicParser.Open1stmtContext ctx) { var filenameInstr = lookupInstruction(ctx.filename); var fileOpenMode = getFileOpenMode(ctx.filemode1()); var accessMode = getFileAccessMode(null); var lockMode = getLockMode(null); var fileNumber = Numbers.parseInt32(ctx.filenum.getText(), () -> getCtxString(ctx)); var recordLenInstrId = ctx.reclen != null ? lookupInstruction(ctx.reclen).result : ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(DEFAULT_RECORD_LEN)); Types.assertString(ir.getSymbolTable().get(filenameInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(recordLenInstrId).getValue().getDataType(), () -> getCtxString(ctx)); // fileName, fileNumber ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.OPEN_FN_FN_0, filenameInstr.result, ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(fileNumber)), NULL_ID ); // openMode, accessMode ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.OPEN_OM_AM_1, ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString(fileOpenMode.name())), ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString(accessMode.name())), NULL_ID ); // lockMode, recordLen ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.OPEN_LM_RL_2, ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString(lockMode.name())), recordLenInstrId, NULL_ID ); } @Override public void exitOpen2stmt(PuffinBasicParser.Open2stmtContext ctx) { var filenameInstr = lookupInstruction(ctx.filename); var fileOpenMode = getFileOpenMode(ctx.filemode2()); var accessMode = getFileAccessMode(ctx.access()); var lockMode = getLockMode(ctx.lock()); var fileNumber = Numbers.parseInt32(ctx.filenum.getText(), () -> getCtxString(ctx)); var recordLenInstrId = ctx.reclen != null ? lookupInstruction(ctx.reclen).result : ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(DEFAULT_RECORD_LEN)); Types.assertString(ir.getSymbolTable().get(filenameInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(recordLenInstrId).getValue().getDataType(), () -> getCtxString(ctx)); // fileName, fileNumber ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.OPEN_FN_FN_0, filenameInstr.result, ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(fileNumber)), NULL_ID ); // openMode, accessMode ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.OPEN_OM_AM_1, ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString(fileOpenMode.name())), ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString(accessMode.name())), NULL_ID ); // lockMode, recordLen ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.OPEN_LM_RL_2, ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString(lockMode.name())), recordLenInstrId, NULL_ID ); } @Override public void exitClosestmt(PuffinBasicParser.ClosestmtContext ctx) { var fileNumbers = ctx.DECIMAL().stream().map( fileNumberCtx -> Numbers.parseInt32(fileNumberCtx.getText(), () -> getCtxString(ctx)) ).collect(Collectors.toList()); if (fileNumbers.isEmpty()) { ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CLOSE_ALL, NULL_ID, NULL_ID, NULL_ID ); } else { fileNumbers.forEach(fileNumber -> ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CLOSE, ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(fileNumber)), NULL_ID, NULL_ID )); } } @Override public void exitFieldstmt(PuffinBasicParser.FieldstmtContext ctx) { var fileNumberInstr = lookupInstruction(ctx.filenum); Types.assertNumeric(ir.getSymbolTable().get(fileNumberInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); var numEntries = ctx.variable().size(); for (int i = 0; i < numEntries; i++) { var recordPartLen = Numbers.parseInt32(ctx.DECIMAL(i).getText(), () -> getCtxString(ctx)); var varInstr = lookupInstruction(ctx.variable(i)); var kind = ir.getSymbolTable().get(varInstr.result).getKind(); assertVariable(kind, () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.FIELD_I, varInstr.result, ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(recordPartLen)), NULL_ID ); } // FileNumber, #fields ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.FIELD, fileNumberInstr.result, ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(numEntries)), NULL_ID ); } private void assertVariable(STKind kind, Supplier<String> line) { if (kind != STKind.VARIABLE && kind != STKind.ARRAYREF) { throw new PuffinBasicSemanticError( BAD_ARGUMENT, line.get(), "Expected variable, but found: " + kind ); } } private void assertVariableDefined(VariableName variableName, Supplier<String> line) { if (!varDefined.contains(variableName)) { throw new PuffinBasicSemanticError( NOT_DEFINED, line.get(), "Variable: " + variableName + " used before it is defined!" ); } } private void assert1DArray(STVariable variable, Supplier<String> line) { if (!variable.getVariable().isArray() || variable.getValue().getNumArrayDimensions() != 1) { throw new PuffinBasicSemanticError( BAD_ARGUMENT, line.get(), "Variable: " + variable.getVariable().getVariableName() + " is not array1d" ); } } private void assert2DArray(STVariable variable, Supplier<String> line) { if (!variable.getVariable().isArray() || variable.getValue().getNumArrayDimensions() != 2) { throw new PuffinBasicSemanticError( BAD_ARGUMENT, line.get(), "Variable: " + variable.getVariable().getVariableName() + " is not array2d" ); } } private void assertNDArray(STVariable variable, Supplier<String> line) { if (!variable.getVariable().isArray()) { throw new PuffinBasicSemanticError( BAD_ARGUMENT, line.get(), "Variable: " + variable.getVariable().getVariableName() + " is not array" ); } } @Override public void exitPutstmt(PuffinBasicParser.PutstmtContext ctx) { var fileNumberInstr = Numbers.parseInt32(ctx.filenum.getText(), () -> getCtxString(ctx)); final int exprId; if (ctx.expr() != null) { exprId = lookupInstruction(ctx.expr()).result; Types.assertNumeric(ir.getSymbolTable().get(exprId).getValue().getDataType(), () -> getCtxString(ctx)); } else { exprId = NULL_ID; } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PUTF, ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(fileNumberInstr)), exprId, NULL_ID ); } @Override public void exitMiddlrstmt(PuffinBasicParser.MiddlrstmtContext ctx) { var varInstr = lookupInstruction(ctx.variable()); var nInstr = lookupInstruction(ctx.expr(0)); var mInstrId = ctx.expr().size() == 3 ? lookupInstruction(ctx.expr(1)).result : ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(-1)); var replacement = ctx.expr().size() == 3 ? lookupInstruction(ctx.expr(2)) : lookupInstruction(ctx.expr(1)); Types.assertString(ir.getSymbolTable().get(varInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertString(ir.getSymbolTable().get(replacement.result).getValue().getDataType(), () -> getCtxString(ctx)); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); assertVariableDefined(((STVariable) ir.getSymbolTable().get(varInstr.result)).getVariable().getVariableName(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(nInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(mInstrId).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.MIDDLR0, varInstr.result, nInstr.result, NULL_ID); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.MIDDLR_STMT, mInstrId, replacement.result, NULL_ID); } @Override public void exitGetstmt(PuffinBasicParser.GetstmtContext ctx) { var fileNumberInstr = Numbers.parseInt32(ctx.filenum.getText(), () -> getCtxString(ctx)); final int exprId; if (ctx.expr() != null) { exprId = lookupInstruction(ctx.expr()).result; Types.assertNumeric(ir.getSymbolTable().get(exprId).getValue().getDataType(), () -> getCtxString(ctx)); } else { exprId = NULL_ID; } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GETF, ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(fileNumberInstr)), exprId, NULL_ID ); } @Override public void exitRandomizestmt(PuffinBasicParser.RandomizestmtContext ctx) { var exprId = lookupInstruction(ctx.expr()).result; Types.assertNumeric(ir.getSymbolTable().get(exprId).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RANDOMIZE, exprId, NULL_ID, NULL_ID ); } @Override public void exitRandomizetimerstmt(PuffinBasicParser.RandomizetimerstmtContext ctx) { ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RANDOMIZE_TIMER, NULL_ID, NULL_ID, NULL_ID ); } @Override public void exitDefintstmt(PuffinBasicParser.DefintstmtContext ctx) { handleDefTypeStmt(ctx.LETTERRANGE(), INT32); } @Override public void exitDeflngstmt(PuffinBasicParser.DeflngstmtContext ctx) { handleDefTypeStmt(ctx.LETTERRANGE(), INT64); } @Override public void exitDefsngstmt(PuffinBasicParser.DefsngstmtContext ctx) { handleDefTypeStmt(ctx.LETTERRANGE(), FLOAT); } @Override public void exitDefdblstmt(PuffinBasicParser.DefdblstmtContext ctx) { handleDefTypeStmt(ctx.LETTERRANGE(), DOUBLE); } @Override public void exitDefstrstmt(PuffinBasicParser.DefstrstmtContext ctx) { handleDefTypeStmt(ctx.LETTERRANGE(), STRING); } @Override public void exitLsetstmt(PuffinBasicParser.LsetstmtContext ctx) { var varInstr = lookupInstruction(ctx.variable()); var exprInstr = lookupInstruction(ctx.expr()); var varEntry = ir.getSymbolTable().get(varInstr.result); assertVariable(varEntry.getKind(), () -> getCtxString(ctx)); Types.assertString(varEntry.getValue().getDataType(), () -> getCtxString(ctx)); Types.assertString(ir.getSymbolTable().get(exprInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LSET, varInstr.result, exprInstr.result, NULL_ID ); } @Override public void exitRsetstmt(PuffinBasicParser.RsetstmtContext ctx) { var varInstr = lookupInstruction(ctx.variable()); var exprInstr = lookupInstruction(ctx.expr()); var varEntry = ir.getSymbolTable().get(varInstr.result); assertVariable(varEntry.getKind(), () -> getCtxString(ctx)); assertVariableDefined(((STVariable) varEntry).getVariable().getVariableName(), () -> getCtxString(ctx)); Types.assertString(varEntry.getValue().getDataType(), () -> getCtxString(ctx)); Types.assertString(ir.getSymbolTable().get(exprInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RSET, varInstr.result, exprInstr.result, NULL_ID ); } @Override public void exitInputstmt(PuffinBasicParser.InputstmtContext ctx) { for (var varCtx : ctx.variable()) { var varInstr = lookupInstruction(varCtx); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INPUT_VAR, varInstr.result, NULL_ID, NULL_ID ); } int promptId; if (ctx.expr() != null) { promptId = lookupInstruction(ctx.expr()).result; Types.assertString(ir.getSymbolTable().get(promptId).getValue().getDataType(), () -> getCtxString(ctx)); } else { promptId = ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString("?")); } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INPUT, promptId, NULL_ID, NULL_ID ); } @Override public void exitInputhashstmt(PuffinBasicParser.InputhashstmtContext ctx) { for (var varCtx : ctx.variable()) { var varInstr = lookupInstruction(varCtx); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INPUT_VAR, varInstr.result, NULL_ID, NULL_ID ); } var fileNumInstr = lookupInstruction(ctx.filenum); Types.assertNumeric(ir.getSymbolTable().get(fileNumInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INPUT, NULL_ID, fileNumInstr.result, NULL_ID ); } @Override public void exitLineinputstmt(PuffinBasicParser.LineinputstmtContext ctx) { var varInstr = lookupInstruction(ctx.variable()); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INPUT_VAR, varInstr.result, NULL_ID, NULL_ID ); int promptId; if (ctx.expr() != null) { promptId = lookupInstruction(ctx.expr()).result; Types.assertString(ir.getSymbolTable().get(promptId).getValue().getDataType(), () -> getCtxString(ctx)); } else { promptId = ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString("")); } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LINE_INPUT, promptId, NULL_ID, NULL_ID ); } @Override public void exitLineinputhashstmt(PuffinBasicParser.LineinputhashstmtContext ctx) { var varInstr = lookupInstruction(ctx.variable()); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.INPUT_VAR, varInstr.result, NULL_ID, NULL_ID ); var fileNumInstr = lookupInstruction(ctx.filenum); Types.assertNumeric(ir.getSymbolTable().get(fileNumInstr.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LINE_INPUT, NULL_ID, fileNumInstr.result, NULL_ID ); } @Override public void exitWritestmt(PuffinBasicParser.WritestmtContext ctx) { handleWritestmt(ctx, ctx.expr(), null); } @Override public void exitWritehashstmt(PuffinBasicParser.WritehashstmtContext ctx) { var fileNumInstr = lookupInstruction(ctx.filenum); handleWritestmt(ctx, ctx.expr(), fileNumInstr); } public void handleWritestmt( ParserRuleContext ctx, List<PuffinBasicParser.ExprContext> exprs, @Nullable Instruction fileNumber) { // if fileNumber != null, skip first instruction for (int i = fileNumber == null ? 0 : 1; i < exprs.size(); i++) { var exprCtx = exprs.get(i); var exprInstr = lookupInstruction(exprCtx); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.WRITE, exprInstr.result, NULL_ID, NULL_ID ); if (i + 1 < exprs.size()) { var commaId = ir.getSymbolTable().addTmp(STRING, entry -> entry.getValue().setString(",")); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PRINT, commaId, NULL_ID, NULL_ID ); } } var newlineId = ir.getSymbolTable().addTmp(STRING, entry -> entry.getValue().setString(System.lineSeparator())); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PRINT, newlineId, NULL_ID, NULL_ID ); final int fileNumberId; if (fileNumber != null) { Types.assertNumeric(ir.getSymbolTable().get(fileNumber.result).getValue().getDataType(), () -> getCtxString(ctx)); fileNumberId = fileNumber.result; } else { fileNumberId = NULL_ID; } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.FLUSH, fileNumberId, NULL_ID, NULL_ID ); } @Override public void exitReadstmt(PuffinBasicParser.ReadstmtContext ctx) { for (var varCtx : ctx.variable()) { var varInstr = lookupInstruction(varCtx); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.READ, varInstr.result, NULL_ID, NULL_ID ); } } @Override public void exitRestorestmt(PuffinBasicParser.RestorestmtContext ctx) { ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.RESTORE, NULL_ID, NULL_ID, NULL_ID ); } @Override public void exitDatastmt(PuffinBasicParser.DatastmtContext ctx) { var children = ctx.children; for (int i = 1; i < children.size(); i += 2) { var child = children.get(i); int valueId; if (child instanceof PuffinBasicParser.NumberContext) { valueId = lookupInstruction((PuffinBasicParser.NumberContext) child).result; } else { var text = unquote(child.getText()); valueId = ir.getSymbolTable().addTmp(STRING, e -> e.getValue().setString(text)); } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.DATA, valueId, NULL_ID, NULL_ID ); } } // GraphicsRuntime @Override public void exitScreenstmt(PuffinBasicParser.ScreenstmtContext ctx) { assertGraphics(); var title = lookupInstruction(ctx.expr(0)); var w = lookupInstruction(ctx.expr(1)); var h = lookupInstruction(ctx.expr(2)); var manualRepaint = ctx.mr != null; Types.assertString(ir.getSymbolTable().get(title.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(w.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(h.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.SCREEN0, w.result, h.result, NULL_ID ); var repaint = ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32( manualRepaint ? 0 : -1)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.SCREEN, title.result, repaint, NULL_ID ); } @Override public void exitRepaintstmt(PuffinBasicParser.RepaintstmtContext ctx) { assertGraphics(); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.REPAINT, NULL_ID, NULL_ID, NULL_ID ); } @Override public void exitCirclestmt(PuffinBasicParser.CirclestmtContext ctx) { assertGraphics(); var x = lookupInstruction(ctx.x); var y = lookupInstruction(ctx.y); var r1 = lookupInstruction(ctx.r1); var r2 = lookupInstruction(ctx.r2); var s = ctx.s != null ? lookupInstruction(ctx.s) : null; var e = ctx.e != null ? lookupInstruction(ctx.e) : null; var fill = ctx.fill != null ? lookupInstruction(ctx.fill) : null; Types.assertNumeric(ir.getSymbolTable().get(x.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(r1.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(r2.result).getValue().getDataType(), () -> getCtxString(ctx)); if (s != null) { Types.assertNumeric(ir.getSymbolTable().get(s.result).getValue().getDataType(), () -> getCtxString(ctx)); } if (e != null) { Types.assertNumeric(ir.getSymbolTable().get(e.result).getValue().getDataType(), () -> getCtxString(ctx)); } if (fill != null) { Types.assertString(ir.getSymbolTable().get(fill.result).getValue().getDataType(), () -> getCtxString(ctx)); } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CIRCLE_XY, x.result, y.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CIRCLE_SE, s != null ? s.result : NULL_ID, e != null ? e.result : NULL_ID, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CIRCLE_FILL, fill != null ? fill.result : NULL_ID, NULL_ID, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CIRCLE, r1.result, r2.result, NULL_ID ); } @Override public void exitLinestmt(PuffinBasicParser.LinestmtContext ctx) { assertGraphics(); var x1 = lookupInstruction(ctx.x1); var y1 = lookupInstruction(ctx.y1); var x2 = lookupInstruction(ctx.x2); var y2 = lookupInstruction(ctx.y2); Types.assertNumeric(ir.getSymbolTable().get(x1.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y1.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(x2.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y2.result).getValue().getDataType(), () -> getCtxString(ctx)); Instruction bf = null; if (ctx.bf != null){ bf = lookupInstruction(ctx.bf); Types.assertString(ir.getSymbolTable().get(bf.result).getValue().getDataType(), () -> getCtxString(ctx)); } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LINE_x1y1, x1.result, y1.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LINE_x2y2, x2.result, y2.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LINE, bf != null ? bf.result : NULL_ID, NULL_ID, NULL_ID ); } @Override public void exitColorstmt(PuffinBasicParser.ColorstmtContext ctx) { var r = lookupInstruction(ctx.r); var g = lookupInstruction(ctx.g); var b = lookupInstruction(ctx.b); Types.assertNumeric(ir.getSymbolTable().get(r.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(g.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(b.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.COLOR_RG, r.result, g.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.COLOR, b.result, NULL_ID, NULL_ID ); } @Override public void exitPaintstmt(PuffinBasicParser.PaintstmtContext ctx) { assertGraphics(); var x = lookupInstruction(ctx.x); var y = lookupInstruction(ctx.y); var r = lookupInstruction(ctx.r); var g = lookupInstruction(ctx.g); var b = lookupInstruction(ctx.b); Types.assertNumeric(ir.getSymbolTable().get(x.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(r.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(g.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(b.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PAINT_RG, r.result, g.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PAINT_B, b.result, NULL_ID, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PAINT, x.result, y.result, NULL_ID ); } @Override public void exitPsetstmt(PuffinBasicParser.PsetstmtContext ctx) { assertGraphics(); var x = lookupInstruction(ctx.x); var y = lookupInstruction(ctx.y); int rId = NULL_ID, gId = NULL_ID, bId = NULL_ID; if (ctx.r != null) { rId = lookupInstruction(ctx.r).result; Types.assertNumeric(ir.getSymbolTable().get(rId).getValue().getDataType(), () -> getCtxString(ctx)); } if (ctx.g != null) { gId = lookupInstruction(ctx.g).result; Types.assertNumeric(ir.getSymbolTable().get(gId).getValue().getDataType(), () -> getCtxString(ctx)); } if (ctx.b != null) { bId = lookupInstruction(ctx.b).result; Types.assertNumeric(ir.getSymbolTable().get(bId).getValue().getDataType(), () -> getCtxString(ctx)); } Types.assertNumeric(ir.getSymbolTable().get(x.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PSET_RG, rId, gId, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PSET_B, bId, NULL_ID, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.PSET, x.result, y.result, NULL_ID ); } @Override public void exitGraphicsgetstmt(PuffinBasicParser.GraphicsgetstmtContext ctx) { assertGraphics(); var x1 = lookupInstruction(ctx.x1); var y1 = lookupInstruction(ctx.y1); var x2 = lookupInstruction(ctx.x2); var y2 = lookupInstruction(ctx.y2); var varInstr = lookupInstruction(ctx.variable()); Types.assertNumeric(ir.getSymbolTable().get(x1.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y1.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(x2.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y2.result).getValue().getDataType(), () -> getCtxString(ctx)); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); assertVariableDefined(((STVariable) ir.getSymbolTable().get(varInstr.result)).getVariable().getVariableName(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GGET_X1Y1, x1.result, y1.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GGET_X2Y2, x2.result, y2.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GGET, varInstr.result, NULL_ID, NULL_ID ); } @Override public void exitGraphicsputstmt(PuffinBasicParser.GraphicsputstmtContext ctx) { assertGraphics(); var x = lookupInstruction(ctx.x); var y = lookupInstruction(ctx.y); var varInstr = lookupInstruction(ctx.variable()); var action = ctx.action != null ? lookupInstruction(ctx.action) : null; Types.assertNumeric(ir.getSymbolTable().get(x.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y.result).getValue().getDataType(), () -> getCtxString(ctx)); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); assertVariableDefined(((STVariable) ir.getSymbolTable().get(varInstr.result)).getVariable().getVariableName(), () -> getCtxString(ctx)); if (action != null) { Types.assertString(ir.getSymbolTable().get(action.result).getValue().getDataType(), () -> getCtxString(ctx)); } ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GPUT_XY, x.result, y.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.GPUT, action != null ? action.result : NULL_ID, varInstr.result, NULL_ID ); } @Override public void exitDrawstmt(PuffinBasicParser.DrawstmtContext ctx) { assertGraphics(); var str = lookupInstruction(ctx.expr()); Types.assertString(ir.getSymbolTable().get(str.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.DRAW, str.result, NULL_ID, NULL_ID ); } @Override public void exitFontstmt(PuffinBasicParser.FontstmtContext ctx) { assertGraphics(); var name = lookupInstruction(ctx.name); var style = lookupInstruction(ctx.style); var size = lookupInstruction(ctx.size); Types.assertString(ir.getSymbolTable().get(style.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(size.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertString(ir.getSymbolTable().get(name.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.FONT_SS, style.result, size.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.FONT, name.result, NULL_ID, NULL_ID ); } @Override public void exitDrawstrstmt(PuffinBasicParser.DrawstrstmtContext ctx) { var str = lookupInstruction(ctx.str); var x = lookupInstruction(ctx.x); var y = lookupInstruction(ctx.y); Types.assertNumeric(ir.getSymbolTable().get(x.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertNumeric(ir.getSymbolTable().get(y.result).getValue().getDataType(), () -> getCtxString(ctx)); Types.assertString(ir.getSymbolTable().get(str.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.DRAWSTR_XY, x.result, y.result, NULL_ID ); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.DRAWSTR, str.result, NULL_ID, NULL_ID ); } @Override public void exitLoadimgstmt(PuffinBasicParser.LoadimgstmtContext ctx) { assertGraphics(); var path = lookupInstruction(ctx.path); var varInstr = lookupInstruction(ctx.variable()); Types.assertString(ir.getSymbolTable().get(path.result).getValue().getDataType(), () -> getCtxString(ctx)); assertVariable(ir.getSymbolTable().get(varInstr.result).getKind(), () -> getCtxString(ctx)); assertVariableDefined(((STVariable) ir.getSymbolTable().get(varInstr.result)).getVariable().getVariableName(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.LOADIMG, path.result, varInstr.result, NULL_ID ); } @Override public void exitClsstmt(PuffinBasicParser.ClsstmtContext ctx) { assertGraphics(); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.CLS, NULL_ID, NULL_ID, NULL_ID ); } @Override public void exitSleepstmt(PuffinBasicParser.SleepstmtContext ctx) { var millis = lookupInstruction(ctx.expr()); Types.assertNumeric(ir.getSymbolTable().get(millis.result).getValue().getDataType(), () -> getCtxString(ctx)); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.SLEEP, millis.result, NULL_ID, NULL_ID ); } @Override public void exitBeepstmt(PuffinBasicParser.BeepstmtContext ctx) { assertGraphics(); ir.addInstruction( currentLineNumber, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), OpCode.BEEP, NULL_ID, NULL_ID, NULL_ID ); } private void assertGraphics() { if (!graphics) { throw new PuffinBasicInternalError( "GraphicsRuntime is not enabled!" ); } } private void handleDefTypeStmt( List<TerminalNode> letterRanges, PuffinBasicDataType dataType) { List<Character> defs = new ArrayList<>(); letterRanges.stream().map(ParseTree::getText).forEach(lr -> { for (char i = lr.charAt(0); i <= lr.charAt(2); i++) { defs.add(i); } }); defs.forEach(def -> ir.getSymbolTable().setDefaultDataType(def, dataType)); } private static FileOpenMode getFileOpenMode(PuffinBasicParser.Filemode1Context filemode1) { var mode = filemode1 != null ? unquote(filemode1.getText()) : null; if (mode == null || mode.equalsIgnoreCase("r")) { return FileOpenMode.RANDOM; } else if (mode.equalsIgnoreCase("i")) { return FileOpenMode.INPUT; } else if (mode.equalsIgnoreCase("o")) { return FileOpenMode.OUTPUT; } else { return FileOpenMode.APPEND; } } private static FileOpenMode getFileOpenMode(PuffinBasicParser.Filemode2Context filemode2) { if (filemode2 == null || filemode2.RANDOM() != null) { return FileOpenMode.RANDOM; } else if (filemode2.INPUT() != null) { return FileOpenMode.INPUT; } else if (filemode2.OUTPUT() != null) { return FileOpenMode.OUTPUT; } else { return FileOpenMode.APPEND; } } private static FileAccessMode getFileAccessMode(PuffinBasicParser.AccessContext access) { if (access == null || (access.READ() != null && access.WRITE() != null)) { return FileAccessMode.READ_WRITE; } else if (access.READ() != null) { return FileAccessMode.READ_ONLY; } else { return FileAccessMode.WRITE_ONLY; } } private static LockMode getLockMode(PuffinBasicParser.LockContext lock) { if (lock == null) { return LockMode.DEFAULT; } else if (lock.SHARED() != null) { return LockMode.SHARED; } else if (lock.READ() != null && lock.WRITE() != null) { return LockMode.READ_WRITE; } else if (lock.READ() != null) { return LockMode.READ; } else { return LockMode.WRITE; } } private int getGotoLineNumberOp1(int lineNumber) { return ir.getSymbolTable().addTmp(INT32, e -> e.getValue().setInt32(lineNumber)); } private void checkDataTypeMatch(int id1, int id2, Supplier<String> lineSupplier) { checkDataTypeMatch(ir.getSymbolTable().get(id1).getValue(), id2, lineSupplier); } private void checkDataTypeMatch(STObjects.STValue entry1, int id2, Supplier<String> lineSupplier) { var entry2 = ir.getSymbolTable().get(id2).getValue(); if ((entry1.getDataType() == STRING && entry2.getDataType() != STRING) || (entry1.getDataType() != STRING && entry2.getDataType() == STRING)) { throw new PuffinBasicSemanticError( DATA_TYPE_MISMATCH, lineSupplier.get(), "Data type " + entry1.getDataType() + " mismatches with " + entry2.getDataType() ); } } private static final class UDFState { public Instruction gotoPostFuncDecl; public Instruction labelFuncStart; } private static final class WhileLoopState { public Instruction labelBeforeWhile; public Instruction gotoAfterWend; } private static final class ForLoopState { public Variable variable; public Instruction labelApplyStep; public Instruction gotoAfterNext; } private static final class IfState { public Instruction gotoIfConditionTrue; public Instruction gotoIfConditionFalse; public Instruction gotoFromThenAfterIf; public Instruction labelBeforeThen; public Instruction labelAfterThen; public Instruction labelBeforeElse; public Instruction labelAfterElse; } }
134,794
0.592601
0.588246
3,178
41.414726
29.994795
135
false
false
0
0
0
0
0
0
0.870044
false
false
13
555d813651088d92f3389d7ef8c614610f369a9c
38,817,914,468,920
ecb89b71bc331507895912c6cb13ac61e312602f
/src/main/java/com/meyermt/dns/DNSClient.java
4286ca0c8bdbb2f0e624f32a1e68c1d2f9d937c5
[]
no_license
meyermt/DNSServer
https://github.com/meyermt/DNSServer
d858fc1fdc5c7040227c08c3520ebc55ccc93bec
61df16d8acbaae45fd9487c78bb1e69f21999102
refs/heads/master
2021-03-19T17:26:42.713000
2017-04-28T23:19:42
2017-04-28T23:19:42
89,670,585
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.meyermt.dns; import com.fasterxml.jackson.core.JsonProcessingException; import com.mashape.unirest.http.ObjectMapper; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * Created by michaelmeyer on 4/23/17. */ public class DNSClient { private Logger logger = LoggerFactory.getLogger(DNSClient.class); public DNSClient() { setUpMapper(); } public String sendMessage(Message message, Peer peer) { String url = "http://" + peer.getIp() + ":" + peer.getPort() + "/messages"; try { return Unirest.post(url) .body(message.getMessage()) .asString() .getBody(); } catch (UnirestException e) { e.printStackTrace(); // we need to pass back something helpful in this scenario return "Sorry, it appears as though " + peer.getName() + " is not home right now."; } } public String sendMessageThroughSuper(Message message, Superpeer sp) { String url = "http://" + sp.getIp() + ":" + sp.getPort() + "/api/sendthrusuper"; try { return Unirest.post(url) .body(message) .asString() .getBody(); } catch (UnirestException e) { throw new RuntimeException("Unable to send message", e); } } public void sendRegistration(String superIPPort, String fullNodeName, String ip, int port) { try { String url = "http://" + superIPPort + "/api/newnode"; Peer peer = new Peer(0, fullNodeName, ip, port, false); Unirest.post(url) .body(peer) .asString(); } catch (UnirestException e) { throw new RuntimeException("Unable to send message", e); } } // public void disseminateSuperRegistration(List<Superpeer> superpeers) { // superpeers.forEach(superpeer -> { // String url = "http://" + superpeer.getIp() + ":" + superpeer.getPort() + "/api/regsuper"; // logger.info("sending along super reg to: {}", url); // try { // Unirest.post(url) // .body(superpeer) // .asString(); // } catch (UnirestException e) { // throw new RuntimeException("Unable to send along superpeer registration", e); // } // }); // } // // public List<Superpeer> sendSuperRegistration(Superpeer mySuper, String superFriend) { // try { // logger.info("friend is " + superFriend); // logger.info("you are " + mySuper.toString()); // String url = "http://" + superFriend + "/api/newsuper"; // HttpResponse<SPGroup> peers = Unirest.post(url) // .body(mySuper) // .asObject(SPGroup.class); // return peers.getBody().getSps(); // } catch (UnirestException e) { // throw new RuntimeException("Unable to send super registration", e); // } // } private void setUpMapper () { Unirest.setObjectMapper(new ObjectMapper() { private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); public <T> T readValue(String value, Class<T> valueType) { try { return jacksonObjectMapper.readValue(value, valueType); } catch (IOException e) { throw new RuntimeException(e); } } public String writeValue(Object value) { try { return jacksonObjectMapper.writeValueAsString(value); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }); } }
UTF-8
Java
4,077
java
DNSClient.java
Java
[ { "context": "y;\n\nimport java.io.IOException;\n\n/**\n * Created by michaelmeyer on 4/23/17.\n */\npublic class DNSClient {\n\n pri", "end": 350, "score": 0.9996132254600525, "start": 338, "tag": "USERNAME", "value": "michaelmeyer" } ]
null
[]
package com.meyermt.dns; import com.fasterxml.jackson.core.JsonProcessingException; import com.mashape.unirest.http.ObjectMapper; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * Created by michaelmeyer on 4/23/17. */ public class DNSClient { private Logger logger = LoggerFactory.getLogger(DNSClient.class); public DNSClient() { setUpMapper(); } public String sendMessage(Message message, Peer peer) { String url = "http://" + peer.getIp() + ":" + peer.getPort() + "/messages"; try { return Unirest.post(url) .body(message.getMessage()) .asString() .getBody(); } catch (UnirestException e) { e.printStackTrace(); // we need to pass back something helpful in this scenario return "Sorry, it appears as though " + peer.getName() + " is not home right now."; } } public String sendMessageThroughSuper(Message message, Superpeer sp) { String url = "http://" + sp.getIp() + ":" + sp.getPort() + "/api/sendthrusuper"; try { return Unirest.post(url) .body(message) .asString() .getBody(); } catch (UnirestException e) { throw new RuntimeException("Unable to send message", e); } } public void sendRegistration(String superIPPort, String fullNodeName, String ip, int port) { try { String url = "http://" + superIPPort + "/api/newnode"; Peer peer = new Peer(0, fullNodeName, ip, port, false); Unirest.post(url) .body(peer) .asString(); } catch (UnirestException e) { throw new RuntimeException("Unable to send message", e); } } // public void disseminateSuperRegistration(List<Superpeer> superpeers) { // superpeers.forEach(superpeer -> { // String url = "http://" + superpeer.getIp() + ":" + superpeer.getPort() + "/api/regsuper"; // logger.info("sending along super reg to: {}", url); // try { // Unirest.post(url) // .body(superpeer) // .asString(); // } catch (UnirestException e) { // throw new RuntimeException("Unable to send along superpeer registration", e); // } // }); // } // // public List<Superpeer> sendSuperRegistration(Superpeer mySuper, String superFriend) { // try { // logger.info("friend is " + superFriend); // logger.info("you are " + mySuper.toString()); // String url = "http://" + superFriend + "/api/newsuper"; // HttpResponse<SPGroup> peers = Unirest.post(url) // .body(mySuper) // .asObject(SPGroup.class); // return peers.getBody().getSps(); // } catch (UnirestException e) { // throw new RuntimeException("Unable to send super registration", e); // } // } private void setUpMapper () { Unirest.setObjectMapper(new ObjectMapper() { private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); public <T> T readValue(String value, Class<T> valueType) { try { return jacksonObjectMapper.readValue(value, valueType); } catch (IOException e) { throw new RuntimeException(e); } } public String writeValue(Object value) { try { return jacksonObjectMapper.writeValueAsString(value); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }); } }
4,077
0.546726
0.544763
112
35.401787
27.807199
103
false
false
0
0
0
0
0
0
0.5
false
false
13
e24065e4287110e4446b3b6095f73de4e3776f6d
34,041,910,851,816
43f885b68c342b6c722abe7f42beafb9a1dca169
/src/test/java/Pages/NavBar/LP2NavBar.java
196cb393b3eaead3e9502c0e706227f89acb0990
[]
no_license
dshiosaky/LearningPlatform
https://github.com/dshiosaky/LearningPlatform
8af4c0f38d8701d20054e19592d7c6cd12f2299b
d7812a35a238a7c69601309bef55d85e16f4e918
refs/heads/master
2020-03-30T02:29:50.574000
2018-10-05T05:11:50
2018-10-05T05:11:50
150,633,611
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Pages.NavBar; import org.openqa.selenium.By; import seleniumControls.Icon; import seleniumControls.Label; import seleniumControls.MenuOption; import seleniumControls.TextBox; public class LP2NavBar { public MenuOption MyProgressMenuOption; public MenuOption TeacherFeedbackMenuoption; public MenuOption ActivitiesMenuoption; public MenuOption UnitAndLessonsMenuOption; public MenuOption PracticeMenuOption; public MenuOption IntroductionMenuOption; public MenuOption LiveChatMenuOption; public MenuOption NotificationsMenuOption; public Icon userProfileIcon; public Label userNameLabel; public MenuOption ContactUsMenuOption; public MenuOption LiveClassSetupMenuOption; public MenuOption LiveClassGuideMenuOption; public MenuOption FAQMenuOption; public MenuOption BillingDetailsMenuOption; public MenuOption ProfileMenuOption; public MenuOption SignOutMenuOption; public LP2NavBar(){ userProfileIcon = new Icon(By.xpath("//a[@id='nav-account']/img[@src='/profile/image/123/123']")); SignOutMenuOption = new MenuOption(By.xpath("//a[@id='nav-logout']")); } }
UTF-8
Java
1,171
java
LP2NavBar.java
Java
[]
null
[]
package Pages.NavBar; import org.openqa.selenium.By; import seleniumControls.Icon; import seleniumControls.Label; import seleniumControls.MenuOption; import seleniumControls.TextBox; public class LP2NavBar { public MenuOption MyProgressMenuOption; public MenuOption TeacherFeedbackMenuoption; public MenuOption ActivitiesMenuoption; public MenuOption UnitAndLessonsMenuOption; public MenuOption PracticeMenuOption; public MenuOption IntroductionMenuOption; public MenuOption LiveChatMenuOption; public MenuOption NotificationsMenuOption; public Icon userProfileIcon; public Label userNameLabel; public MenuOption ContactUsMenuOption; public MenuOption LiveClassSetupMenuOption; public MenuOption LiveClassGuideMenuOption; public MenuOption FAQMenuOption; public MenuOption BillingDetailsMenuOption; public MenuOption ProfileMenuOption; public MenuOption SignOutMenuOption; public LP2NavBar(){ userProfileIcon = new Icon(By.xpath("//a[@id='nav-account']/img[@src='/profile/image/123/123']")); SignOutMenuOption = new MenuOption(By.xpath("//a[@id='nav-logout']")); } }
1,171
0.77199
0.765158
41
27.560976
23.80003
106
false
false
0
0
0
0
0
0
0.609756
false
false
13
a6b1d0f7c4bcca6a0dc4feb001b065bf53d00f69
35,579,509,131,604
82db4d2cd5b3325b40420b405d75cd0fc721eede
/life-program-institute/src/main/java/com/belphegor/lifeprograminstitute/dao/SkillDAO.java
e95e3cce15ead99d4c7c247b920c9eea7029b7ff
[]
no_license
wenwuliu/kotlin-blog
https://github.com/wenwuliu/kotlin-blog
bf0c85c4548611342712119410eeb75d4dd6ff29
1e277b082d1ad12bae846fb7e0d964d377251194
refs/heads/master
2023-01-07T12:36:18.290000
2019-09-24T09:46:20
2019-09-24T09:46:20
206,506,495
0
0
null
false
2023-01-04T10:52:48
2019-09-05T07:51:28
2019-09-24T09:46:45
2023-01-04T10:52:46
1,420
0
0
25
Java
false
false
package com.belphegor.lifeprograminstitute.dao; import com.belphegor.common.mybatis.BaseDAO; import com.belphegor.lifeprograminstitute.dao.mapper.SkillMapper; import com.belphegor.lifeprograminstitute.entity.Skill; import org.springframework.stereotype.Component; @Component public class SkillDAO extends BaseDAO<Skill, SkillMapper> { }
UTF-8
Java
339
java
SkillDAO.java
Java
[]
null
[]
package com.belphegor.lifeprograminstitute.dao; import com.belphegor.common.mybatis.BaseDAO; import com.belphegor.lifeprograminstitute.dao.mapper.SkillMapper; import com.belphegor.lifeprograminstitute.entity.Skill; import org.springframework.stereotype.Component; @Component public class SkillDAO extends BaseDAO<Skill, SkillMapper> { }
339
0.849558
0.849558
10
32.900002
25.410431
65
false
false
0
0
0
0
0
0
0.6
false
false
13
9478cd122b59be3e1cc34c581b3c5b7b3f05358a
24,532,853,226,300
a26d42803f26bab3a9d5a6b8cbf5487c5ad50fda
/src/gui/Catalogos/ImpuestoCatalogo.java
affe49d76a3d576c01477677560f6a5235bbff50
[]
no_license
GAMASH/EON-FASTFOOD
https://github.com/GAMASH/EON-FASTFOOD
20102d3bdbcdcdbd2213012c8f469f0c8da4a462
8085510525a549f0f516352ed76f75bd136dbd3b
refs/heads/master
2021-01-19T07:07:16.349000
2016-10-13T22:25:57
2016-10-13T22:25:57
60,911,636
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui.Catalogos; import abstractt.visual.CatalogoAbstracto; import java.awt.Dimension; /** * * @author Developer GAGS */ public class ImpuestoCatalogo extends CatalogoAbstracto { /** * */ public ImpuestoCatalogo(){ super("Impuestos"); } public void Dimensionar() { Dimension d = new Dimension(); d.height = 500; d.width = 250; this.setSize(d); } }
UTF-8
Java
632
java
ImpuestoCatalogo.java
Java
[ { "context": "cto;\nimport java.awt.Dimension;\n\n/**\n *\n * @author Developer GAGS\n */\npublic class ImpuestoCatalogo extends Ca", "end": 307, "score": 0.8836502432823181, "start": 298, "tag": "NAME", "value": "Developer" }, { "context": "t java.awt.Dimension;\n\n/**\n *\n * @auth...
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui.Catalogos; import abstractt.visual.CatalogoAbstracto; import java.awt.Dimension; /** * * @author Developer GAGS */ public class ImpuestoCatalogo extends CatalogoAbstracto { /** * */ public ImpuestoCatalogo(){ super("Impuestos"); } public void Dimensionar() { Dimension d = new Dimension(); d.height = 500; d.width = 250; this.setSize(d); } }
632
0.626582
0.617089
34
17.588236
19.71431
79
false
false
0
0
0
0
0
0
0.323529
false
false
11
60e1fc792dd61f7f7ab643b1066f7fbdcebbbc20
12,652,973,654,776
719ef5968f972412f29f02508bd3db48f9755359
/src/_02_sea_creature/SpongeBobRunner.java
0572d9735c1b5bc801d882c076e5d8e3a03f1916
[]
no_license
League-Level1-Student/level1-module2-RedHawk1967
https://github.com/League-Level1-Student/level1-module2-RedHawk1967
371f6d8f5179937b6d33aa2e0ed3c160232d9266
9ae81c46dad875d733213d7b913b09bc1f498644
refs/heads/master
2020-05-21T13:18:55.342000
2019-05-25T01:29:31
2019-05-25T01:29:31
186,068,495
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package _02_sea_creature; public class SpongeBobRunner { public static void main(String[] args) { SeaCreature bob = new SeaCreature("SpongeBob"); bob.eat(); bob.laugh(); SeaCreature pat = new SeaCreature("Patrick" ); pat.eat(); pat.laugh(); SeaCreature squ = new SeaCreature("Squidward"); squ.eat(); squ.laugh(); } }
UTF-8
Java
340
java
SpongeBobRunner.java
Java
[ { "context": "g[] args) {\n\t\n\nSeaCreature bob = new SeaCreature(\"SpongeBob\");\nbob.eat();\nbob.laugh();\n\nSeaCreature pat = new", "end": 149, "score": 0.8238720893859863, "start": 140, "tag": "NAME", "value": "SpongeBob" }, { "context": "\nbob.laugh();\n\nSeaCreature pat = new ...
null
[]
package _02_sea_creature; public class SpongeBobRunner { public static void main(String[] args) { SeaCreature bob = new SeaCreature("SpongeBob"); bob.eat(); bob.laugh(); SeaCreature pat = new SeaCreature("Patrick" ); pat.eat(); pat.laugh(); SeaCreature squ = new SeaCreature("Squidward"); squ.eat(); squ.laugh(); } }
340
0.667647
0.661765
36
8.444445
14.744951
47
false
false
0
0
0
0
0
0
0.305556
false
false
11
22db0de1dacab2adb24e4cd9179f1bdb82fe7673
18,786,186,991,406
7be0d44e4cb3faa37e50f3810ecacf541f61a4d5
/framework/framework-base/src/main/java/com/travelzen/framework/net/http/SimpleHttpClient.java
a642bc9b751492e0ce95f809af3762d5c23bcd70
[]
no_license
syzh120/hello-world
https://github.com/syzh120/hello-world
e4135e50a1b87dd1f87ec3d7c28f24a967fb80bb
a39569bb967b98f13ab9553890854167f93a1f74
refs/heads/master
2021-01-11T08:51:56.099000
2016-11-24T02:48:03
2016-11-24T02:48:15
76,549,388
1
3
null
true
2016-12-15T10:19:59
2016-12-15T10:19:59
2016-11-10T07:14:23
2016-11-24T02:50:25
51,921
0
0
0
null
null
null
package com.travelzen.framework.net.http; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SimpleHttpClient { private static Logger logger = LoggerFactory.getLogger(SimpleHttpClient.class); private static PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); private static CloseableHttpClient client = HttpClients.custom().setConnectionManager(cm).build(); public static String get(String url, List<NameValuePair> nameValuePairs) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < nameValuePairs.size(); i++) { buf.append(i == 0 ? "?" : "&"); try { buf.append(nameValuePairs.get(i).getName()).append("=") .append(URLEncoder.encode(nameValuePairs.get(i).getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { logger.error("URL{}编码时发生错误", url, e); } } return getString(url + buf.toString()); } public static String get(String url, NameValuePair[] nameValuePairs) { return get(url, Arrays.asList(nameValuePairs)); } private static String getString(String url) { String result = null; HttpGet getMethod = new HttpGet(url); getMethod.setHeader("Content-Encoding", "UTF-8"); try { HttpResponse response = client.execute(getMethod); result = EntityUtils.toString(response.getEntity()); EntityUtils.consume(response.getEntity()); } catch (IOException e) { logger.error("请求URL{}时发生错误", url, e); } return result; } public static String post(String url, NameValuePair[] nameValuePairs) { return post(url, Arrays.asList(nameValuePairs)); } public static String post(String url, List<NameValuePair> nameValuePairs) { String result = null; HttpPost httpPost = new HttpPost(url); try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); HttpResponse response = client.execute(httpPost); result = EntityUtils.toString(response.getEntity(), "UTF-8"); EntityUtils.consume(response.getEntity()); } catch (IOException e) { logger.error("请求URL{}时发生错误", url, e); } return result; } }
UTF-8
Java
2,704
java
SimpleHttpClient.java
Java
[]
null
[]
package com.travelzen.framework.net.http; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SimpleHttpClient { private static Logger logger = LoggerFactory.getLogger(SimpleHttpClient.class); private static PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); private static CloseableHttpClient client = HttpClients.custom().setConnectionManager(cm).build(); public static String get(String url, List<NameValuePair> nameValuePairs) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < nameValuePairs.size(); i++) { buf.append(i == 0 ? "?" : "&"); try { buf.append(nameValuePairs.get(i).getName()).append("=") .append(URLEncoder.encode(nameValuePairs.get(i).getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { logger.error("URL{}编码时发生错误", url, e); } } return getString(url + buf.toString()); } public static String get(String url, NameValuePair[] nameValuePairs) { return get(url, Arrays.asList(nameValuePairs)); } private static String getString(String url) { String result = null; HttpGet getMethod = new HttpGet(url); getMethod.setHeader("Content-Encoding", "UTF-8"); try { HttpResponse response = client.execute(getMethod); result = EntityUtils.toString(response.getEntity()); EntityUtils.consume(response.getEntity()); } catch (IOException e) { logger.error("请求URL{}时发生错误", url, e); } return result; } public static String post(String url, NameValuePair[] nameValuePairs) { return post(url, Arrays.asList(nameValuePairs)); } public static String post(String url, List<NameValuePair> nameValuePairs) { String result = null; HttpPost httpPost = new HttpPost(url); try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); HttpResponse response = client.execute(httpPost); result = EntityUtils.toString(response.getEntity(), "UTF-8"); EntityUtils.consume(response.getEntity()); } catch (IOException e) { logger.error("请求URL{}时发生错误", url, e); } return result; } }
2,704
0.747558
0.744553
80
32.275002
26.351933
99
false
false
0
0
0
0
0
0
2.0625
false
false
11
c822e04406022a587a53c88824bebf34667f5981
27,187,143,012,007
9a5def2289afa8805e03ca554fb2d740ab7f6bf0
/score-admin-web/src/main/java/com/ptteng/score/admin/controller/ModuleController.java
40bf72d5d7f73d090152ec3d43b4477271de75e9
[]
no_license
angshun/score
https://github.com/angshun/score
c1e117086a70798c75a152857962260a59e809c3
4c0c5ebbfb4cf23854140cb1d6c9ac613db0bef0
refs/heads/master
2021-08-23T04:29:58.438000
2017-12-03T08:14:33
2017-12-03T08:14:36
112,911,260
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ptteng.score.admin.controller; import com.ptteng.score.admin.constant.ConstantItem; import com.ptteng.score.admin.model.Module; import com.ptteng.score.admin.service.ModuleService; import com.ptteng.score.admin.util.ControllerAnnotation; import com.qding.common.util.DataUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Module crud * * @author magenm * @Date 2014-4-16 13:43 * */ @Controller public class ModuleController { private static final Log log = LogFactory.getLog(ModuleController.class); @Autowired private ModuleService moduleService; @Autowired private com.qding.common.util.http.cookie.CookieUtil cookieUtil; /** * 1.新增 * @param request * @param response * @param model * @param module * @return * @throws Exception */ @ControllerAnnotation("092") @RequestMapping(value = "/a/u/module", method = RequestMethod.POST) public String addModuleJson(HttpServletRequest request, HttpServletResponse response, ModelMap model, @RequestBody Module module) throws Exception { log.info("insert module is " + module); if (DataUtils.isNullOrEmpty(module.getName())) { log.error("必填参数有误或为空!"); model.addAttribute("code", -1000); return "common/fail"; } Long adminId = Long.valueOf(cookieUtil.getKeyIdentity(request, com.qding.common.util.http.cookie.CookieUtil.USER_ID)); try { module.setCreateBy(adminId); module.setUpdateBy(adminId); Long id = moduleService.insert(module); log.info("insert module is : " + id); model.addAttribute("code", 0); } catch (Throwable t) { t.printStackTrace(); log.error(t.getMessage()); log.error("add module error "); model.addAttribute("code", -100000); } return "/data/json"; } /** * 2.删除 * @param request * @param response * @param model * @param id * @return * @throws Exception */ @ControllerAnnotation("093") @RequestMapping(value = "/a/u/module/{id}", method = RequestMethod.DELETE) public String deleteModuleJson(HttpServletRequest request, HttpServletResponse response, ModelMap model, @PathVariable Long id) throws Exception { log.info("delete module id : " + id); try { boolean result = moduleService.delete(id); log.info("delete module id result is :" + result); model.addAttribute("code", 0); } catch (Throwable t) { t.printStackTrace(); log.error(t.getMessage()); log.error("delete module error,id is " + id); model.addAttribute("code", -6004); } return "/data/json"; } /** * 3.修改 * @param request * @param response * @param model * @param module * @param id * @return * @throws Exception */ @ControllerAnnotation("091") @RequestMapping(value = "/a/u/module/{id}", method = RequestMethod.PUT) public String updateModuleJson(HttpServletRequest request, HttpServletResponse response, ModelMap model, @RequestBody Module module, @PathVariable Long id) throws Exception { log.info("update module is : " + module); if (DataUtils.isNullOrEmpty(module.getName())) { log.error("必填参数有误或为空!"); model.addAttribute("code", -1000); return "common/fail"; } Long adminId = Long.valueOf(cookieUtil.getKeyIdentity(request, com.qding.common.util.http.cookie.CookieUtil.USER_ID)); try { Module module1 = moduleService.getObjectById(id); log.info("get module1 is :" + module1); module.setCreateAt(module1.getCreateAt()); module.setCreateBy(module1.getCreateBy()); module.setUpdateBy(adminId); module.setId(module1.getId()); boolean result = moduleService.update(module); log.info("update module result is : " + result); model.addAttribute("code", 0); } catch (Throwable t) { t.printStackTrace(); log.error(t.getMessage()); log.error("update module error,id is " + module.getId()); model.addAttribute("code", -100000); } return "/data/json"; } /** * 4.列表 * @param request * @param response * @param model * @param page * @param size * @return * @throws Exception */ @RequestMapping(value = "/a/u/module/list", method = RequestMethod.GET) public String getModuleList(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer page, Integer size) throws Exception { log.info("get param = page is : " + page + " size is : " + size); if (page == null || page <= ConstantItem.ZERO) { page = ConstantItem.ONE; } if (size == null || size <= ConstantItem.ZERO) { size = ConstantItem.FIFTY; } int start = (page - ConstantItem.ONE) * size; if (start < ConstantItem.ZERO) { start = ConstantItem.ZERO; } List<Long> moduleIdList = null; List<Long> count = null; List<Module> moduleList = null; try { moduleIdList = moduleService.getModuleIds(start, size); log.info("get moduleIdList is : " + moduleIdList); count = moduleService.getModuleIds(ConstantItem.ZERO, Integer.MAX_VALUE); log.info("get count is : " + count); moduleList = moduleService.getObjectsByIds(moduleIdList); log.info("get moduleList.size is : " + moduleList.size()); model.addAttribute("code", 0); model.addAttribute("total", count.size()); model.addAttribute("page", page); model.addAttribute("size", size); model.addAttribute("moduleList", moduleList); } catch (Throwable t) { log.error(t.getMessage()); log.error("get module error,id is " + moduleIdList); model.addAttribute("code", -100000); } return "/json/module/json/moduleListJson"; } /** * 5.详情 * @param request * @param response * @param model * @param id * @return * @throws Exception */ @RequestMapping(value = "/a/u/module/{id}", method = RequestMethod.GET) public String getModuleJson(HttpServletRequest request, HttpServletResponse response, ModelMap model, @PathVariable Long id) throws Exception { log.info("get module id is : " + id); try { Module module = moduleService.getObjectById(id); log.info("get module is : " + module); model.addAttribute("code", 0); model.addAttribute("module", module); } catch (Throwable t) { t.printStackTrace(); log.error(t.getMessage()); log.error("get module error,id is " + id); model.addAttribute("code", -100000); } return "/json/module/json/moduleDetailJson"; } /** * 批量获取模块详细信息 * @param request * @param response * @param model * @param ids * @return * @throws Exception */ @RequestMapping(value = "/a/u/multi/module", method = RequestMethod.GET) public String getMultiModuleJson(HttpServletRequest request, HttpServletResponse response, ModelMap model, Long[] ids) throws Exception { log.info("get module mid " + ids); List<Long> idList = new ArrayList(); if (ids == null|| ids.length<=ConstantItem.ZERO) { model.addAttribute("code", 0); model.addAttribute("total", 0); model.addAttribute("size", 10); } else { idList = Arrays.asList(ids); } try { if (idList.size() == 0 || idList.size() <= ConstantItem.ZERO) { model.addAttribute("code", 0); model.addAttribute("total", 0); model.addAttribute("size", 10); } else { List<Module> moduleList = moduleService.getObjectsByIds(idList); log.info("get moduleList data is " + moduleList.size()); if (moduleList.size() != 0 && moduleList.size() > ConstantItem.ZERO) { int totalPage = 0; int totalCnt = moduleList.size(); if (totalCnt > 0) { totalPage = totalCnt / ConstantItem.TEN + ConstantItem.ONE; } model.addAttribute("code", 0); // model.addAttribute("size", 10); model.addAttribute("total", moduleList.size()); model.addAttribute("moduleList", moduleList); } else { model.addAttribute("code", 0); model.addAttribute("total", 0); model.addAttribute("moduleList", moduleList); } } } catch (Throwable t) { log.error(t.getMessage()); log.error("get module error,id is " + Arrays.toString(ids)); model.addAttribute("code", -100000); } return "/json/module/json/moduleListJson"; } /** * 查询模块列表 */ @RequestMapping(value = "/a/u/module/", method = RequestMethod.GET) public String getModuleIdsByTypeJsonList(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer page, Integer size, String type) throws Exception { if (page==null) { page = ConstantItem.ONE; } if (size==null) { size = ConstantItem.FIFTY; } int start = (page - ConstantItem.ONE) * size; if (start < ConstantItem.ZERO) { start = ConstantItem.ZERO; } log.info("pageList : page= " + start + " , size=" + size); try { List<Long> ids=null; List<Long> totalids = new ArrayList<Long>(); Boolean next = false; size+=1; if ((type!=null)&&(!"".equals(type))) { ids= moduleService.getModuleIdsByType(type, start,size); totalids= moduleService.getModuleIdsByType(type, ConstantItem.ZERO, Integer.MAX_VALUE); }else { ids=moduleService.getModuleIds(start,size); totalids=moduleService.getModuleIds(ConstantItem.ZERO, Integer.MAX_VALUE); } log.info("get countModuleIdsByType size is " + ids.size()); if(ids.size()!=0 && ids.size()>0){ if (size.equals(ids.size())) { next = true; log.info("ss "+ids.subList(ConstantItem.ZERO,size-ConstantItem.ONE)); model.addAttribute("ids", ids.subList(ConstantItem.ZERO,size-ConstantItem.ONE)); }else{ log.info("ss "+ids.subList(ConstantItem.ZERO,ids.size())); model.addAttribute("ids", ids.subList(ConstantItem.ZERO, ids.size())); } int totalCnt = totalids.size(); //model.addAttribute("page",page); model.addAttribute("total",totalCnt); }else{ model.addAttribute("ids", ids); } model.addAttribute("code", 0); model.addAttribute("size", size-1); model.addAttribute("page",page); model.addAttribute("next", next); } catch (Throwable t) { t.printStackTrace(); log.error(t.getMessage()); log.error("get module list error,page is " + start + " , size " + size); // for test model.addAttribute("code", -100000); } return "/json/module/json/moduleIdListJson"; } }
UTF-8
Java
10,870
java
ModuleController.java
Java
[ { "context": "ava.util.List;\n\n/**\n * Module crud\n * \n * @author magenm\n * @Date 2014-4-16 13:43\n * \n */\n@Controller\npubl", "end": 987, "score": 0.9996769428253174, "start": 981, "tag": "USERNAME", "value": "magenm" } ]
null
[]
package com.ptteng.score.admin.controller; import com.ptteng.score.admin.constant.ConstantItem; import com.ptteng.score.admin.model.Module; import com.ptteng.score.admin.service.ModuleService; import com.ptteng.score.admin.util.ControllerAnnotation; import com.qding.common.util.DataUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Module crud * * @author magenm * @Date 2014-4-16 13:43 * */ @Controller public class ModuleController { private static final Log log = LogFactory.getLog(ModuleController.class); @Autowired private ModuleService moduleService; @Autowired private com.qding.common.util.http.cookie.CookieUtil cookieUtil; /** * 1.新增 * @param request * @param response * @param model * @param module * @return * @throws Exception */ @ControllerAnnotation("092") @RequestMapping(value = "/a/u/module", method = RequestMethod.POST) public String addModuleJson(HttpServletRequest request, HttpServletResponse response, ModelMap model, @RequestBody Module module) throws Exception { log.info("insert module is " + module); if (DataUtils.isNullOrEmpty(module.getName())) { log.error("必填参数有误或为空!"); model.addAttribute("code", -1000); return "common/fail"; } Long adminId = Long.valueOf(cookieUtil.getKeyIdentity(request, com.qding.common.util.http.cookie.CookieUtil.USER_ID)); try { module.setCreateBy(adminId); module.setUpdateBy(adminId); Long id = moduleService.insert(module); log.info("insert module is : " + id); model.addAttribute("code", 0); } catch (Throwable t) { t.printStackTrace(); log.error(t.getMessage()); log.error("add module error "); model.addAttribute("code", -100000); } return "/data/json"; } /** * 2.删除 * @param request * @param response * @param model * @param id * @return * @throws Exception */ @ControllerAnnotation("093") @RequestMapping(value = "/a/u/module/{id}", method = RequestMethod.DELETE) public String deleteModuleJson(HttpServletRequest request, HttpServletResponse response, ModelMap model, @PathVariable Long id) throws Exception { log.info("delete module id : " + id); try { boolean result = moduleService.delete(id); log.info("delete module id result is :" + result); model.addAttribute("code", 0); } catch (Throwable t) { t.printStackTrace(); log.error(t.getMessage()); log.error("delete module error,id is " + id); model.addAttribute("code", -6004); } return "/data/json"; } /** * 3.修改 * @param request * @param response * @param model * @param module * @param id * @return * @throws Exception */ @ControllerAnnotation("091") @RequestMapping(value = "/a/u/module/{id}", method = RequestMethod.PUT) public String updateModuleJson(HttpServletRequest request, HttpServletResponse response, ModelMap model, @RequestBody Module module, @PathVariable Long id) throws Exception { log.info("update module is : " + module); if (DataUtils.isNullOrEmpty(module.getName())) { log.error("必填参数有误或为空!"); model.addAttribute("code", -1000); return "common/fail"; } Long adminId = Long.valueOf(cookieUtil.getKeyIdentity(request, com.qding.common.util.http.cookie.CookieUtil.USER_ID)); try { Module module1 = moduleService.getObjectById(id); log.info("get module1 is :" + module1); module.setCreateAt(module1.getCreateAt()); module.setCreateBy(module1.getCreateBy()); module.setUpdateBy(adminId); module.setId(module1.getId()); boolean result = moduleService.update(module); log.info("update module result is : " + result); model.addAttribute("code", 0); } catch (Throwable t) { t.printStackTrace(); log.error(t.getMessage()); log.error("update module error,id is " + module.getId()); model.addAttribute("code", -100000); } return "/data/json"; } /** * 4.列表 * @param request * @param response * @param model * @param page * @param size * @return * @throws Exception */ @RequestMapping(value = "/a/u/module/list", method = RequestMethod.GET) public String getModuleList(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer page, Integer size) throws Exception { log.info("get param = page is : " + page + " size is : " + size); if (page == null || page <= ConstantItem.ZERO) { page = ConstantItem.ONE; } if (size == null || size <= ConstantItem.ZERO) { size = ConstantItem.FIFTY; } int start = (page - ConstantItem.ONE) * size; if (start < ConstantItem.ZERO) { start = ConstantItem.ZERO; } List<Long> moduleIdList = null; List<Long> count = null; List<Module> moduleList = null; try { moduleIdList = moduleService.getModuleIds(start, size); log.info("get moduleIdList is : " + moduleIdList); count = moduleService.getModuleIds(ConstantItem.ZERO, Integer.MAX_VALUE); log.info("get count is : " + count); moduleList = moduleService.getObjectsByIds(moduleIdList); log.info("get moduleList.size is : " + moduleList.size()); model.addAttribute("code", 0); model.addAttribute("total", count.size()); model.addAttribute("page", page); model.addAttribute("size", size); model.addAttribute("moduleList", moduleList); } catch (Throwable t) { log.error(t.getMessage()); log.error("get module error,id is " + moduleIdList); model.addAttribute("code", -100000); } return "/json/module/json/moduleListJson"; } /** * 5.详情 * @param request * @param response * @param model * @param id * @return * @throws Exception */ @RequestMapping(value = "/a/u/module/{id}", method = RequestMethod.GET) public String getModuleJson(HttpServletRequest request, HttpServletResponse response, ModelMap model, @PathVariable Long id) throws Exception { log.info("get module id is : " + id); try { Module module = moduleService.getObjectById(id); log.info("get module is : " + module); model.addAttribute("code", 0); model.addAttribute("module", module); } catch (Throwable t) { t.printStackTrace(); log.error(t.getMessage()); log.error("get module error,id is " + id); model.addAttribute("code", -100000); } return "/json/module/json/moduleDetailJson"; } /** * 批量获取模块详细信息 * @param request * @param response * @param model * @param ids * @return * @throws Exception */ @RequestMapping(value = "/a/u/multi/module", method = RequestMethod.GET) public String getMultiModuleJson(HttpServletRequest request, HttpServletResponse response, ModelMap model, Long[] ids) throws Exception { log.info("get module mid " + ids); List<Long> idList = new ArrayList(); if (ids == null|| ids.length<=ConstantItem.ZERO) { model.addAttribute("code", 0); model.addAttribute("total", 0); model.addAttribute("size", 10); } else { idList = Arrays.asList(ids); } try { if (idList.size() == 0 || idList.size() <= ConstantItem.ZERO) { model.addAttribute("code", 0); model.addAttribute("total", 0); model.addAttribute("size", 10); } else { List<Module> moduleList = moduleService.getObjectsByIds(idList); log.info("get moduleList data is " + moduleList.size()); if (moduleList.size() != 0 && moduleList.size() > ConstantItem.ZERO) { int totalPage = 0; int totalCnt = moduleList.size(); if (totalCnt > 0) { totalPage = totalCnt / ConstantItem.TEN + ConstantItem.ONE; } model.addAttribute("code", 0); // model.addAttribute("size", 10); model.addAttribute("total", moduleList.size()); model.addAttribute("moduleList", moduleList); } else { model.addAttribute("code", 0); model.addAttribute("total", 0); model.addAttribute("moduleList", moduleList); } } } catch (Throwable t) { log.error(t.getMessage()); log.error("get module error,id is " + Arrays.toString(ids)); model.addAttribute("code", -100000); } return "/json/module/json/moduleListJson"; } /** * 查询模块列表 */ @RequestMapping(value = "/a/u/module/", method = RequestMethod.GET) public String getModuleIdsByTypeJsonList(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer page, Integer size, String type) throws Exception { if (page==null) { page = ConstantItem.ONE; } if (size==null) { size = ConstantItem.FIFTY; } int start = (page - ConstantItem.ONE) * size; if (start < ConstantItem.ZERO) { start = ConstantItem.ZERO; } log.info("pageList : page= " + start + " , size=" + size); try { List<Long> ids=null; List<Long> totalids = new ArrayList<Long>(); Boolean next = false; size+=1; if ((type!=null)&&(!"".equals(type))) { ids= moduleService.getModuleIdsByType(type, start,size); totalids= moduleService.getModuleIdsByType(type, ConstantItem.ZERO, Integer.MAX_VALUE); }else { ids=moduleService.getModuleIds(start,size); totalids=moduleService.getModuleIds(ConstantItem.ZERO, Integer.MAX_VALUE); } log.info("get countModuleIdsByType size is " + ids.size()); if(ids.size()!=0 && ids.size()>0){ if (size.equals(ids.size())) { next = true; log.info("ss "+ids.subList(ConstantItem.ZERO,size-ConstantItem.ONE)); model.addAttribute("ids", ids.subList(ConstantItem.ZERO,size-ConstantItem.ONE)); }else{ log.info("ss "+ids.subList(ConstantItem.ZERO,ids.size())); model.addAttribute("ids", ids.subList(ConstantItem.ZERO, ids.size())); } int totalCnt = totalids.size(); //model.addAttribute("page",page); model.addAttribute("total",totalCnt); }else{ model.addAttribute("ids", ids); } model.addAttribute("code", 0); model.addAttribute("size", size-1); model.addAttribute("page",page); model.addAttribute("next", next); } catch (Throwable t) { t.printStackTrace(); log.error(t.getMessage()); log.error("get module list error,page is " + start + " , size " + size); // for test model.addAttribute("code", -100000); } return "/json/module/json/moduleIdListJson"; } }
10,870
0.674615
0.66478
403
25.741936
23.708902
120
false
false
0
0
0
0
0
0
2.543424
false
false
11
0e55414526112d41d72dfd3d45410581f10bcfea
33,268,816,693,931
3b48c99f3e84e61d53534ee68115d988805e8355
/JeslieMJ/exemple5/src/com/projet/inter/Personne.java
b1c28d8c109ff44b90d35a8238714f3125628e84
[]
no_license
manelBHM/EPEC_Alt
https://github.com/manelBHM/EPEC_Alt
5c631e1e7080364722ab418c337722f389d09032
75df0667ad0caeed015b40cf2780dc2acb0f40ff
refs/heads/master
2023-01-12T23:12:30.926000
2019-07-07T11:01:30
2019-07-07T11:01:30
180,750,372
1
1
null
false
2023-01-07T20:59:41
2019-04-11T08:39:32
2019-07-07T11:01:51
2023-01-07T20:59:40
300,070
0
0
67
JavaScript
false
false
package com.projet.inter; import java.util.Date; public class Personne { private String nom; private Date dateNais; private double salaire; public profil profil ; public profil getProfil() { return profil; } public void setProfil(profil profil) { this.profil = profil; } public Personne(String nom, Date dateNais, int salaire, profil profil) { // TODO Auto-generated constructor stub this.nom =nom; this.dateNais = dateNais; this.salaire = salaire; this.profil=profil; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public Date getDateNais() { return dateNais; } public void setDateNais(Date dateNais) { this.dateNais = dateNais; } public double getSalaire() { return salaire; } public void setSalaire(double salaire) { this.salaire = salaire; } double calculerSalaire() { //double code; if( profil.getLibelle().equals("DIR")) salaire = (this.salaire*0.1) + this.salaire; else if(profil.getLibelle().equals("DIR")) salaire = (this.salaire*0.2)+ this.salaire; return salaire;} public void affiche() { System.out.println("Je m'appelle " + this.nom+". Je suis né le "+this.dateNais+". Mon salaire est de "+ calculerSalaire()); } }
UTF-8
Java
1,325
java
Personne.java
Java
[]
null
[]
package com.projet.inter; import java.util.Date; public class Personne { private String nom; private Date dateNais; private double salaire; public profil profil ; public profil getProfil() { return profil; } public void setProfil(profil profil) { this.profil = profil; } public Personne(String nom, Date dateNais, int salaire, profil profil) { // TODO Auto-generated constructor stub this.nom =nom; this.dateNais = dateNais; this.salaire = salaire; this.profil=profil; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public Date getDateNais() { return dateNais; } public void setDateNais(Date dateNais) { this.dateNais = dateNais; } public double getSalaire() { return salaire; } public void setSalaire(double salaire) { this.salaire = salaire; } double calculerSalaire() { //double code; if( profil.getLibelle().equals("DIR")) salaire = (this.salaire*0.1) + this.salaire; else if(profil.getLibelle().equals("DIR")) salaire = (this.salaire*0.2)+ this.salaire; return salaire;} public void affiche() { System.out.println("Je m'appelle " + this.nom+". Je suis né le "+this.dateNais+". Mon salaire est de "+ calculerSalaire()); } }
1,325
0.654079
0.651057
81
15.345679
20.163015
130
false
false
0
0
0
0
0
0
1.234568
false
false
11
ce2d38d7355547887db46cf6ec51dbba8159fe2c
31,439,160,653,666
bd3bfd2f1fc2f058180f97a692dac6577b0c85f5
/agencia/src/main/java/br/edu/univas/agencia/restaurante/RestaurantListTO.java
732f3d93d647feb2260f82eaf4240e5ee7678e71
[]
no_license
rrocharoberto/AgenciaDeViagens
https://github.com/rrocharoberto/AgenciaDeViagens
9e4b27160bba85cf99d9ff0a5ab255d310eb693f
564c8de811ce1a01a33753f5e3c17e6e9d390876
refs/heads/master
2023-06-09T20:05:03.810000
2021-06-04T21:45:05
2021-06-04T21:45:05
43,336,993
1
2
null
false
2023-05-23T20:18:01
2015-09-29T01:18:04
2021-06-04T21:45:09
2023-05-23T20:18:00
7,524
0
1
6
CSS
false
false
package br.edu.univas.agencia.restaurante; import br.edu.univas.agencia.model.Restaurante; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class RestaurantListTO { private List<Restaurante> restaurantList = new ArrayList<Restaurante>(); public RestaurantListTO() { } public List<Restaurante> getRestaurantList() { return restaurantList; } public void setRestaurantList(List<Restaurante> cityList) { this.restaurantList = cityList; } }
UTF-8
Java
561
java
RestaurantListTO.java
Java
[]
null
[]
package br.edu.univas.agencia.restaurante; import br.edu.univas.agencia.model.Restaurante; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class RestaurantListTO { private List<Restaurante> restaurantList = new ArrayList<Restaurante>(); public RestaurantListTO() { } public List<Restaurante> getRestaurantList() { return restaurantList; } public void setRestaurantList(List<Restaurante> cityList) { this.restaurantList = cityList; } }
561
0.73975
0.73975
24
22.375
22.696939
76
false
false
0
0
0
0
0
0
0.333333
false
false
11
2ccebb0c316017935bbc65132479b687d4c4ac99
16,793,322,156,536
54f95f70103b831098ec2b4167b7d7124264e87d
/DocJavaParaTraduzir/javafx-src/com/sun/javafx/scene/control/behavior/ProgressBarBehavior.java
6750691ba8ed4e4c6734c9ca386101990b9dfe38
[]
no_license
FaustoCouto/MeuGit
https://github.com/FaustoCouto/MeuGit
ec73dd303ee5160edfa5378f4abddb35a8c5e4c5
035b35165a0884cea13dcd2deb023fc73452e46f
refs/heads/master
2016-03-10T20:35:54.387000
2015-04-16T11:15:28
2015-04-16T11:15:28
33,222,726
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.javafx.scene.control.behavior; import javafx.scene.control.ProgressBar; import java.util.Collections; public class ProgressBarBehavior<C extends ProgressBar> extends BehaviorBase<C> { /*************************************************************************** * * * Constructors * * * **************************************************************************/ public ProgressBarBehavior(final C progress) { super(progress, Collections.EMPTY_LIST); } }
UTF-8
Java
935
java
ProgressBarBehavior.java
Java
[]
null
[]
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.javafx.scene.control.behavior; import javafx.scene.control.ProgressBar; import java.util.Collections; public class ProgressBarBehavior<C extends ProgressBar> extends BehaviorBase<C> { /*************************************************************************** * * * Constructors * * * **************************************************************************/ public ProgressBarBehavior(final C progress) { super(progress, Collections.EMPTY_LIST); } }
935
0.391444
0.382888
43
20.744186
30.652662
81
false
false
0
0
0
0
0
0
0.162791
false
false
11
ec0ab2620a86154d2dc5d58892b1513bed62e475
7,834,020,352,246
6104534621f798fd3d51e258cde230a9a601cb28
/JavaDynamicAnalyzer/src/org/javadynamicanalyzer/timer/BetterLinkedList.java
67ac36e0d500dde6691b0c01fe5abd0d0fc1dffc
[]
no_license
jasonz88/jdatest
https://github.com/jasonz88/jdatest
2363d26ecaeb9f0afee4afd6eb7242c728772ede
7534720f743beebafe075a897db2cd97a82267cf
refs/heads/master
2020-05-17T00:32:11.915000
2013-05-06T05:36:00
2013-05-06T05:36:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.javadynamicanalyzer.timer; import java.util.Collection; import java.util.Iterator; public class BetterLinkedList<T> implements Collection<T>{ class Node { T e=null; Node next=null; Node prev=null; Node(){} Node(T e, Node next, Node prev){ this.e=e; this.next=next; this.prev=prev; } } int size=0; Node head; //will be an invalid node at the head of the list Node last; //will be an invalid node at the end of the list to make sure end iterators don't fall off public BetterLinkedList(){ head=new Node(); last=new Node(); head.next=last; last.prev=head; } public boolean add(T e){ last.e=e; //set this node's element to the new item last.next=new Node(); //make a new node last.next.prev=last; //link the new node to the old node last=last.next; //go to the new node ++size; return true; } public void addLast(T e){ add(e); } public void addFirst(T e){ Node n=new Node(); n.e=e; head.prev=n; n.next=head; head=n; ++size; } public void pop(){ last=last.prev; last.next=null; last.e=null; } public void popLast(){ pop(); } public void popFirst(){ head=head.next; head.prev=null; head.e=null; } public T getFirst(){ return head.next.e; } public T getLast(){ return last.prev.e; } class iterator implements Iterator<T>{ Node current; iterator(Node n){ current=n; } //standard public boolean hasNext(){ return current.next!=last; } public T next(){ current=current.next; return current.e; } public void remove(){ if(current==head || current==last) return; current.e=null; current.prev.next=current.next; current.next.prev=current.prev; current=current.next; --size; } //better stuff public boolean hasPrev(){ return isValid() && current.prev!=null; } public T prev(){ current=current.prev; return current.e; } public T deref(){ return current.e; } public void insert(T e){ Node newNode=new Node(); newNode.e=e; newNode.prev=current; newNode.next=current.next; current.next=newNode; newNode.next.prev=newNode; ++size; } public void insertNext(T e){ insert(e); } public void insertPrev(T e){ assert(current!=head); iterator itr=new iterator(current.prev); itr.insertNext(e); } public iterator clone(){ return new iterator(current); } public boolean isValid(){ return current.e!=null; } public boolean equals(Object o){ return false; } public boolean equals(BetterLinkedList<T>.iterator itr){ return this.current==itr.current; } } @Override public Iterator<T> iterator(){ return new iterator(head); } public iterator begin() { return new iterator(head); } public iterator end() { return new iterator(last); } public iterator last(){ return new iterator(last.prev); } //Container Stuff @Override public boolean addAll(Collection<? extends T> collection) { for(T e : collection) addLast(e); return true; } @Override public boolean contains(Object o) { for(Object obj : this) if(obj.equals(o)) return true; return false; } @Override public boolean containsAll(Collection<?> collection) { for(Object that : collection) if(contains(that)==false) return false; return true; } @Override public boolean isEmpty() { return size==0; } @Override public boolean remove(Object obj) { iterator itr=new iterator(head); while(itr.hasNext()){ if(itr.next().equals(obj)){ itr.remove(); return true; } } return false; } @Override public boolean removeAll(Collection<?> collection) { boolean out=false; for(Object o : collection) out|=remove(o); return out; } @Override public boolean retainAll(Collection<?> collection) { boolean out=false; iterator itr=new iterator(head); while(itr.hasNext()){ if(collection.contains((Object)itr.next())==false){ itr.remove(); out=true; } } return out; } @Override public int size() { return size; } @Override public Object[] toArray() { if(size==0) return null; Object[] oarr=new Object[size]; int count=0; for(Object o : this) oarr[count++]=o; return oarr; } @SuppressWarnings({ "hiding", "unchecked" }) @Override public <T> T[] toArray(T[] arg0) { return (T[])toArray(); } @Override public void clear() { head=new Node(); last=head; size=0; } }
UTF-8
Java
4,542
java
BetterLinkedList.java
Java
[]
null
[]
package org.javadynamicanalyzer.timer; import java.util.Collection; import java.util.Iterator; public class BetterLinkedList<T> implements Collection<T>{ class Node { T e=null; Node next=null; Node prev=null; Node(){} Node(T e, Node next, Node prev){ this.e=e; this.next=next; this.prev=prev; } } int size=0; Node head; //will be an invalid node at the head of the list Node last; //will be an invalid node at the end of the list to make sure end iterators don't fall off public BetterLinkedList(){ head=new Node(); last=new Node(); head.next=last; last.prev=head; } public boolean add(T e){ last.e=e; //set this node's element to the new item last.next=new Node(); //make a new node last.next.prev=last; //link the new node to the old node last=last.next; //go to the new node ++size; return true; } public void addLast(T e){ add(e); } public void addFirst(T e){ Node n=new Node(); n.e=e; head.prev=n; n.next=head; head=n; ++size; } public void pop(){ last=last.prev; last.next=null; last.e=null; } public void popLast(){ pop(); } public void popFirst(){ head=head.next; head.prev=null; head.e=null; } public T getFirst(){ return head.next.e; } public T getLast(){ return last.prev.e; } class iterator implements Iterator<T>{ Node current; iterator(Node n){ current=n; } //standard public boolean hasNext(){ return current.next!=last; } public T next(){ current=current.next; return current.e; } public void remove(){ if(current==head || current==last) return; current.e=null; current.prev.next=current.next; current.next.prev=current.prev; current=current.next; --size; } //better stuff public boolean hasPrev(){ return isValid() && current.prev!=null; } public T prev(){ current=current.prev; return current.e; } public T deref(){ return current.e; } public void insert(T e){ Node newNode=new Node(); newNode.e=e; newNode.prev=current; newNode.next=current.next; current.next=newNode; newNode.next.prev=newNode; ++size; } public void insertNext(T e){ insert(e); } public void insertPrev(T e){ assert(current!=head); iterator itr=new iterator(current.prev); itr.insertNext(e); } public iterator clone(){ return new iterator(current); } public boolean isValid(){ return current.e!=null; } public boolean equals(Object o){ return false; } public boolean equals(BetterLinkedList<T>.iterator itr){ return this.current==itr.current; } } @Override public Iterator<T> iterator(){ return new iterator(head); } public iterator begin() { return new iterator(head); } public iterator end() { return new iterator(last); } public iterator last(){ return new iterator(last.prev); } //Container Stuff @Override public boolean addAll(Collection<? extends T> collection) { for(T e : collection) addLast(e); return true; } @Override public boolean contains(Object o) { for(Object obj : this) if(obj.equals(o)) return true; return false; } @Override public boolean containsAll(Collection<?> collection) { for(Object that : collection) if(contains(that)==false) return false; return true; } @Override public boolean isEmpty() { return size==0; } @Override public boolean remove(Object obj) { iterator itr=new iterator(head); while(itr.hasNext()){ if(itr.next().equals(obj)){ itr.remove(); return true; } } return false; } @Override public boolean removeAll(Collection<?> collection) { boolean out=false; for(Object o : collection) out|=remove(o); return out; } @Override public boolean retainAll(Collection<?> collection) { boolean out=false; iterator itr=new iterator(head); while(itr.hasNext()){ if(collection.contains((Object)itr.next())==false){ itr.remove(); out=true; } } return out; } @Override public int size() { return size; } @Override public Object[] toArray() { if(size==0) return null; Object[] oarr=new Object[size]; int count=0; for(Object o : this) oarr[count++]=o; return oarr; } @SuppressWarnings({ "hiding", "unchecked" }) @Override public <T> T[] toArray(T[] arg0) { return (T[])toArray(); } @Override public void clear() { head=new Node(); last=head; size=0; } }
4,542
0.632321
0.631
199
20.824121
17.788094
102
false
false
0
0
0
0
0
0
2.341709
false
false
11
d4fe1db7e65c3345a339951e566fbc890a84d3cc
4,217,657,931,252
42af4d8d8be42263aec3eb120593c4e4f9fc234b
/TimeSheet/src/br/ts/Begin.java
9183533a0b908133d2460169b790a22165ff6da0
[]
no_license
nfleorj/repo02
https://github.com/nfleorj/repo02
769604915eafb779a175906d123a001065e77ca9
902ebeaf21070c0dd67b46fd7c72195965751ffb
refs/heads/master
2020-03-14T12:33:40.359000
2018-04-30T16:06:17
2018-04-30T16:06:17
131,614,464
0
0
null
false
2018-04-30T16:11:20
2018-04-30T15:42:24
2018-04-30T16:06:56
2018-04-30T16:10:54
0
0
0
1
Java
false
null
package br.ts; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; public class Begin { private static String INICIO_PERIODO = "23/12/2017"; private static String ENTRADA = "Hora de entrada não preenchida"; private static String SAIDA = "Hora de saída não preenchida"; private static String SAIDA_ALMOCO = "Hora de saída almoço não preenchida"; private static String RETORNO_ALMOCO = "Hora de retorno almoço não preenchida"; private static String MENOS_HORAS = "Dia encerrado com menos horas de trabalho"; private static String NENHUMA_TAREFA = "Nenhuma tarefa apontada"; private static String FILE_MANIFEST = "C:/!/TS/manifest.txt"; private static String FILE_TIME = "C:/!/TS/time.txt"; // JDBC driver name and database URL private static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final String DB_URL = "jdbc:oracle:thin:@223.223.2.143:1521:des_amil"; // Database credentials private static final String USER = "ts_ger"; private static final String PASS = "ts_ger"; public static void main(String[] args) { // TODO Auto-generated method stub try { // create file System.out.println("Creating file... "); File f = createFile("C:/!/TS/ts.csv"); System.out.println("File created."); // read manifest String lines = readManifest(FILE_MANIFEST); // write on file writeOnFile(f, lines); } catch (Exception e) { e.printStackTrace(); } } /** * * @param nameFile * @return * @throws IOException */ private static File createFile(String nameFile) throws IOException { File file = new File(nameFile); try { file.createNewFile(); if(file.isFile()){ System.out.println(">> File created susseful."); } } catch (Exception e) { throw new IOException(e.getMessage()); } return file; } /** * * @param date * @param action * @return * @throws IOException */ private static String readFile(String date, String action) throws IOException { date = date.substring(8,10)+'/'+date.substring(5,7)+'/'+date.substring(0,4); BufferedReader br = new BufferedReader(new FileReader(FILE_TIME)); String line = br.readLine(); String hour = ""; String time = ""; try { while (line != null) { if(line.contains(date) && action.equals("entrada")){ hour = line.substring(11,16)+":00"; return hour; }else if(line.contains(date) && action.equals("almoco")){ hour = line.substring(17,22)+":00"; return hour; }else if(line.contains(date) && action.equals("tempo")){ time = line.substring(29,33)+":00"; return time; }else if(line.contains(date) && action.equals("saida")){ hour = line.substring(34,39)+":00"; return hour; } line = br.readLine(); } } catch (Exception e) { throw new IOException(e.getMessage()); }finally{ br.close(); } return null; } /** * * @param manifest * @return * @throws IOException */ private static String readManifest(String manifest) throws IOException { System.out.println("Begin reading manifest.txt..."); BufferedReader br = new BufferedReader(new FileReader(manifest)); StringBuilder sb = new StringBuilder(); String line = br.readLine(); int i = 1; try { while (line != null) { System.out.println("Reading line "+i+"... "); line = createLines(line); if(line != null){ sb.append(line); sb.append(System.lineSeparator()); } line = br.readLine(); i++; } System.out.println(sb.length()); System.out.println(sb.toString()); } catch (Exception e) { throw new IOException("Erro ao ler arquivo de horas na linha: "+ line); }finally{ br.close(); } return sb.toString(); } /** * * @param file * @param lines * @throws IOException */ private static void writeOnFile(File file, String lines) throws IOException { PrintWriter writer = new PrintWriter(file, "UTF-8"); try { writer.println("Email,Client,Project,Description,Start date,Start time,Duration,Tags"); writer.println(lines); } catch (Exception e) { throw new IOException(e.getMessage()); } finally{ writer.close(); } } /** * * @param line * @return * @throws IOException */ private static String createLines(String line) throws IOException { try { String dateToggle = "20"+line.substring(6,8)+"-"+line.substring(3,5)+"-"+line.substring(0,2); String hour = ""; String time = "00:00:00"; if(line.contains(ENTRADA)){ hour = ','+readFile(dateToggle, "entrada"); time = ",00:00:00"; line = "leonardo.nascimento@topdown.com.br,AMIL,FABRICA AMIL,ENTRADA,"+dateToggle+hour+time+','; }else if(line.contains(SAIDA)){ hour = ','+readFile(dateToggle, "saida"); time = ",00:00:00"; line = "leonardo.nascimento@topdown.com.br,AMIL,FABRICA AMIL,SAIDA,"+dateToggle+hour+time+','; }else if(line.contains(SAIDA_ALMOCO)){ hour = ','+readFile(dateToggle, "almoco"); time = ','+readFile(dateToggle, "tempo"); line = "leonardo.nascimento@topdown.com.br,AMIL,FABRICA AMIL,ALMOCO,"+dateToggle+hour+time+','; }else if(line.contains(RETORNO_ALMOCO)){ line = null; }else if(line.contains(MENOS_HORAS)){ line = null; // line = "leonardo.nascimento@topdown.com.br,AMIL,FABRICA AMIL,Avaliando CL / Acompanhando desenvolvimento / correção,"+dateToggle+",15:00:00,01:00:00,CL00003734"; }else if(line.contains(NENHUMA_TAREFA)){ line = getLineChamados(dateToggle, conn()); } } catch (Exception e) { throw new IOException(e.getMessage()); } return line; } /** * * @param dateToggle * @param conn * @return */ private static String getLineChamados(String dateToggle, Connection conn) throws SQLException { // 2017-12-26 // 0123456789 String dateConsulta = dateToggle.substring(8,10)+'/'+dateToggle.substring(5,7)+'/'+dateToggle.substring(0,4); String line = "leonardo.nascimento@topdown.com.br,AMIL,FABRICA AMIL,Acompanhando correção / distribuição,"+dateToggle+",11:00:00,01:00:00,SD"; try { String numChamado = ""; PreparedStatement stmt = null; String qry = "select gce2.num_chamado, trunc(gce2.dt_abertura)" + " from ts_ger.ger_chamado_ext gce2" + " where gce2.num_chamado in" + " (select gceh.num_chamado" + " from ts_ger.ger_chamado_ext gce, ts_ger.ger_chamado_ext_hist gceh" + " where (gce.nom_categoria_modulo like '%DENTAL%' or" + " gce.nom_categoria_modulo like '%ODONTO%')" + " and gce.dt_abertura >= '"+INICIO_PERIODO+"'" + " and gceh.num_chamado = gce.num_chamado" + " and gceh.ind_grupo_acao = 'N3'" + " group by gceh.num_chamado)" + " and trunc(gce2.dt_abertura) = '"+dateConsulta+"'" + " order by gce2.dt_abertura"; stmt = conn.prepareStatement(qry); ResultSet rs = stmt.executeQuery(qry); while (rs.next()) { numChamado = rs.getString("NUM_CHAMADO"); if(!numChamado.equals("")){ line = line+numChamado; }else{ line = null; } } } catch (Exception e) { e.printStackTrace(); }finally{ conn.close(); System.out.println("Connection closed..."); } return line; } /** * * @return * @throws SQLException */ private static Connection conn() throws SQLException { Connection conn = null; try { //STEP 2: Register JDBC driver Class.forName(JDBC_DRIVER); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); } catch (Exception e) { e.printStackTrace(); } return conn; } }
ISO-8859-1
Java
8,250
java
Begin.java
Java
[ { "context": "e static final String DB_URL = \"jdbc:oracle:thin:@223.223.2.143:1521:des_amil\";\n\n // Database credentials\n ", "end": 1195, "score": 0.9935442209243774, "start": 1182, "tag": "IP_ADDRESS", "value": "223.223.2.143" }, { "context": "edentials\n private static...
null
[]
package br.ts; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; public class Begin { private static String INICIO_PERIODO = "23/12/2017"; private static String ENTRADA = "Hora de entrada não preenchida"; private static String SAIDA = "Hora de saída não preenchida"; private static String SAIDA_ALMOCO = "Hora de saída almoço não preenchida"; private static String RETORNO_ALMOCO = "Hora de retorno almoço não preenchida"; private static String MENOS_HORAS = "Dia encerrado com menos horas de trabalho"; private static String NENHUMA_TAREFA = "Nenhuma tarefa apontada"; private static String FILE_MANIFEST = "C:/!/TS/manifest.txt"; private static String FILE_TIME = "C:/!/TS/time.txt"; // JDBC driver name and database URL private static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final String DB_URL = "jdbc:oracle:thin:@172.16.17.32:1521:des_amil"; // Database credentials private static final String USER = "ts_ger"; private static final String PASS = "<PASSWORD>"; public static void main(String[] args) { // TODO Auto-generated method stub try { // create file System.out.println("Creating file... "); File f = createFile("C:/!/TS/ts.csv"); System.out.println("File created."); // read manifest String lines = readManifest(FILE_MANIFEST); // write on file writeOnFile(f, lines); } catch (Exception e) { e.printStackTrace(); } } /** * * @param nameFile * @return * @throws IOException */ private static File createFile(String nameFile) throws IOException { File file = new File(nameFile); try { file.createNewFile(); if(file.isFile()){ System.out.println(">> File created susseful."); } } catch (Exception e) { throw new IOException(e.getMessage()); } return file; } /** * * @param date * @param action * @return * @throws IOException */ private static String readFile(String date, String action) throws IOException { date = date.substring(8,10)+'/'+date.substring(5,7)+'/'+date.substring(0,4); BufferedReader br = new BufferedReader(new FileReader(FILE_TIME)); String line = br.readLine(); String hour = ""; String time = ""; try { while (line != null) { if(line.contains(date) && action.equals("entrada")){ hour = line.substring(11,16)+":00"; return hour; }else if(line.contains(date) && action.equals("almoco")){ hour = line.substring(17,22)+":00"; return hour; }else if(line.contains(date) && action.equals("tempo")){ time = line.substring(29,33)+":00"; return time; }else if(line.contains(date) && action.equals("saida")){ hour = line.substring(34,39)+":00"; return hour; } line = br.readLine(); } } catch (Exception e) { throw new IOException(e.getMessage()); }finally{ br.close(); } return null; } /** * * @param manifest * @return * @throws IOException */ private static String readManifest(String manifest) throws IOException { System.out.println("Begin reading manifest.txt..."); BufferedReader br = new BufferedReader(new FileReader(manifest)); StringBuilder sb = new StringBuilder(); String line = br.readLine(); int i = 1; try { while (line != null) { System.out.println("Reading line "+i+"... "); line = createLines(line); if(line != null){ sb.append(line); sb.append(System.lineSeparator()); } line = br.readLine(); i++; } System.out.println(sb.length()); System.out.println(sb.toString()); } catch (Exception e) { throw new IOException("Erro ao ler arquivo de horas na linha: "+ line); }finally{ br.close(); } return sb.toString(); } /** * * @param file * @param lines * @throws IOException */ private static void writeOnFile(File file, String lines) throws IOException { PrintWriter writer = new PrintWriter(file, "UTF-8"); try { writer.println("Email,Client,Project,Description,Start date,Start time,Duration,Tags"); writer.println(lines); } catch (Exception e) { throw new IOException(e.getMessage()); } finally{ writer.close(); } } /** * * @param line * @return * @throws IOException */ private static String createLines(String line) throws IOException { try { String dateToggle = "20"+line.substring(6,8)+"-"+line.substring(3,5)+"-"+line.substring(0,2); String hour = ""; String time = "00:00:00"; if(line.contains(ENTRADA)){ hour = ','+readFile(dateToggle, "entrada"); time = ",00:00:00"; line = "<EMAIL>,AMIL,FABRICA AMIL,ENTRADA,"+dateToggle+hour+time+','; }else if(line.contains(SAIDA)){ hour = ','+readFile(dateToggle, "saida"); time = ",00:00:00"; line = "<EMAIL>,AMIL,FABRICA AMIL,SAIDA,"+dateToggle+hour+time+','; }else if(line.contains(SAIDA_ALMOCO)){ hour = ','+readFile(dateToggle, "almoco"); time = ','+readFile(dateToggle, "tempo"); line = "<EMAIL>,AMIL,FABRICA AMIL,ALMOCO,"+dateToggle+hour+time+','; }else if(line.contains(RETORNO_ALMOCO)){ line = null; }else if(line.contains(MENOS_HORAS)){ line = null; // line = "<EMAIL>,AMIL,FAB<NAME>,Avaliando CL / Acompanhando desenvolvimento / correção,"+dateToggle+",15:00:00,01:00:00,CL00003734"; }else if(line.contains(NENHUMA_TAREFA)){ line = getLineChamados(dateToggle, conn()); } } catch (Exception e) { throw new IOException(e.getMessage()); } return line; } /** * * @param dateToggle * @param conn * @return */ private static String getLineChamados(String dateToggle, Connection conn) throws SQLException { // 2017-12-26 // 0123456789 String dateConsulta = dateToggle.substring(8,10)+'/'+dateToggle.substring(5,7)+'/'+dateToggle.substring(0,4); String line = "<EMAIL>,AMIL,<NAME>,Acompanhando correção / distribuição,"+dateToggle+",11:00:00,01:00:00,SD"; try { String numChamado = ""; PreparedStatement stmt = null; String qry = "select gce2.num_chamado, trunc(gce2.dt_abertura)" + " from ts_ger.ger_chamado_ext gce2" + " where gce2.num_chamado in" + " (select gceh.num_chamado" + " from ts_ger.ger_chamado_ext gce, ts_ger.ger_chamado_ext_hist gceh" + " where (gce.nom_categoria_modulo like '%DENTAL%' or" + " gce.nom_categoria_modulo like '%ODONTO%')" + " and gce.dt_abertura >= '"+INICIO_PERIODO+"'" + " and gceh.num_chamado = gce.num_chamado" + " and gceh.ind_grupo_acao = 'N3'" + " group by gceh.num_chamado)" + " and trunc(gce2.dt_abertura) = '"+dateConsulta+"'" + " order by gce2.dt_abertura"; stmt = conn.prepareStatement(qry); ResultSet rs = stmt.executeQuery(qry); while (rs.next()) { numChamado = rs.getString("NUM_CHAMADO"); if(!numChamado.equals("")){ line = line+numChamado; }else{ line = null; } } } catch (Exception e) { e.printStackTrace(); }finally{ conn.close(); System.out.println("Connection closed..."); } return line; } /** * * @return * @throws SQLException */ private static Connection conn() throws SQLException { Connection conn = null; try { //STEP 2: Register JDBC driver Class.forName(JDBC_DRIVER); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); } catch (Exception e) { e.printStackTrace(); } return conn; } }
8,109
0.626032
0.608184
313
25.316294
26.528042
168
false
false
0
0
0
0
0
0
2.738019
false
false
11
92f73e8770d88c2029cdbb21781a435394116b24
32,882,269,664,052
d53b82ee2597b12088a504a2d1e5bd31960578bf
/fapi/src/main/java/com/netcracker/edu/vlad/controllers/HomeController.java
1769c32a2c9788466abcb905bda10cc52411d476
[]
no_license
vladbykovsky/NC-2019-Simple-Charging
https://github.com/vladbykovsky/NC-2019-Simple-Charging
48bbb1ce5e391bc3608983e62c2a73f6322477e1
4b7cca9380ec563cd6cbf14ecf1987b8a77793ee
refs/heads/master
2023-01-10T06:33:49.300000
2019-12-15T13:34:26
2019-12-15T13:34:26
176,020,533
0
0
null
false
2023-01-07T04:31:34
2019-03-16T20:18:40
2019-12-15T13:34:56
2023-01-07T04:31:34
1,599
0
0
31
Java
false
false
package com.netcracker.edu.vlad.controllers; import com.netcracker.edu.vlad.models.Product; import com.netcracker.edu.vlad.service.HomeService; import com.netcracker.edu.vlad.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping("/api") public class HomeController { @Autowired private HomeService homeService; @RequestMapping(value = "", method = RequestMethod.GET) public ResponseEntity<Page<Product>> getAllProducts(@RequestParam int page, @RequestParam int size, @RequestParam String sort, @RequestParam String order){ Page<Product> products = homeService.findAll(page, size, sort, order); if (products.getContent() != null) { return ResponseEntity.ok(products); }else { return ResponseEntity.notFound().build(); } } // @RequestMapping(value = "", method = RequestMethod.GET) // public ResponseEntity<Page<Product>> getAllProducts(@RequestParam int page, // @RequestParam String sort, // @RequestParam String order){ // Page<Product> products = homeService.findAll(page, sort, order); // if (products.getContent() != null) { // return ResponseEntity.ok(products); // }else { // return ResponseEntity.notFound().build(); // } // } @RequestMapping(value = "/search/{name}", method = RequestMethod.GET) public Product getAllByName(@PathVariable(name = "name") String name){ return homeService.findAllByNameStartWith(name); } }
UTF-8
Java
2,267
java
HomeController.java
Java
[]
null
[]
package com.netcracker.edu.vlad.controllers; import com.netcracker.edu.vlad.models.Product; import com.netcracker.edu.vlad.service.HomeService; import com.netcracker.edu.vlad.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping("/api") public class HomeController { @Autowired private HomeService homeService; @RequestMapping(value = "", method = RequestMethod.GET) public ResponseEntity<Page<Product>> getAllProducts(@RequestParam int page, @RequestParam int size, @RequestParam String sort, @RequestParam String order){ Page<Product> products = homeService.findAll(page, size, sort, order); if (products.getContent() != null) { return ResponseEntity.ok(products); }else { return ResponseEntity.notFound().build(); } } // @RequestMapping(value = "", method = RequestMethod.GET) // public ResponseEntity<Page<Product>> getAllProducts(@RequestParam int page, // @RequestParam String sort, // @RequestParam String order){ // Page<Product> products = homeService.findAll(page, sort, order); // if (products.getContent() != null) { // return ResponseEntity.ok(products); // }else { // return ResponseEntity.notFound().build(); // } // } @RequestMapping(value = "/search/{name}", method = RequestMethod.GET) public Product getAllByName(@PathVariable(name = "name") String name){ return homeService.findAllByNameStartWith(name); } }
2,267
0.631231
0.629466
54
40.98148
27.254963
86
false
false
0
0
0
0
0
0
0.666667
false
false
11
2d8d35e121a2a772207948f509b8fa48f3627463
11,836,929,915,474
6d32701a8a6f8386c385c42b30e4e8f5d19cb849
/advanced-search-demo/src/main/java/it/mm/advancedSearch/demo/controllers/CompanyController.java
234c1728f834ddd5a68153cae8b9c3423f05b95b
[]
no_license
MicheleM04/advanced-search
https://github.com/MicheleM04/advanced-search
9ce6116027c0bd166102c45f7ed317336a0f7248
b31da62ef12a2a6d13e891c66d66b019ca3d70a3
refs/heads/master
2020-03-17T21:40:00.704000
2018-05-25T15:24:37
2018-05-25T15:24:37
133,968,639
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.mm.advancedSearch.demo.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort.Direction; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import it.mm.advancedSearch.demo.entities.Company; import it.mm.advancedSearch.demo.repositories.CompanyRepository; @RestController @RequestMapping("company") public class CompanyController { @Autowired private CompanyRepository companyRepository; @GetMapping("") public List<Company> getAll() { return companyRepository.findAll(); } @GetMapping("searchByText") public Page<Company> searchByString(@RequestParam() String searchText) { if (searchText == null) { searchText = ""; } return companyRepository.findByNameContaining(searchText, PageRequest.of(0, 5, Direction.ASC, "name")); } }
UTF-8
Java
1,150
java
CompanyController.java
Java
[]
null
[]
package it.mm.advancedSearch.demo.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort.Direction; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import it.mm.advancedSearch.demo.entities.Company; import it.mm.advancedSearch.demo.repositories.CompanyRepository; @RestController @RequestMapping("company") public class CompanyController { @Autowired private CompanyRepository companyRepository; @GetMapping("") public List<Company> getAll() { return companyRepository.findAll(); } @GetMapping("searchByText") public Page<Company> searchByString(@RequestParam() String searchText) { if (searchText == null) { searchText = ""; } return companyRepository.findByNameContaining(searchText, PageRequest.of(0, 5, Direction.ASC, "name")); } }
1,150
0.803478
0.801739
38
29.263159
24.293907
73
false
false
0
0
0
0
0
0
1.131579
false
false
11
cff2747359be31510d2beedf744c262200c3c570
11,836,929,918,509
ff50eef06b2d2f8149b95d07ed98f8d28546685a
/ServerFXMLController.java
5c9189f3830f622d1ee9f9390a1e3a622f139a9e
[ "MIT" ]
permissive
KazeSoftworks/UDPServerClientJava
https://github.com/KazeSoftworks/UDPServerClientJava
e251923810680b5f0899f86921fb8442f0d41e69
cd3b7da2ab3bf958f4be2de5a8ecd2b64b0e2d16
refs/heads/master
2021-09-08T10:13:50.482000
2018-03-06T05:41:35
2018-03-06T05:41:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URL; import java.util.ArrayList; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.ListView; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; /** * * @author Spellkaze */ public class ServerFXMLController implements Initializable { ArrayList<Message> messageList = new ArrayList<>(); ArrayList<User> userList = new ArrayList<>(); Service<Void> backgroundThread; Message selectedMessage; ArrayList<Message> outMessageList; @FXML private TableColumn<Message, String> ColumnRemitente; @FXML private TableColumn<Message, String> ColumnReceptor; @FXML private TableColumn<Message, String> ColumnMensaje; @FXML private TableColumn<Message, String> ColumnFecha; @FXML private TableColumn<Message, String> ColumnConfirmation; private ObservableList<Message> dataMessage; private ObservableList<User> dataUser; @FXML private TableView<Message> table; DatagramSocket datagramSocket; boolean abortedSending = false; @FXML private ListView<User> UserListTable; @FXML private TextField userField; @FXML private TextField FilterField; @Override public void initialize(URL url, ResourceBundle rb) { try { datagramSocket = new DatagramSocket(5000); } catch (SocketException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } MessageListRead(); UserListRead(); setTableMessagesAll(); //SetUserList(); setUserTableAll(); AwaitingPackets(); UserListWrite(); MessageListWrite(); } public void setTableMessagesAll() { dataMessage = FXCollections.observableArrayList(); dataMessage.addAll(messageList); ColumnRemitente.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getSender())); ColumnReceptor.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getReceiver())); ColumnMensaje.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getMessage())); ColumnFecha.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getDate())); ColumnConfirmation.setCellValueFactory(p -> { if (!p.getValue().getReceivedNotification()) { return new SimpleStringProperty("✓"); //Simbolo positivo } else { return new SimpleStringProperty("✗"); //Simbolo negativo } }); table.setItems(dataMessage); } @FXML public void SelectedUserList() { userField.setText(UserListTable.getSelectionModel().getSelectedItem().getUserName()); } public void setUserTableAll() { dataUser = FXCollections.observableArrayList(); dataUser.addAll(userList); UserListTable.setItems(dataUser); } public void UserListRead() { try { ObjectInputStream archivoIngreso = new ObjectInputStream(new FileInputStream("./user.dat")); userList = (ArrayList<User>) archivoIngreso.readObject(); } catch (FileNotFoundException ex) { System.out.println("No file to read"); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } public void UserListWrite() { try { ObjectOutputStream ArchivoSalida = new ObjectOutputStream(new FileOutputStream("./user.dat", false)); ArchivoSalida.writeObject(userList); } catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } } public void MessageListRead() { try { ObjectInputStream archivoIngreso = new ObjectInputStream(new FileInputStream("./messages.dat")); messageList = (ArrayList<Message>) archivoIngreso.readObject(); } catch (FileNotFoundException ex) { System.out.println("No file to read"); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } } public void MessageListWrite() { try { ObjectOutputStream ArchivoSalida = new ObjectOutputStream(new FileOutputStream("./messages.dat", false)); ArchivoSalida.writeObject(messageList); } catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } } public void ShowAllMesages() { System.out.println(messageList); } private void AwaitingPackets() { backgroundThread = new Service<Void>() { @Override protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { try { while (true) { byte[] buffer = new byte[5000]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); datagramSocket.receive(packet); ByteArrayInputStream inputByteStream = new ByteArrayInputStream(buffer); ObjectInputStream objectInput = new ObjectInputStream(new BufferedInputStream(inputByteStream)); Object obj = objectInput.readObject(); System.out.println(obj.toString()); if (obj instanceof User) { System.out.println("is user request"); User dataObtained = (User) obj; if (SearchListUser(dataObtained)) { Platform.runLater(() -> { ConfirmUserPacket(dataObtained, datagramSocket, packet, "GRANTED"); sendMessageListToUser(dataObtained, datagramSocket, packet); }); } else { Platform.runLater(() -> { ConfirmUserPacket(dataObtained, datagramSocket, packet, "REJECTED"); }); } } else if (obj instanceof Message) { Message dataObtained = (Message) obj; System.out.println("is message request"); ConfirmMessagePacket(dataObtained, datagramSocket, packet); Platform.runLater(() -> { sendMessageListToSender(dataObtained.getSender(), datagramSocket, packet); if (!abortedSending) { try { Thread.sleep(100); sendMessageListToReceiver(dataObtained.getReceiver(), datagramSocket, packet); } catch (InterruptedException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } MessageListWrite(); setTableMessagesAll(); }); } else if (obj instanceof String) { String dataObtained = (String) obj; if (dataObtained.substring(0, 16).equals("TERMINATE_CLIENT")) { String[] parted = dataObtained.split(" "); System.out.println("Terminating client " + parted[1]); ResetUserInfo(parted[1]); } else { System.out.println("Data string obtained incorrectly: " + dataObtained); } } else { System.out.println("Getting unknown object"); System.out.println(obj.toString()); } } } catch (SocketException | SocketTimeoutException ex) { System.out.println("Socket timeoutr"); } catch (IOException ex) { System.out.println("IO error" + ex); } catch (ClassNotFoundException ex) { System.out.println("Class error" + ex); } finally { datagramSocket.setSoTimeout(0); } return null; } }; } }; backgroundThread.restart(); } private void ConfirmUserPacket(User user, DatagramSocket socket, DatagramPacket packet, String confirm) { try { InetAddress address = packet.getAddress(); int port = packet.getPort(); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput = new ObjectOutputStream(new BufferedOutputStream(byteStream)); objectOutput.writeObject(confirm); objectOutput.flush(); byte[] buffer2 = byteStream.toByteArray(); packet = new DatagramPacket(buffer2, buffer2.length, address, port); socket.send(packet); System.out.println("Sending confirmation to: " + address + " " + port + " " + confirm); setUserAddressPort(user, address, port); } catch (SocketException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } private void ConfirmMessagePacket(Message message, DatagramSocket socket, DatagramPacket packet) { abortedSending = false; String sender = message.getSender(); String receiver = message.getReceiver(); String messageGot = message.getMessage(); String date = message.getDate(); InetAddress addressOrigin = packet.getAddress(); int portOrigin = packet.getPort(); try { InetAddress address = null; int port = 0; for (User userOnList : userList) { if (receiver.equals(userOnList.getUserName())) { address = userOnList.getAddress(); port = userOnList.getPort(); } } if (address == null) //SECURITY CHECK PARA IMPOSIBLE DE ENVIAR { System.out.println("Abortar Envio"); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput = new ObjectOutputStream(new BufferedOutputStream(byteStream)); objectOutput.writeObject("NONEXISTANT"); objectOutput.flush(); byte[] buffer2 = byteStream.toByteArray(); packet = new DatagramPacket(buffer2, buffer2.length, addressOrigin, portOrigin); socket.send(packet); System.out.println("Sending counter to: " + addressOrigin + " " + portOrigin); abortedSending = true; return; } //Send message to receiver ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput = new ObjectOutputStream(new BufferedOutputStream(byteStream)); objectOutput.writeObject(message); objectOutput.flush(); byte[] buffer2 = byteStream.toByteArray(); packet = new DatagramPacket(buffer2, buffer2.length, address, port); socket.send(packet); System.out.println("Sending message to: " + address + " " + port); //Awaiting confirmation from receiver byte[] buffer = new byte[100]; packet = new DatagramPacket(buffer, buffer.length); datagramSocket.setSoTimeout(4000); datagramSocket.receive(packet); ByteArrayInputStream inputByteStream = new ByteArrayInputStream(buffer); ObjectInputStream objectInput = new ObjectInputStream(new BufferedInputStream(inputByteStream)); Object obj = objectInput.readObject(); System.out.println("Recieved confirmation from: " + packet.getAddress() + " " + packet.getPort()); System.out.println(obj.toString()); if (obj.toString().equals("RECEIVED")) { messageList.add(message); System.out.println("Message has been received"); //Send message to sender ByteArrayOutputStream byteStream2 = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput2 = new ObjectOutputStream(new BufferedOutputStream(byteStream2)); objectOutput2.writeObject("RECEIVED"); objectOutput2.flush(); byte[] buffer3 = byteStream2.toByteArray(); packet = new DatagramPacket(buffer3, buffer3.length, addressOrigin, portOrigin); socket.send(packet); System.out.println("Sending confirmation to: " + addressOrigin + " " + portOrigin); Thread.sleep(100); } else { System.out.println("Message has NOT been received"); } } catch (SocketException | SocketTimeoutException ex) { System.out.println("Message has Not been received"); //Send message to sender try { datagramSocket.setSoTimeout(0); ByteArrayOutputStream byteStream2 = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput2 = new ObjectOutputStream(new BufferedOutputStream(byteStream2)); objectOutput2.writeObject("NOTRECEIVED"); objectOutput2.flush(); byte[] buffer3 = byteStream2.toByteArray(); packet = new DatagramPacket(buffer3, buffer3.length, addressOrigin, portOrigin); socket.send(packet); System.out.println("Sending confirmation of not received to: " + addressOrigin + " " + portOrigin); } catch (IOException ex1) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex1); } Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } finally { try { datagramSocket.setSoTimeout(0); } catch (SocketException ex) { //Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } } //#Searching list by username private boolean SearchListUser(User user) { for (User userOnList : userList) { if (user.getUserName().equals(userOnList.getUserName())) { return true; } } return false; } //#Searching list by username private boolean SearchListUser(String user) { for (User userOnList : userList) { if (user.equals(userOnList.getUserName())) { return true; } } return false; } //Asigns adddres and port to user list private void setUserAddressPort(User user, InetAddress address, int port) { for (User userOnList : userList) { if (user.getUserName().equals(userOnList.getUserName())) { userOnList.setAddress(address); userOnList.setPort(port); userOnList.ConnectionEstablished(); System.out.println("Guardando info de cliente: " + userOnList.getUserName() + " " + userOnList.getAddress() + " " + userOnList.getPort()); } } } //Send message list to the respective client private void sendMessageListToUser(User user, DatagramSocket socket, DatagramPacket packet) { outMessageList = new ArrayList<>(); InetAddress address = user.getAddress(); int port = user.getPort(); for (User userOnList : userList) { if (user.getUserName().equals(userOnList.getUserName())) { address = userOnList.getAddress(); port = userOnList.getPort(); } } for (Message messageOnList : messageList) { if (user.getUserName().equals(messageOnList.getSender()) || user.getUserName().equals(messageOnList.getReceiver())) { outMessageList.add(messageOnList); } } try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput = new ObjectOutputStream(new BufferedOutputStream(byteStream)); objectOutput.writeObject(outMessageList); objectOutput.flush(); byte[] buffer2 = byteStream.toByteArray(); packet = new DatagramPacket(buffer2, buffer2.length, address, port); socket.send(packet); System.out.println("Sending message List to: " + address + " " + port); } catch (IOException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } //Send message list, update sender and receiver message list; private void sendMessageListToSender(String sender, DatagramSocket socket, DatagramPacket packet) { outMessageList = new ArrayList<>(); InetAddress address = null; int port = 0; //UPDATE SENDER for (User userOnList : userList) { if (sender.equals(userOnList.getUserName())) { address = userOnList.getAddress(); port = userOnList.getPort(); } } for (Message messageOnList : messageList) { if (sender.equals(messageOnList.getSender()) || sender.equals(messageOnList.getReceiver())) { outMessageList.add(messageOnList); } } try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput = new ObjectOutputStream(new BufferedOutputStream(byteStream)); objectOutput.writeObject(outMessageList); objectOutput.flush(); byte[] buffer2 = byteStream.toByteArray(); packet = new DatagramPacket(buffer2, buffer2.length, address, port); socket.send(packet); System.out.println("Sending message Sender List to: " + address + " " + port); } catch (IOException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } //Send message list, update sender and receiver message list; private void sendMessageListToReceiver(String receiver, DatagramSocket socket, DatagramPacket packet) { outMessageList = new ArrayList<>(); InetAddress address = null; int port = 0; //UPDATE SENDER for (User userOnList : userList) { if (receiver.equals(userOnList.getUserName())) { address = userOnList.getAddress(); port = userOnList.getPort(); } } for (Message messageOnList : messageList) { if (receiver.equals(messageOnList.getSender()) || receiver.equals(messageOnList.getReceiver())) { outMessageList.add(messageOnList); } } try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput = new ObjectOutputStream(new BufferedOutputStream(byteStream)); objectOutput.writeObject(outMessageList); objectOutput.flush(); byte[] buffer2 = byteStream.toByteArray(); packet = new DatagramPacket(buffer2, buffer2.length, address, port); socket.send(packet); System.out.println("Sending message Receiver List to: " + address + " " + port); } catch (IOException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } private void ResetUserInfo(String user) { for (User userOnList : userList) { if (user.equals(userOnList.getUserName())) { userOnList.setAddress(null); userOnList.setPort(0); System.out.println("Terminated " + userOnList.getUserName()); return; } } UserListWrite(); } //#DEBUG private void SetUserList() { userList.add(new User("Waluigi")); userList.add(new User("Espageti")); userList.add(new User("Wario")); } @FXML private void AddUser(ActionEvent event) { String user = userField.getText(); if (!SearchListUser(user) && user.length() > 0) { userList.add(new User(user)); } else { System.out.println("Already added"); } setUserTableAll(); UserListWrite(); } @FXML private void RemoveUser(ActionEvent event) { String user = userField.getText(); if (SearchListUser(user) && user.length() > 0) { for (int i = 0; i < userList.size(); i++) { if (user.equals(userList.get(i).getUserName())) { TerminateClientbyUser(userList.get(i).getUserName()); userList.remove(i); for (int j = 0; j < messageList.size(); j++) { if (messageList.get(j).getSender().equals(user)) { messageList.get(j).setSender("-ELIMINADO-"); } if (messageList.get(j).getReceiver().equals(user)) { messageList.get(j).setReceiver("-ELIMINADO-"); } } } } } else { System.out.println("No user like that"); } System.out.println(messageList); setUserTableAll(); dataMessage.clear(); setTableMessagesAll(); UpdateMessageListToAllConnected(); UserListWrite(); } @FXML private void SelectedMessageList(MouseEvent event) { selectedMessage = table.getSelectionModel().getSelectedItem(); } @FXML private void DeleteMessage(ActionEvent event) { for (int i = 0; i < messageList.size(); i++) { if (messageList.get(i).equals(selectedMessage)) { System.out.println("Found message to get deleted"); messageList.remove(i); UpdateMessageListToAllConnected(); } } setTableMessagesAll(); MessageListWrite(); } @FXML private void FilterMessageListSender(ActionEvent event) { String searchString = FilterField.getText(); ArrayList<Message> filteredMessageList = new ArrayList<>(); ObservableList<Message> dataFilteredMessage; dataFilteredMessage = FXCollections.observableArrayList(); if (searchString.length() > 0) { for (Message messageOnList : messageList) { if (searchString.equals(messageOnList.getSender())) { filteredMessageList.add(messageOnList); } } System.out.println(filteredMessageList); dataFilteredMessage.addAll(filteredMessageList); ColumnRemitente.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getSender())); ColumnReceptor.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getReceiver())); ColumnMensaje.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getMessage())); ColumnFecha.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getDate())); ColumnConfirmation.setCellValueFactory(p -> { if (!p.getValue().getReceivedNotification()) { return new SimpleStringProperty("✓"); //Simbolo positivo } else { return new SimpleStringProperty("✗"); //Simbolo negativo } }); table.setItems(dataFilteredMessage); } else { setTableMessagesAll(); } } @FXML private void FilterMessageListReceiver(ActionEvent event) { String searchString = FilterField.getText(); ArrayList<Message> filteredMessageList = new ArrayList<>(); ObservableList<Message> dataFilteredMessage; dataFilteredMessage = FXCollections.observableArrayList(); if (searchString.length() > 0) { for (Message messageOnList : messageList) { if (searchString.equals(messageOnList.getReceiver())) { filteredMessageList.add(messageOnList); } } System.out.println(filteredMessageList); dataFilteredMessage.addAll(filteredMessageList); ColumnRemitente.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getSender())); ColumnReceptor.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getReceiver())); ColumnMensaje.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getMessage())); ColumnFecha.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getDate())); ColumnConfirmation.setCellValueFactory(p -> { if (!p.getValue().getReceivedNotification()) { return new SimpleStringProperty("✓"); //Simbolo positivo } else { return new SimpleStringProperty("✗"); //Simbolo negativo } }); table.setItems(dataFilteredMessage); } else { setTableMessagesAll(); } } private void TerminateClientbyUser(String user) { InetAddress address = null; int port = 0; //UPDATE SENDER for (User userOnList : userList) { if (user.equals(userOnList.getUserName())) { address = userOnList.getAddress(); port = userOnList.getPort(); System.out.println("Found address"); } } if (address == null) { System.out.println(user + " already terminated"); return; } try { ByteArrayOutputStream byteStream2 = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput2 = new ObjectOutputStream(new BufferedOutputStream(byteStream2)); objectOutput2.writeObject("TERMINATE"); objectOutput2.flush(); byte[] buffer3 = byteStream2.toByteArray(); DatagramPacket packet = new DatagramPacket(buffer3, buffer3.length, address, port); datagramSocket.send(packet); System.out.println("Terminating client remotely: " + address + " " + port); } catch (IOException ex1) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex1); } } private void UpdateMessageListToAllConnected() { for (User userOnList : userList) { outMessageList = new ArrayList<>(); InetAddress address; int port; boolean canSend = true; address = userOnList.getAddress(); port = userOnList.getPort(); if (address == null) { canSend = false; } System.out.println(userOnList.getUserName() + " " + userOnList.getAddress() + " " + userOnList.getPort() + " " + canSend); if (canSend) { for (Message messageOnList : messageList) { if (userOnList.getUserName().equals(messageOnList.getSender()) || userOnList.getUserName().equals(messageOnList.getReceiver())) { outMessageList.add(messageOnList); } } try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput = new ObjectOutputStream(new BufferedOutputStream(byteStream)); if (outMessageList.size() > 0) { objectOutput.writeObject(outMessageList); objectOutput.flush(); } else { objectOutput.writeObject("ALLCLEAR"); objectOutput.flush(); } byte[] buffer2 = byteStream.toByteArray(); DatagramPacket packet = new DatagramPacket(buffer2, buffer2.length, address, port); datagramSocket.send(packet); System.out.println("Updating Message List to: " + userOnList.getUserName() + " " + address + " " + port); } catch (IOException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } } } @FXML private void DeleteMessageFromUser(ActionEvent event) { ArrayList<Message> toDeleteList = new ArrayList<>(); String user = userField.getText(); for (Message messageOnList : messageList) { if (messageOnList.getReceiver().equals(user) || messageOnList.getSender().equals(user)) { toDeleteList.add(messageOnList); } } messageList.removeAll(toDeleteList); setTableMessagesAll(); MessageListWrite(); UpdateMessageListToAllConnected(); } @FXML private void DeleteMessageFromDeletedUser(ActionEvent event) { ArrayList<Message> toDeleteList = new ArrayList<>(); String user = "-ELIMINADO-"; for (Message messageOnList : messageList) { if (messageOnList.getReceiver().equals(user) || messageOnList.getSender().equals(user)) { toDeleteList.add(messageOnList); } } messageList.removeAll(toDeleteList); setTableMessagesAll(); MessageListWrite(); UpdateMessageListToAllConnected(); } @FXML private void FilterUser(ActionEvent event) { String searchString = userField.getText(); ArrayList<User> filteredUserList = new ArrayList<>(); ObservableList<User> dataFilteredUser; if (!(searchString.length() > 0)) { setUserTableAll(); return; } for (User userOnList : userList) { if (userOnList.getUserName().startsWith(searchString)) { filteredUserList.add(userOnList); } } dataFilteredUser = FXCollections.observableArrayList(); dataFilteredUser.addAll(filteredUserList); UserListTable.setItems(dataFilteredUser); } }
UTF-8
Java
36,192
java
ServerFXMLController.java
Java
[ { "context": "afx.scene.input.MouseEvent;\r\n\r\n/**\r\n *\r\n * @author Spellkaze\r\n */\r\npublic class ServerFXMLController implement", "end": 1250, "score": 0.9994175434112549, "start": 1241, "tag": "USERNAME", "value": "Spellkaze" }, { "context": "UserList()\r\n {\r\n ...
null
[]
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URL; import java.util.ArrayList; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.ListView; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; /** * * @author Spellkaze */ public class ServerFXMLController implements Initializable { ArrayList<Message> messageList = new ArrayList<>(); ArrayList<User> userList = new ArrayList<>(); Service<Void> backgroundThread; Message selectedMessage; ArrayList<Message> outMessageList; @FXML private TableColumn<Message, String> ColumnRemitente; @FXML private TableColumn<Message, String> ColumnReceptor; @FXML private TableColumn<Message, String> ColumnMensaje; @FXML private TableColumn<Message, String> ColumnFecha; @FXML private TableColumn<Message, String> ColumnConfirmation; private ObservableList<Message> dataMessage; private ObservableList<User> dataUser; @FXML private TableView<Message> table; DatagramSocket datagramSocket; boolean abortedSending = false; @FXML private ListView<User> UserListTable; @FXML private TextField userField; @FXML private TextField FilterField; @Override public void initialize(URL url, ResourceBundle rb) { try { datagramSocket = new DatagramSocket(5000); } catch (SocketException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } MessageListRead(); UserListRead(); setTableMessagesAll(); //SetUserList(); setUserTableAll(); AwaitingPackets(); UserListWrite(); MessageListWrite(); } public void setTableMessagesAll() { dataMessage = FXCollections.observableArrayList(); dataMessage.addAll(messageList); ColumnRemitente.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getSender())); ColumnReceptor.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getReceiver())); ColumnMensaje.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getMessage())); ColumnFecha.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getDate())); ColumnConfirmation.setCellValueFactory(p -> { if (!p.getValue().getReceivedNotification()) { return new SimpleStringProperty("✓"); //Simbolo positivo } else { return new SimpleStringProperty("✗"); //Simbolo negativo } }); table.setItems(dataMessage); } @FXML public void SelectedUserList() { userField.setText(UserListTable.getSelectionModel().getSelectedItem().getUserName()); } public void setUserTableAll() { dataUser = FXCollections.observableArrayList(); dataUser.addAll(userList); UserListTable.setItems(dataUser); } public void UserListRead() { try { ObjectInputStream archivoIngreso = new ObjectInputStream(new FileInputStream("./user.dat")); userList = (ArrayList<User>) archivoIngreso.readObject(); } catch (FileNotFoundException ex) { System.out.println("No file to read"); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } public void UserListWrite() { try { ObjectOutputStream ArchivoSalida = new ObjectOutputStream(new FileOutputStream("./user.dat", false)); ArchivoSalida.writeObject(userList); } catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } } public void MessageListRead() { try { ObjectInputStream archivoIngreso = new ObjectInputStream(new FileInputStream("./messages.dat")); messageList = (ArrayList<Message>) archivoIngreso.readObject(); } catch (FileNotFoundException ex) { System.out.println("No file to read"); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } } public void MessageListWrite() { try { ObjectOutputStream ArchivoSalida = new ObjectOutputStream(new FileOutputStream("./messages.dat", false)); ArchivoSalida.writeObject(messageList); } catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } } public void ShowAllMesages() { System.out.println(messageList); } private void AwaitingPackets() { backgroundThread = new Service<Void>() { @Override protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { try { while (true) { byte[] buffer = new byte[5000]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); datagramSocket.receive(packet); ByteArrayInputStream inputByteStream = new ByteArrayInputStream(buffer); ObjectInputStream objectInput = new ObjectInputStream(new BufferedInputStream(inputByteStream)); Object obj = objectInput.readObject(); System.out.println(obj.toString()); if (obj instanceof User) { System.out.println("is user request"); User dataObtained = (User) obj; if (SearchListUser(dataObtained)) { Platform.runLater(() -> { ConfirmUserPacket(dataObtained, datagramSocket, packet, "GRANTED"); sendMessageListToUser(dataObtained, datagramSocket, packet); }); } else { Platform.runLater(() -> { ConfirmUserPacket(dataObtained, datagramSocket, packet, "REJECTED"); }); } } else if (obj instanceof Message) { Message dataObtained = (Message) obj; System.out.println("is message request"); ConfirmMessagePacket(dataObtained, datagramSocket, packet); Platform.runLater(() -> { sendMessageListToSender(dataObtained.getSender(), datagramSocket, packet); if (!abortedSending) { try { Thread.sleep(100); sendMessageListToReceiver(dataObtained.getReceiver(), datagramSocket, packet); } catch (InterruptedException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } MessageListWrite(); setTableMessagesAll(); }); } else if (obj instanceof String) { String dataObtained = (String) obj; if (dataObtained.substring(0, 16).equals("TERMINATE_CLIENT")) { String[] parted = dataObtained.split(" "); System.out.println("Terminating client " + parted[1]); ResetUserInfo(parted[1]); } else { System.out.println("Data string obtained incorrectly: " + dataObtained); } } else { System.out.println("Getting unknown object"); System.out.println(obj.toString()); } } } catch (SocketException | SocketTimeoutException ex) { System.out.println("Socket timeoutr"); } catch (IOException ex) { System.out.println("IO error" + ex); } catch (ClassNotFoundException ex) { System.out.println("Class error" + ex); } finally { datagramSocket.setSoTimeout(0); } return null; } }; } }; backgroundThread.restart(); } private void ConfirmUserPacket(User user, DatagramSocket socket, DatagramPacket packet, String confirm) { try { InetAddress address = packet.getAddress(); int port = packet.getPort(); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput = new ObjectOutputStream(new BufferedOutputStream(byteStream)); objectOutput.writeObject(confirm); objectOutput.flush(); byte[] buffer2 = byteStream.toByteArray(); packet = new DatagramPacket(buffer2, buffer2.length, address, port); socket.send(packet); System.out.println("Sending confirmation to: " + address + " " + port + " " + confirm); setUserAddressPort(user, address, port); } catch (SocketException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } private void ConfirmMessagePacket(Message message, DatagramSocket socket, DatagramPacket packet) { abortedSending = false; String sender = message.getSender(); String receiver = message.getReceiver(); String messageGot = message.getMessage(); String date = message.getDate(); InetAddress addressOrigin = packet.getAddress(); int portOrigin = packet.getPort(); try { InetAddress address = null; int port = 0; for (User userOnList : userList) { if (receiver.equals(userOnList.getUserName())) { address = userOnList.getAddress(); port = userOnList.getPort(); } } if (address == null) //SECURITY CHECK PARA IMPOSIBLE DE ENVIAR { System.out.println("Abortar Envio"); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput = new ObjectOutputStream(new BufferedOutputStream(byteStream)); objectOutput.writeObject("NONEXISTANT"); objectOutput.flush(); byte[] buffer2 = byteStream.toByteArray(); packet = new DatagramPacket(buffer2, buffer2.length, addressOrigin, portOrigin); socket.send(packet); System.out.println("Sending counter to: " + addressOrigin + " " + portOrigin); abortedSending = true; return; } //Send message to receiver ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput = new ObjectOutputStream(new BufferedOutputStream(byteStream)); objectOutput.writeObject(message); objectOutput.flush(); byte[] buffer2 = byteStream.toByteArray(); packet = new DatagramPacket(buffer2, buffer2.length, address, port); socket.send(packet); System.out.println("Sending message to: " + address + " " + port); //Awaiting confirmation from receiver byte[] buffer = new byte[100]; packet = new DatagramPacket(buffer, buffer.length); datagramSocket.setSoTimeout(4000); datagramSocket.receive(packet); ByteArrayInputStream inputByteStream = new ByteArrayInputStream(buffer); ObjectInputStream objectInput = new ObjectInputStream(new BufferedInputStream(inputByteStream)); Object obj = objectInput.readObject(); System.out.println("Recieved confirmation from: " + packet.getAddress() + " " + packet.getPort()); System.out.println(obj.toString()); if (obj.toString().equals("RECEIVED")) { messageList.add(message); System.out.println("Message has been received"); //Send message to sender ByteArrayOutputStream byteStream2 = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput2 = new ObjectOutputStream(new BufferedOutputStream(byteStream2)); objectOutput2.writeObject("RECEIVED"); objectOutput2.flush(); byte[] buffer3 = byteStream2.toByteArray(); packet = new DatagramPacket(buffer3, buffer3.length, addressOrigin, portOrigin); socket.send(packet); System.out.println("Sending confirmation to: " + addressOrigin + " " + portOrigin); Thread.sleep(100); } else { System.out.println("Message has NOT been received"); } } catch (SocketException | SocketTimeoutException ex) { System.out.println("Message has Not been received"); //Send message to sender try { datagramSocket.setSoTimeout(0); ByteArrayOutputStream byteStream2 = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput2 = new ObjectOutputStream(new BufferedOutputStream(byteStream2)); objectOutput2.writeObject("NOTRECEIVED"); objectOutput2.flush(); byte[] buffer3 = byteStream2.toByteArray(); packet = new DatagramPacket(buffer3, buffer3.length, addressOrigin, portOrigin); socket.send(packet); System.out.println("Sending confirmation of not received to: " + addressOrigin + " " + portOrigin); } catch (IOException ex1) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex1); } Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } finally { try { datagramSocket.setSoTimeout(0); } catch (SocketException ex) { //Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } } //#Searching list by username private boolean SearchListUser(User user) { for (User userOnList : userList) { if (user.getUserName().equals(userOnList.getUserName())) { return true; } } return false; } //#Searching list by username private boolean SearchListUser(String user) { for (User userOnList : userList) { if (user.equals(userOnList.getUserName())) { return true; } } return false; } //Asigns adddres and port to user list private void setUserAddressPort(User user, InetAddress address, int port) { for (User userOnList : userList) { if (user.getUserName().equals(userOnList.getUserName())) { userOnList.setAddress(address); userOnList.setPort(port); userOnList.ConnectionEstablished(); System.out.println("Guardando info de cliente: " + userOnList.getUserName() + " " + userOnList.getAddress() + " " + userOnList.getPort()); } } } //Send message list to the respective client private void sendMessageListToUser(User user, DatagramSocket socket, DatagramPacket packet) { outMessageList = new ArrayList<>(); InetAddress address = user.getAddress(); int port = user.getPort(); for (User userOnList : userList) { if (user.getUserName().equals(userOnList.getUserName())) { address = userOnList.getAddress(); port = userOnList.getPort(); } } for (Message messageOnList : messageList) { if (user.getUserName().equals(messageOnList.getSender()) || user.getUserName().equals(messageOnList.getReceiver())) { outMessageList.add(messageOnList); } } try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput = new ObjectOutputStream(new BufferedOutputStream(byteStream)); objectOutput.writeObject(outMessageList); objectOutput.flush(); byte[] buffer2 = byteStream.toByteArray(); packet = new DatagramPacket(buffer2, buffer2.length, address, port); socket.send(packet); System.out.println("Sending message List to: " + address + " " + port); } catch (IOException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } //Send message list, update sender and receiver message list; private void sendMessageListToSender(String sender, DatagramSocket socket, DatagramPacket packet) { outMessageList = new ArrayList<>(); InetAddress address = null; int port = 0; //UPDATE SENDER for (User userOnList : userList) { if (sender.equals(userOnList.getUserName())) { address = userOnList.getAddress(); port = userOnList.getPort(); } } for (Message messageOnList : messageList) { if (sender.equals(messageOnList.getSender()) || sender.equals(messageOnList.getReceiver())) { outMessageList.add(messageOnList); } } try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput = new ObjectOutputStream(new BufferedOutputStream(byteStream)); objectOutput.writeObject(outMessageList); objectOutput.flush(); byte[] buffer2 = byteStream.toByteArray(); packet = new DatagramPacket(buffer2, buffer2.length, address, port); socket.send(packet); System.out.println("Sending message Sender List to: " + address + " " + port); } catch (IOException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } //Send message list, update sender and receiver message list; private void sendMessageListToReceiver(String receiver, DatagramSocket socket, DatagramPacket packet) { outMessageList = new ArrayList<>(); InetAddress address = null; int port = 0; //UPDATE SENDER for (User userOnList : userList) { if (receiver.equals(userOnList.getUserName())) { address = userOnList.getAddress(); port = userOnList.getPort(); } } for (Message messageOnList : messageList) { if (receiver.equals(messageOnList.getSender()) || receiver.equals(messageOnList.getReceiver())) { outMessageList.add(messageOnList); } } try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput = new ObjectOutputStream(new BufferedOutputStream(byteStream)); objectOutput.writeObject(outMessageList); objectOutput.flush(); byte[] buffer2 = byteStream.toByteArray(); packet = new DatagramPacket(buffer2, buffer2.length, address, port); socket.send(packet); System.out.println("Sending message Receiver List to: " + address + " " + port); } catch (IOException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } private void ResetUserInfo(String user) { for (User userOnList : userList) { if (user.equals(userOnList.getUserName())) { userOnList.setAddress(null); userOnList.setPort(0); System.out.println("Terminated " + userOnList.getUserName()); return; } } UserListWrite(); } //#DEBUG private void SetUserList() { userList.add(new User("Waluigi")); userList.add(new User("Espageti")); userList.add(new User("Wario")); } @FXML private void AddUser(ActionEvent event) { String user = userField.getText(); if (!SearchListUser(user) && user.length() > 0) { userList.add(new User(user)); } else { System.out.println("Already added"); } setUserTableAll(); UserListWrite(); } @FXML private void RemoveUser(ActionEvent event) { String user = userField.getText(); if (SearchListUser(user) && user.length() > 0) { for (int i = 0; i < userList.size(); i++) { if (user.equals(userList.get(i).getUserName())) { TerminateClientbyUser(userList.get(i).getUserName()); userList.remove(i); for (int j = 0; j < messageList.size(); j++) { if (messageList.get(j).getSender().equals(user)) { messageList.get(j).setSender("-ELIMINADO-"); } if (messageList.get(j).getReceiver().equals(user)) { messageList.get(j).setReceiver("-ELIMINADO-"); } } } } } else { System.out.println("No user like that"); } System.out.println(messageList); setUserTableAll(); dataMessage.clear(); setTableMessagesAll(); UpdateMessageListToAllConnected(); UserListWrite(); } @FXML private void SelectedMessageList(MouseEvent event) { selectedMessage = table.getSelectionModel().getSelectedItem(); } @FXML private void DeleteMessage(ActionEvent event) { for (int i = 0; i < messageList.size(); i++) { if (messageList.get(i).equals(selectedMessage)) { System.out.println("Found message to get deleted"); messageList.remove(i); UpdateMessageListToAllConnected(); } } setTableMessagesAll(); MessageListWrite(); } @FXML private void FilterMessageListSender(ActionEvent event) { String searchString = FilterField.getText(); ArrayList<Message> filteredMessageList = new ArrayList<>(); ObservableList<Message> dataFilteredMessage; dataFilteredMessage = FXCollections.observableArrayList(); if (searchString.length() > 0) { for (Message messageOnList : messageList) { if (searchString.equals(messageOnList.getSender())) { filteredMessageList.add(messageOnList); } } System.out.println(filteredMessageList); dataFilteredMessage.addAll(filteredMessageList); ColumnRemitente.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getSender())); ColumnReceptor.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getReceiver())); ColumnMensaje.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getMessage())); ColumnFecha.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getDate())); ColumnConfirmation.setCellValueFactory(p -> { if (!p.getValue().getReceivedNotification()) { return new SimpleStringProperty("✓"); //Simbolo positivo } else { return new SimpleStringProperty("✗"); //Simbolo negativo } }); table.setItems(dataFilteredMessage); } else { setTableMessagesAll(); } } @FXML private void FilterMessageListReceiver(ActionEvent event) { String searchString = FilterField.getText(); ArrayList<Message> filteredMessageList = new ArrayList<>(); ObservableList<Message> dataFilteredMessage; dataFilteredMessage = FXCollections.observableArrayList(); if (searchString.length() > 0) { for (Message messageOnList : messageList) { if (searchString.equals(messageOnList.getReceiver())) { filteredMessageList.add(messageOnList); } } System.out.println(filteredMessageList); dataFilteredMessage.addAll(filteredMessageList); ColumnRemitente.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getSender())); ColumnReceptor.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getReceiver())); ColumnMensaje.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getMessage())); ColumnFecha.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getDate())); ColumnConfirmation.setCellValueFactory(p -> { if (!p.getValue().getReceivedNotification()) { return new SimpleStringProperty("✓"); //Simbolo positivo } else { return new SimpleStringProperty("✗"); //Simbolo negativo } }); table.setItems(dataFilteredMessage); } else { setTableMessagesAll(); } } private void TerminateClientbyUser(String user) { InetAddress address = null; int port = 0; //UPDATE SENDER for (User userOnList : userList) { if (user.equals(userOnList.getUserName())) { address = userOnList.getAddress(); port = userOnList.getPort(); System.out.println("Found address"); } } if (address == null) { System.out.println(user + " already terminated"); return; } try { ByteArrayOutputStream byteStream2 = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput2 = new ObjectOutputStream(new BufferedOutputStream(byteStream2)); objectOutput2.writeObject("TERMINATE"); objectOutput2.flush(); byte[] buffer3 = byteStream2.toByteArray(); DatagramPacket packet = new DatagramPacket(buffer3, buffer3.length, address, port); datagramSocket.send(packet); System.out.println("Terminating client remotely: " + address + " " + port); } catch (IOException ex1) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex1); } } private void UpdateMessageListToAllConnected() { for (User userOnList : userList) { outMessageList = new ArrayList<>(); InetAddress address; int port; boolean canSend = true; address = userOnList.getAddress(); port = userOnList.getPort(); if (address == null) { canSend = false; } System.out.println(userOnList.getUserName() + " " + userOnList.getAddress() + " " + userOnList.getPort() + " " + canSend); if (canSend) { for (Message messageOnList : messageList) { if (userOnList.getUserName().equals(messageOnList.getSender()) || userOnList.getUserName().equals(messageOnList.getReceiver())) { outMessageList.add(messageOnList); } } try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000); ObjectOutputStream objectOutput = new ObjectOutputStream(new BufferedOutputStream(byteStream)); if (outMessageList.size() > 0) { objectOutput.writeObject(outMessageList); objectOutput.flush(); } else { objectOutput.writeObject("ALLCLEAR"); objectOutput.flush(); } byte[] buffer2 = byteStream.toByteArray(); DatagramPacket packet = new DatagramPacket(buffer2, buffer2.length, address, port); datagramSocket.send(packet); System.out.println("Updating Message List to: " + userOnList.getUserName() + " " + address + " " + port); } catch (IOException ex) { Logger.getLogger(ServerFXMLController.class.getName()).log(Level.SEVERE, null, ex); } } } } @FXML private void DeleteMessageFromUser(ActionEvent event) { ArrayList<Message> toDeleteList = new ArrayList<>(); String user = userField.getText(); for (Message messageOnList : messageList) { if (messageOnList.getReceiver().equals(user) || messageOnList.getSender().equals(user)) { toDeleteList.add(messageOnList); } } messageList.removeAll(toDeleteList); setTableMessagesAll(); MessageListWrite(); UpdateMessageListToAllConnected(); } @FXML private void DeleteMessageFromDeletedUser(ActionEvent event) { ArrayList<Message> toDeleteList = new ArrayList<>(); String user = "-ELIMINADO-"; for (Message messageOnList : messageList) { if (messageOnList.getReceiver().equals(user) || messageOnList.getSender().equals(user)) { toDeleteList.add(messageOnList); } } messageList.removeAll(toDeleteList); setTableMessagesAll(); MessageListWrite(); UpdateMessageListToAllConnected(); } @FXML private void FilterUser(ActionEvent event) { String searchString = userField.getText(); ArrayList<User> filteredUserList = new ArrayList<>(); ObservableList<User> dataFilteredUser; if (!(searchString.length() > 0)) { setUserTableAll(); return; } for (User userOnList : userList) { if (userOnList.getUserName().startsWith(searchString)) { filteredUserList.add(userOnList); } } dataFilteredUser = FXCollections.observableArrayList(); dataFilteredUser.addAll(filteredUserList); UserListTable.setItems(dataFilteredUser); } }
36,192
0.528303
0.524572
969
35.335396
30.778545
154
false
false
0
0
0
0
0
0
0.536636
false
false
11
a124dbef096771a444b06e84c725786ed702fba5
26,645,977,132,870
ee90c9e94d3c12980bdba1a64a34238f64345807
/hello-spring/src/test/java/hello/hellospring/service/MemberServiceIntegrationTest2.java
3be6dc449ed96c1ad28f42f2974e31e6c93b6398
[]
no_license
SimJaeMin/SpringStudy1
https://github.com/SimJaeMin/SpringStudy1
8e00446bd0c97d68a5f173e93df183c77d7977d7
eac7a5a3ce98f0d49e69a6602aad5794804f3e20
refs/heads/master
2023-01-16T06:54:13.373000
2020-11-17T08:35:22
2020-11-17T08:35:22
311,572,498
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hello.hellospring.service; import static org.junit.jupiter.api.Assertions.fail; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.annotation.Transactional; import hello.hellospring.domain.Member; import hello.hellospring.repository.MemberRepository; import hello.hellospring.repository.MemoryMemberRepository; @SpringBootTest @Transactional //테스트를 진행할 때 트랜잭션을 하나 실행시키고 이후에 insert까지한다음 롤백해준다. //jpa 는 모든 테스트케이스는 Transactional 안에서 수행되야한다. class MemberServiceIntegrationTest2 { @Autowired MemberService memberService; @Autowired MemberRepository memberRepository; // 그런데 만약 memberRepository에 store가 static이 아니라면 다른객체라 잘못된 조회가 될 수 있음 // MemoryMemberRepository memberRepository = new MemoryMemberRepository(); // // 그걸 방지하기 위해 MemberService에서 생성자를 만들고 // @BeforeEach // 테스트를 실행할 떄마다 독립적으로 만들어준다. // public void beforeEach() { // System.out.println("before"); // memberRepository = new MemoryMemberRepository(); // memberService = new MemberService(memberRepository); // } // // @AfterEach // public void afterEach() { // System.out.println("after"); // memberRepository.clearStore(); // } @Test void join() { //given -> 무언가가 주어젔는데 Member member = new Member(); member.setName("hello"); //when -> 이거를 실행했을때 Long saveId= memberService.join(member); //then -> 결과가 이게 나와야된다. Member findMember = memberService.findOne(member.getId()).get(); Assertions.assertThat(member.getName()).isEqualTo(findMember.getName()); } @Test public void 중복_회원_예외() { //given Member member1= new Member(); member1.setName("Spring"); Member member2= new Member(); member2.setName("Spring"); memberService.join(member1); //첫번째 인수가 터저야됨 => 언제 ? => 두번쨰 인자(로직)이 진행될 때 IllegalStateException e = org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class, ()->memberService.join(member2)); //메시지도 비교하고 싶으면 위에처럼 받아서 사용가능 Assertions.assertThat(e.getMessage()).isEqualTo("이미 존재하는 이름(회원) 입니다."); // try { // memberService.join(member2); // fail(); // }catch (IllegalStateException e) { // // TODO: handle exception // Assertions.assertThat(e.getMessage()).isEqualTo("이미 존재하는 이름(회원)입니다."); // } //when //then } }
UTF-8
Java
2,989
java
MemberServiceIntegrationTest2.java
Java
[ { "context": "\tMember member = new Member();\n\t\t\tmember.setName(\"hello\");\n\t\t\t\n\t\t\t//when -> 이거를 실행했을때 \n\t\t\tLong saveId= me", "end": 1522, "score": 0.9891144037246704, "start": 1517, "tag": "USERNAME", "value": "hello" }, { "context": "Member member1= new Member();\n\t...
null
[]
package hello.hellospring.service; import static org.junit.jupiter.api.Assertions.fail; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.annotation.Transactional; import hello.hellospring.domain.Member; import hello.hellospring.repository.MemberRepository; import hello.hellospring.repository.MemoryMemberRepository; @SpringBootTest @Transactional //테스트를 진행할 때 트랜잭션을 하나 실행시키고 이후에 insert까지한다음 롤백해준다. //jpa 는 모든 테스트케이스는 Transactional 안에서 수행되야한다. class MemberServiceIntegrationTest2 { @Autowired MemberService memberService; @Autowired MemberRepository memberRepository; // 그런데 만약 memberRepository에 store가 static이 아니라면 다른객체라 잘못된 조회가 될 수 있음 // MemoryMemberRepository memberRepository = new MemoryMemberRepository(); // // 그걸 방지하기 위해 MemberService에서 생성자를 만들고 // @BeforeEach // 테스트를 실행할 떄마다 독립적으로 만들어준다. // public void beforeEach() { // System.out.println("before"); // memberRepository = new MemoryMemberRepository(); // memberService = new MemberService(memberRepository); // } // // @AfterEach // public void afterEach() { // System.out.println("after"); // memberRepository.clearStore(); // } @Test void join() { //given -> 무언가가 주어젔는데 Member member = new Member(); member.setName("hello"); //when -> 이거를 실행했을때 Long saveId= memberService.join(member); //then -> 결과가 이게 나와야된다. Member findMember = memberService.findOne(member.getId()).get(); Assertions.assertThat(member.getName()).isEqualTo(findMember.getName()); } @Test public void 중복_회원_예외() { //given Member member1= new Member(); member1.setName("Spring"); Member member2= new Member(); member2.setName("Spring"); memberService.join(member1); //첫번째 인수가 터저야됨 => 언제 ? => 두번쨰 인자(로직)이 진행될 때 IllegalStateException e = org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class, ()->memberService.join(member2)); //메시지도 비교하고 싶으면 위에처럼 받아서 사용가능 Assertions.assertThat(e.getMessage()).isEqualTo("이미 존재하는 이름(회원) 입니다."); // try { // memberService.join(member2); // fail(); // }catch (IllegalStateException e) { // // TODO: handle exception // Assertions.assertThat(e.getMessage()).isEqualTo("이미 존재하는 이름(회원)입니다."); // } //when //then } }
2,989
0.71064
0.707499
92
26.684782
24.95776
138
false
false
0
0
0
0
0
0
2.369565
false
false
11
d08cf3af2ba0f9a73bd3225c38ca9f28891745ec
6,760,278,527,782
fac09015d5f158441e4a1a735de733aaacbc5fb2
/system-parent/system-cache/src/main/java/org/whale/system/cache/ICacheService.java
39a9c7d37daa71049238869e5319efcf21f8c8b5
[ "Apache-2.0" ]
permissive
fywxin/base
https://github.com/fywxin/base
613062300637968910b7e78458e4a0ea136a309b
53cc15d82028b76196411356ea1ef8c90bf01bfa
refs/heads/master
2020-12-25T16:50:40.409000
2017-12-11T03:14:58
2017-12-11T03:14:58
28,173,388
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.whale.system.cache; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Set; /** * 一个cacheName 只能对应一种java类型或类 * * @author Administrator * */ public interface ICacheService<M extends Serializable> { /** * 缓存中保存记录,不会过期 * @param cacheName * @param key * @param value */ void put(String cacheName, String key, M value); /** * 批量保存记录,不会过期 * * @param cacheName * @param keyValues */ void mput(String cacheName, Map<String, M> keyValues); /** * *功能说明: 往本缓中存入一条记录,seconds 秒后过期 *创建人: wjs *创建时间:2013-4-28 下午3:06:19 *@param key *@param value void * */ void put(String cacheName, String key, M value, Integer seconds); /** * 批量保存记录,seconds 秒后过期 * * @param cacheName * @param keyValues * @param seconds */ void mput(String cacheName, Map<String, M> keyValues, Integer seconds); /** * 根据key获取缓存记录数据 * @param key * @return */ M get(String cacheName, String key); /** * 批量获取缓存记录数据 * * @param cacheName * @param keys * @return */ List<M> mget(String cacheName, List<String> keys); /** * 删除键为KEY的缓存记录 * @param key */ void del(String cacheName, String key); /** * 批量删除 * * @param cacheName * @param keys */ void mdel(String cacheName, List<String> keys); /** * 清除该缓存实例的所有缓存记录 */ void clear(String cacheName); /** * 获取缓存对象 * @return */ Object getNativeCache(); /** * 获取缓存的所有key集合 * @date 2015年1月16日 上午10:07:12 */ Set<String> getKeys(String cacheName); }
UTF-8
Java
1,826
java
ICacheService.java
Java
[ { "context": "\n\n/**\n * 一个cacheName 只能对应一种java类型或类\n * \n * @author Administrator\n *\n */\npublic interface ICacheService<M extends S", "end": 192, "score": 0.6551220417022705, "start": 179, "tag": "USERNAME", "value": "Administrator" }, { "context": "\t/**\n\t * \n\t *功能说明: 往本缓中存...
null
[]
package org.whale.system.cache; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Set; /** * 一个cacheName 只能对应一种java类型或类 * * @author Administrator * */ public interface ICacheService<M extends Serializable> { /** * 缓存中保存记录,不会过期 * @param cacheName * @param key * @param value */ void put(String cacheName, String key, M value); /** * 批量保存记录,不会过期 * * @param cacheName * @param keyValues */ void mput(String cacheName, Map<String, M> keyValues); /** * *功能说明: 往本缓中存入一条记录,seconds 秒后过期 *创建人: wjs *创建时间:2013-4-28 下午3:06:19 *@param key *@param value void * */ void put(String cacheName, String key, M value, Integer seconds); /** * 批量保存记录,seconds 秒后过期 * * @param cacheName * @param keyValues * @param seconds */ void mput(String cacheName, Map<String, M> keyValues, Integer seconds); /** * 根据key获取缓存记录数据 * @param key * @return */ M get(String cacheName, String key); /** * 批量获取缓存记录数据 * * @param cacheName * @param keys * @return */ List<M> mget(String cacheName, List<String> keys); /** * 删除键为KEY的缓存记录 * @param key */ void del(String cacheName, String key); /** * 批量删除 * * @param cacheName * @param keys */ void mdel(String cacheName, List<String> keys); /** * 清除该缓存实例的所有缓存记录 */ void clear(String cacheName); /** * 获取缓存对象 * @return */ Object getNativeCache(); /** * 获取缓存的所有key集合 * @date 2015年1月16日 上午10:07:12 */ Set<String> getKeys(String cacheName); }
1,826
0.628886
0.612694
99
14.59596
15.44748
72
true
false
0
0
0
0
0
0
1.151515
false
false
11
c460bdd8d5f11cf4c76282176c696f4f4618b0fa
22,368,189,744,153
887f03e31dbbea80be14646c47dfcf010cc15612
/src/main/java/student_dmitry_samsonov/lesson_19_io/WriteRandToFile.java
110bf7de92d7aff8a81e3f0b272b789f89b8d1b7
[]
no_license
javagurulv/ok_ru_admin_group_2
https://github.com/javagurulv/ok_ru_admin_group_2
8137113dedfd9b72e8fdbca21a9a4088887db612
9fdb8ac22648da3be9e96689042b30f379df22fd
refs/heads/master
2023-08-19T13:07:13.124000
2021-10-31T13:03:34
2021-10-31T13:03:34
372,749,341
0
3
null
false
2021-06-02T08:01:45
2021-06-01T08:02:43
2021-06-02T07:22:05
2021-06-02T08:01:44
42,141
0
3
0
Java
false
false
package student_dmitry_samsonov.lesson_19_io; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Random; class WriteRandToFile { public static void main(String[] args) { try { File file = new File("/tmp/rand.txt"); FileWriter myWriter = new FileWriter(file); Random rand = new Random(); for (int i = 0; i < 1000; i++) { myWriter.write(Integer.toString(rand.nextInt()) + '\n'); } myWriter.close(); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
UTF-8
Java
689
java
WriteRandToFile.java
Java
[ { "context": "package student_dmitry_samsonov.lesson_19_io;\n\nimport java.io.File;\nimpo", "end": 22, "score": 0.9004325866699219, "start": 17, "tag": "NAME", "value": "mitry" }, { "context": "package student_dmitry_samsonov.lesson_19_io;\n\nimport java.io.File;\nimpor", "end": ...
null
[]
package student_dmitry_samsonov.lesson_19_io; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Random; class WriteRandToFile { public static void main(String[] args) { try { File file = new File("/tmp/rand.txt"); FileWriter myWriter = new FileWriter(file); Random rand = new Random(); for (int i = 0; i < 1000; i++) { myWriter.write(Integer.toString(rand.nextInt()) + '\n'); } myWriter.close(); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
689
0.554427
0.544267
25
26.559999
19.557259
72
false
false
0
0
0
0
0
0
0.56
false
false
11
1d2f31e4f07df52cb0841b71c76c5f2ec0c6a119
14,637,248,563,571
5d194af8d72de019637b5c3359500775c0c113f9
/app/src/main/java/fr/utt/if26_avargues_jacquot/fragment/CarteFragment.java
dfb6015c35194b65bae4f4d839de662b8d419bba
[]
no_license
guillaumeAVG/UTT_IF26_AVARGUES_JACQUOT
https://github.com/guillaumeAVG/UTT_IF26_AVARGUES_JACQUOT
25c2ac4190364f4a81530000faf3a471b8278ed5
5f69073e66f91de465fd69fab881dac5dec3bef7
refs/heads/master
2021-01-10T10:59:48.618000
2016-01-04T16:58:16
2016-01-04T16:58:16
46,928,972
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.utt.if26_avargues_jacquot.fragment; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import com.example.guillaume.if26_avargues_jacquot.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.osmdroid.DefaultResourceProxyImpl; import org.osmdroid.ResourceProxy; import org.osmdroid.api.IMapController; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.gestures.RotationGestureOverlay; import java.io.IOException; import java.net.MalformedURLException; import fr.utt.if26_avargues_jacquot.activity.NouveauBonPlanActivity; import fr.utt.if26_avargues_jacquot.services.CheckTokenService; import fr.utt.if26_avargues_jacquot.services.GetBonsPlansService; import fr.utt.if26_avargues_jacquot.services.MyItemizedOverlay; /** * Created by guillaume on 26/11/2015. */ /* Cette classe définit le fragment de la carte C'est à dire lorsque le menu tabs est sur: Carte. Elle hérite de Fragment et implémente View.OnClickListener car cet écran possède des éléments qui sont cliquables: c'est pour que l'utilisateur puisse ajouter un bon plan.*/ public class CarteFragment extends Fragment implements View.OnClickListener { MapView map; /* La méthode onCreateView permet de créer des vues: c'est à dire on dit quel fichier XML doit réprésenter la page pour la carte. De plus, on ajoute les éléments qui sont cliquables pour permettre d'avoir des intéractions par la suite*/ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //On définit le XML a utiliser View rootView = inflater.inflate(R.layout.fragment_carte, container, false); //On met en place le listener sur les éléments souhaités rootView.findViewById(R.id.IMGB_ajouterBonPlan).setOnClickListener(this); rootView.findViewById(R.id.CB_agencesDeTransports).setOnClickListener(this); rootView.findViewById(R.id.CB_alimentations).setOnClickListener(this); rootView.findViewById(R.id.CB_assuranceMaladieEtMutuelles).setOnClickListener(this); rootView.findViewById(R.id.CB_caf).setOnClickListener(this); rootView.findViewById(R.id.CB_distributionsDeBillets).setOnClickListener(this); rootView.findViewById(R.id.CB_emploi).setOnClickListener(this); rootView.findViewById(R.id.CB_evenements).setOnClickListener(this); rootView.findViewById(R.id.CB_garages).setOnClickListener(this); rootView.findViewById(R.id.CB_hopitaux).setOnClickListener(this); rootView.findViewById(R.id.CB_laveries).setOnClickListener(this); rootView.findViewById(R.id.CB_mairies).setOnClickListener(this); rootView.findViewById(R.id.CB_maisonDesEtudiants).setOnClickListener(this); rootView.findViewById(R.id.CB_medecins).setOnClickListener(this); rootView.findViewById(R.id.CB_pharmacies).setOnClickListener(this); rootView.findViewById(R.id.CB_reductionsACourtTerme).setOnClickListener(this); rootView.findViewById(R.id.CB_reductionsALongTerme).setOnClickListener(this); rootView.findViewById(R.id.CB_salleDeSport).setOnClickListener(this); rootView.findViewById(R.id.CB_stades).setOnClickListener(this); rootView.findViewById(R.id.CB_stationsEssences).setOnClickListener(this); rootView.findViewById(R.id.CB_terrains).setOnClickListener(this); //On défini quel élément représente la carte sur l'interface map = (MapView) rootView.findViewById(R.id.map); map.setTileSource(TileSourceFactory.MAPQUESTOSM); map.setBuiltInZoomControls(true); map.setMultiTouchControls(true); IMapController mapController = map.getController(); mapController.setZoom(13); // On met un place directement la vue sur la ville de Troyes GeoPoint startPoint = new GeoPoint(48.3, 4.0833); mapController.setCenter(startPoint); RotationGestureOverlay mRotationGestureOverlay = new RotationGestureOverlay(getContext(), map); mRotationGestureOverlay.setEnabled(true); map.setMultiTouchControls(true); map.getOverlays().add(mRotationGestureOverlay); try { putBonsPlans(map); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return rootView; } /** * La méthode onClick permet de définir une action dès que l'utilisateur clique sur un des éléments défini dans la méhode * * @param v Vue */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.IMGB_ajouterBonPlan: Boolean connecte = false; try { connecte = this.checkToken(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } if (!connecte) { AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create(); alertDialog.setTitle("Connexion requise"); alertDialog.setMessage("Vous devez être connecté pour ajouter un bon plan."); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); } else { // On met en place le passage entre les deux activités sur ce Listener // On passe de l'activité principale à l'activité d'ajout de bon plan. Intent intent = new Intent(getActivity(), NouveauBonPlanActivity.class); startActivity(intent); } break; case R.id.CB_agencesDeTransports: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_agencesDeTransports), "Agence de Transport"); break; case R.id.CB_alimentations: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_alimentations), "Alimentation"); break; case R.id.CB_assuranceMaladieEtMutuelles: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_assuranceMaladieEtMutuelles), "Assurance Maladie et Mutuelles"); break; case R.id.CB_caf: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_caf), "CAF"); break; case R.id.CB_distributionsDeBillets: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_distributionsDeBillets), "Distributeur de billets"); break; case R.id.CB_emploi: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_emploi), "Emploi"); break; case R.id.CB_evenements: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_evenements), "Evènement"); break; case R.id.CB_garages: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_garages), "Garage"); break; case R.id.CB_hopitaux: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_hopitaux), "Hopital"); break; case R.id.CB_laveries: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_laveries), "Laverie"); break; case R.id.CB_mairies: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_mairies), "Mairie"); break; case R.id.CB_maisonDesEtudiants: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_maisonDesEtudiants), "Maison des étudiants"); break; case R.id.CB_medecins: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_medecins), "Médecin"); break; case R.id.CB_pharmacies: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_pharmacies), "Laverie"); break; case R.id.CB_reductionsACourtTerme: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_reductionsACourtTerme), "Réduction à court terme"); break; case R.id.CB_reductionsALongTerme: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_reductionsALongTerme), "Réduction à long terme"); break; case R.id.CB_terrains: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_terrains), "Terrain"); break; case R.id.CB_salleDeSport: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_salleDeSport), "Salle de sport"); break; case R.id.CB_stades: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_stades), "Stade"); break; case R.id.CB_stationsEssences: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_stationsEssences), "Station essence"); break; } } /** * Permet de cacher tous les éléments, sur la carte, en fonction de leur type * * @param type Type du bon plan (ex : CAF, Réduction à court terme, ...) */ private void hideFromMap(String type) { for (int i = 1; i < map.getOverlays().size(); i++) { MyItemizedOverlay overlay = (MyItemizedOverlay) map.getOverlays().get(i); String categorie = overlay.getItem(0).getSnippet(); if (categorie.equals(type)) { Drawable marker = ContextCompat.getDrawable(getContext(), R.drawable.transparent); Bitmap bitmap = ((BitmapDrawable) marker).getBitmap(); Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 1, 1, true)); overlay.getItem(0).setMarker(d); } } } /** * Permet de cacher ou montrer des éléments de la carte en fonction de la catégorie du bon plan. * Ce choix est effectué par l'utilisateur à l'aide des checkbox des filtres * * @param CB Checkbox dont l'état est à observer * @param type Type du bon plan (ex : CAF, Réduction à court terme, ...) */ private void ShowOrHideType(CheckBox CB, String type) { if (!CB.isChecked()) hideFromMap(type); else showOnMap(type); } /** * Permet de montrer tous les éléments, sur la carte, en fonction de leur type * * @param type Type du bon plan (ex : CAF, Réduction à court terme, ...) */ private void showOnMap(String type) { for (int i = 1; i < map.getOverlays().size(); i++) { MyItemizedOverlay overlay = (MyItemizedOverlay) map.getOverlays().get(i); String categorie = overlay.getItem(0).getSnippet(); if (categorie.equals(type)) { Drawable d = getDrawable(type); overlay.getItem(0).setMarker(d); } } } /** * Permet de savoir si l'utilisateur est connecté en vérifiant le token en mémoire. * * @return True si l'utilisateur est correctement authentifié, sinon false. * @throws IOException * @throws JSONException */ public boolean checkToken() throws IOException, JSONException { SharedPreferences settings = getContext().getSharedPreferences("StudenN3_storage", 0); String token = settings.getString("token", ""); CheckTokenService cts = new CheckTokenService(); Boolean checkToken = cts.validateToken(token); if (checkToken) { return true; } else { return false; } } /** * Méthode permettant d'ajouter les bons plans sur la carte, à partir des données en base * * @param map Carte présente sur l'écran * @throws JSONException * @throws IOException * @throws MalformedURLException */ public void putBonsPlans(MapView map) throws JSONException, IOException, MalformedURLException { //On récupère les bons plans depuis le webservice GetBonsPlansService gbps = new GetBonsPlansService(); String bonsPlans = gbps.getCurrentBonsPlans(); JSONArray jsonArrayBonsPlans = new JSONArray(bonsPlans); //Si on a des bons plans à afficher if (jsonArrayBonsPlans != null) { for (int i = 0; i < jsonArrayBonsPlans.length(); i++) { //Pour chaque bon plan, on récupère son titre, son type et les coordonnées pour l'afficher sur la carte JSONObject bonPlan = (JSONObject) jsonArrayBonsPlans.get(i); String bonPlanNom = bonPlan.getString("nom"); String bonPlanType = bonPlan.getString("type"); Double bonPlanLongitude = bonPlan.getDouble("longitude"); Double bonPlanLatitude = bonPlan.getDouble("latitude"); addBPtoMap(map, bonPlanNom, bonPlanType, bonPlanLongitude, bonPlanLatitude); } } } /** * Méthode permettant d'afficher l'icône du bon plan sur la carte * * @param map Carte présente sur l'écran * @param bonPlanNom Titre du bon plan * @param type Type du bon plan * @param bonPlanLongitude Longitude du bon plan * @param bonPlanLatitude Latitude du bon plan */ public void addBPtoMap(MapView map, String bonPlanNom, String type, Double bonPlanLongitude, Double bonPlanLatitude) { // On ajoute une icône sur la carte Drawable marker = getDrawable(type); if (marker != null) { marker.setBounds(-marker.getIntrinsicWidth() / 4, -marker.getIntrinsicHeight(), marker.getIntrinsicWidth() / 4, 0); ResourceProxy resourceProxy = new DefaultResourceProxyImpl(getActivity().getApplicationContext()); MyItemizedOverlay myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy); map.getOverlays().add(myItemizedOverlay); GeoPoint myPoint = new GeoPoint(bonPlanLatitude, bonPlanLongitude); myItemizedOverlay.addItem(myPoint, bonPlanNom, type); } } /** * Récupère la bonne icône en fonction du bon plan * * @param type Type de bon plan * @return Drawable Icone du bon plan correspondant à son type */ public Drawable getDrawable(String type) { Drawable marker = null; switch (type) { case "Agence de Transport": marker = ContextCompat.getDrawable(getContext(), R.drawable.bus); break; case "Alimentation": marker = ContextCompat.getDrawable(getContext(), R.drawable.alimentation); break; case "Assurance Maladie et Mutuelles": marker = ContextCompat.getDrawable(getContext(), R.drawable.assurance_maladie); break; case "CAF": marker = ContextCompat.getDrawable(getContext(), R.drawable.caf_jaune); break; case "Distributeur de billets": marker = ContextCompat.getDrawable(getContext(), R.drawable.distributeurs); break; case "Emploi": marker = ContextCompat.getDrawable(getContext(), R.drawable.emploi); break; case "Evènement": marker = ContextCompat.getDrawable(getContext(), R.drawable.evenement_etudiant); break; case "Garage": marker = ContextCompat.getDrawable(getContext(), R.drawable.garage); break; case "Hopital": marker = ContextCompat.getDrawable(getContext(), R.drawable.hopital); break; case "Laverie": marker = ContextCompat.getDrawable(getContext(), R.drawable.laveries); break; case "Mairie": marker = ContextCompat.getDrawable(getContext(), R.drawable.mairie); break; case "Maison des étudiants": marker = ContextCompat.getDrawable(getContext(), R.drawable.maison_des_etudiants); break; case "Médecin": marker = ContextCompat.getDrawable(getContext(), R.drawable.medecin); break; case "Pharmacie": marker = ContextCompat.getDrawable(getContext(), R.drawable.pharmacie); break; case "Réduction à court terme": marker = ContextCompat.getDrawable(getContext(), R.drawable.court_terme_reduction); break; case "Réduction à long terme": marker = ContextCompat.getDrawable(getContext(), R.drawable.long_terme_reduction); break; case "Salle de sport": marker = ContextCompat.getDrawable(getContext(), R.drawable.salle_de_sport); break; case "Stade": marker = ContextCompat.getDrawable(getContext(), R.drawable.stade); break; case "Station essence": marker = ContextCompat.getDrawable(getContext(), R.drawable.stations_services); break; case "Terrain": marker = ContextCompat.getDrawable(getContext(), R.drawable.terrain); break; default: marker = null; } Bitmap bitmap = ((BitmapDrawable) marker).getBitmap(); Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 50, 50, true)); return d; } }
UTF-8
Java
18,629
java
CarteFragment.java
Java
[ { "context": "ot.services.MyItemizedOverlay;\n\n\n/**\n * Created by guillaume on 26/11/2015.\n */\n/* Cette classe définit le fra", "end": 1382, "score": 0.8647662997245789, "start": 1373, "tag": "USERNAME", "value": "guillaume" }, { "context": "garage);\n break;\n ...
null
[]
package fr.utt.if26_avargues_jacquot.fragment; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import com.example.guillaume.if26_avargues_jacquot.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.osmdroid.DefaultResourceProxyImpl; import org.osmdroid.ResourceProxy; import org.osmdroid.api.IMapController; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.gestures.RotationGestureOverlay; import java.io.IOException; import java.net.MalformedURLException; import fr.utt.if26_avargues_jacquot.activity.NouveauBonPlanActivity; import fr.utt.if26_avargues_jacquot.services.CheckTokenService; import fr.utt.if26_avargues_jacquot.services.GetBonsPlansService; import fr.utt.if26_avargues_jacquot.services.MyItemizedOverlay; /** * Created by guillaume on 26/11/2015. */ /* Cette classe définit le fragment de la carte C'est à dire lorsque le menu tabs est sur: Carte. Elle hérite de Fragment et implémente View.OnClickListener car cet écran possède des éléments qui sont cliquables: c'est pour que l'utilisateur puisse ajouter un bon plan.*/ public class CarteFragment extends Fragment implements View.OnClickListener { MapView map; /* La méthode onCreateView permet de créer des vues: c'est à dire on dit quel fichier XML doit réprésenter la page pour la carte. De plus, on ajoute les éléments qui sont cliquables pour permettre d'avoir des intéractions par la suite*/ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //On définit le XML a utiliser View rootView = inflater.inflate(R.layout.fragment_carte, container, false); //On met en place le listener sur les éléments souhaités rootView.findViewById(R.id.IMGB_ajouterBonPlan).setOnClickListener(this); rootView.findViewById(R.id.CB_agencesDeTransports).setOnClickListener(this); rootView.findViewById(R.id.CB_alimentations).setOnClickListener(this); rootView.findViewById(R.id.CB_assuranceMaladieEtMutuelles).setOnClickListener(this); rootView.findViewById(R.id.CB_caf).setOnClickListener(this); rootView.findViewById(R.id.CB_distributionsDeBillets).setOnClickListener(this); rootView.findViewById(R.id.CB_emploi).setOnClickListener(this); rootView.findViewById(R.id.CB_evenements).setOnClickListener(this); rootView.findViewById(R.id.CB_garages).setOnClickListener(this); rootView.findViewById(R.id.CB_hopitaux).setOnClickListener(this); rootView.findViewById(R.id.CB_laveries).setOnClickListener(this); rootView.findViewById(R.id.CB_mairies).setOnClickListener(this); rootView.findViewById(R.id.CB_maisonDesEtudiants).setOnClickListener(this); rootView.findViewById(R.id.CB_medecins).setOnClickListener(this); rootView.findViewById(R.id.CB_pharmacies).setOnClickListener(this); rootView.findViewById(R.id.CB_reductionsACourtTerme).setOnClickListener(this); rootView.findViewById(R.id.CB_reductionsALongTerme).setOnClickListener(this); rootView.findViewById(R.id.CB_salleDeSport).setOnClickListener(this); rootView.findViewById(R.id.CB_stades).setOnClickListener(this); rootView.findViewById(R.id.CB_stationsEssences).setOnClickListener(this); rootView.findViewById(R.id.CB_terrains).setOnClickListener(this); //On défini quel élément représente la carte sur l'interface map = (MapView) rootView.findViewById(R.id.map); map.setTileSource(TileSourceFactory.MAPQUESTOSM); map.setBuiltInZoomControls(true); map.setMultiTouchControls(true); IMapController mapController = map.getController(); mapController.setZoom(13); // On met un place directement la vue sur la ville de Troyes GeoPoint startPoint = new GeoPoint(48.3, 4.0833); mapController.setCenter(startPoint); RotationGestureOverlay mRotationGestureOverlay = new RotationGestureOverlay(getContext(), map); mRotationGestureOverlay.setEnabled(true); map.setMultiTouchControls(true); map.getOverlays().add(mRotationGestureOverlay); try { putBonsPlans(map); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return rootView; } /** * La méthode onClick permet de définir une action dès que l'utilisateur clique sur un des éléments défini dans la méhode * * @param v Vue */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.IMGB_ajouterBonPlan: Boolean connecte = false; try { connecte = this.checkToken(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } if (!connecte) { AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create(); alertDialog.setTitle("Connexion requise"); alertDialog.setMessage("Vous devez être connecté pour ajouter un bon plan."); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); } else { // On met en place le passage entre les deux activités sur ce Listener // On passe de l'activité principale à l'activité d'ajout de bon plan. Intent intent = new Intent(getActivity(), NouveauBonPlanActivity.class); startActivity(intent); } break; case R.id.CB_agencesDeTransports: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_agencesDeTransports), "Agence de Transport"); break; case R.id.CB_alimentations: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_alimentations), "Alimentation"); break; case R.id.CB_assuranceMaladieEtMutuelles: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_assuranceMaladieEtMutuelles), "Assurance Maladie et Mutuelles"); break; case R.id.CB_caf: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_caf), "CAF"); break; case R.id.CB_distributionsDeBillets: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_distributionsDeBillets), "Distributeur de billets"); break; case R.id.CB_emploi: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_emploi), "Emploi"); break; case R.id.CB_evenements: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_evenements), "Evènement"); break; case R.id.CB_garages: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_garages), "Garage"); break; case R.id.CB_hopitaux: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_hopitaux), "Hopital"); break; case R.id.CB_laveries: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_laveries), "Laverie"); break; case R.id.CB_mairies: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_mairies), "Mairie"); break; case R.id.CB_maisonDesEtudiants: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_maisonDesEtudiants), "Maison des étudiants"); break; case R.id.CB_medecins: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_medecins), "Médecin"); break; case R.id.CB_pharmacies: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_pharmacies), "Laverie"); break; case R.id.CB_reductionsACourtTerme: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_reductionsACourtTerme), "Réduction à court terme"); break; case R.id.CB_reductionsALongTerme: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_reductionsALongTerme), "Réduction à long terme"); break; case R.id.CB_terrains: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_terrains), "Terrain"); break; case R.id.CB_salleDeSport: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_salleDeSport), "Salle de sport"); break; case R.id.CB_stades: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_stades), "Stade"); break; case R.id.CB_stationsEssences: ShowOrHideType((CheckBox) v.findViewById(R.id.CB_stationsEssences), "Station essence"); break; } } /** * Permet de cacher tous les éléments, sur la carte, en fonction de leur type * * @param type Type du bon plan (ex : CAF, Réduction à court terme, ...) */ private void hideFromMap(String type) { for (int i = 1; i < map.getOverlays().size(); i++) { MyItemizedOverlay overlay = (MyItemizedOverlay) map.getOverlays().get(i); String categorie = overlay.getItem(0).getSnippet(); if (categorie.equals(type)) { Drawable marker = ContextCompat.getDrawable(getContext(), R.drawable.transparent); Bitmap bitmap = ((BitmapDrawable) marker).getBitmap(); Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 1, 1, true)); overlay.getItem(0).setMarker(d); } } } /** * Permet de cacher ou montrer des éléments de la carte en fonction de la catégorie du bon plan. * Ce choix est effectué par l'utilisateur à l'aide des checkbox des filtres * * @param CB Checkbox dont l'état est à observer * @param type Type du bon plan (ex : CAF, Réduction à court terme, ...) */ private void ShowOrHideType(CheckBox CB, String type) { if (!CB.isChecked()) hideFromMap(type); else showOnMap(type); } /** * Permet de montrer tous les éléments, sur la carte, en fonction de leur type * * @param type Type du bon plan (ex : CAF, Réduction à court terme, ...) */ private void showOnMap(String type) { for (int i = 1; i < map.getOverlays().size(); i++) { MyItemizedOverlay overlay = (MyItemizedOverlay) map.getOverlays().get(i); String categorie = overlay.getItem(0).getSnippet(); if (categorie.equals(type)) { Drawable d = getDrawable(type); overlay.getItem(0).setMarker(d); } } } /** * Permet de savoir si l'utilisateur est connecté en vérifiant le token en mémoire. * * @return True si l'utilisateur est correctement authentifié, sinon false. * @throws IOException * @throws JSONException */ public boolean checkToken() throws IOException, JSONException { SharedPreferences settings = getContext().getSharedPreferences("StudenN3_storage", 0); String token = settings.getString("token", ""); CheckTokenService cts = new CheckTokenService(); Boolean checkToken = cts.validateToken(token); if (checkToken) { return true; } else { return false; } } /** * Méthode permettant d'ajouter les bons plans sur la carte, à partir des données en base * * @param map Carte présente sur l'écran * @throws JSONException * @throws IOException * @throws MalformedURLException */ public void putBonsPlans(MapView map) throws JSONException, IOException, MalformedURLException { //On récupère les bons plans depuis le webservice GetBonsPlansService gbps = new GetBonsPlansService(); String bonsPlans = gbps.getCurrentBonsPlans(); JSONArray jsonArrayBonsPlans = new JSONArray(bonsPlans); //Si on a des bons plans à afficher if (jsonArrayBonsPlans != null) { for (int i = 0; i < jsonArrayBonsPlans.length(); i++) { //Pour chaque bon plan, on récupère son titre, son type et les coordonnées pour l'afficher sur la carte JSONObject bonPlan = (JSONObject) jsonArrayBonsPlans.get(i); String bonPlanNom = bonPlan.getString("nom"); String bonPlanType = bonPlan.getString("type"); Double bonPlanLongitude = bonPlan.getDouble("longitude"); Double bonPlanLatitude = bonPlan.getDouble("latitude"); addBPtoMap(map, bonPlanNom, bonPlanType, bonPlanLongitude, bonPlanLatitude); } } } /** * Méthode permettant d'afficher l'icône du bon plan sur la carte * * @param map Carte présente sur l'écran * @param bonPlanNom Titre du bon plan * @param type Type du bon plan * @param bonPlanLongitude Longitude du bon plan * @param bonPlanLatitude Latitude du bon plan */ public void addBPtoMap(MapView map, String bonPlanNom, String type, Double bonPlanLongitude, Double bonPlanLatitude) { // On ajoute une icône sur la carte Drawable marker = getDrawable(type); if (marker != null) { marker.setBounds(-marker.getIntrinsicWidth() / 4, -marker.getIntrinsicHeight(), marker.getIntrinsicWidth() / 4, 0); ResourceProxy resourceProxy = new DefaultResourceProxyImpl(getActivity().getApplicationContext()); MyItemizedOverlay myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy); map.getOverlays().add(myItemizedOverlay); GeoPoint myPoint = new GeoPoint(bonPlanLatitude, bonPlanLongitude); myItemizedOverlay.addItem(myPoint, bonPlanNom, type); } } /** * Récupère la bonne icône en fonction du bon plan * * @param type Type de bon plan * @return Drawable Icone du bon plan correspondant à son type */ public Drawable getDrawable(String type) { Drawable marker = null; switch (type) { case "Agence de Transport": marker = ContextCompat.getDrawable(getContext(), R.drawable.bus); break; case "Alimentation": marker = ContextCompat.getDrawable(getContext(), R.drawable.alimentation); break; case "Assurance Maladie et Mutuelles": marker = ContextCompat.getDrawable(getContext(), R.drawable.assurance_maladie); break; case "CAF": marker = ContextCompat.getDrawable(getContext(), R.drawable.caf_jaune); break; case "Distributeur de billets": marker = ContextCompat.getDrawable(getContext(), R.drawable.distributeurs); break; case "Emploi": marker = ContextCompat.getDrawable(getContext(), R.drawable.emploi); break; case "Evènement": marker = ContextCompat.getDrawable(getContext(), R.drawable.evenement_etudiant); break; case "Garage": marker = ContextCompat.getDrawable(getContext(), R.drawable.garage); break; case "Hopital": marker = ContextCompat.getDrawable(getContext(), R.drawable.hopital); break; case "Laverie": marker = ContextCompat.getDrawable(getContext(), R.drawable.laveries); break; case "Mairie": marker = ContextCompat.getDrawable(getContext(), R.drawable.mairie); break; case "Maison des étudiants": marker = ContextCompat.getDrawable(getContext(), R.drawable.maison_des_etudiants); break; case "Médecin": marker = ContextCompat.getDrawable(getContext(), R.drawable.medecin); break; case "Pharmacie": marker = ContextCompat.getDrawable(getContext(), R.drawable.pharmacie); break; case "Réduction à court terme": marker = ContextCompat.getDrawable(getContext(), R.drawable.court_terme_reduction); break; case "Réduction à long terme": marker = ContextCompat.getDrawable(getContext(), R.drawable.long_terme_reduction); break; case "Salle de sport": marker = ContextCompat.getDrawable(getContext(), R.drawable.salle_de_sport); break; case "Stade": marker = ContextCompat.getDrawable(getContext(), R.drawable.stade); break; case "Station essence": marker = ContextCompat.getDrawable(getContext(), R.drawable.stations_services); break; case "Terrain": marker = ContextCompat.getDrawable(getContext(), R.drawable.terrain); break; default: marker = null; } Bitmap bitmap = ((BitmapDrawable) marker).getBitmap(); Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 50, 50, true)); return d; } }
18,629
0.620489
0.617791
424
42.719341
32.160255
129
false
false
0
0
0
0
0
0
0.716981
false
false
11
db2bdcecd60f5b68002e2acbbaa8b595d34b5474
5,944,234,765,504
2f0f12590cace1965ac793b9656e882359c61dea
/app/src/androidTest/java/es/iessaladillo/pedrojoya/pr05/ui/main/MainActivityTest.java
6f5e18b45ebabaad0c69ec436476d78ab1d1d744
[]
no_license
chitaua/MGC-PR05-OrientationChange-Base-master
https://github.com/chitaua/MGC-PR05-OrientationChange-Base-master
0ae756079adeb3e0a4dae5b02e7777e97dea9949
20c42f7a4d3e31547787b5501e4066786efb6d1f
refs/heads/master
2020-04-04T11:59:49.016000
2018-11-02T19:09:13
2018-11-02T19:09:13
155,910,694
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package es.iessaladillo.pedrojoya.pr05.ui.main; import android.graphics.Typeface; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import androidx.test.espresso.intent.rule.IntentsTestRule; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.LargeTest; import es.iessaladillo.pedrojoya.pr05.R; import es.iessaladillo.pedrojoya.pr05.data.local.Database; import es.iessaladillo.pedrojoya.pr05.data.local.model.Avatar; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard; import static androidx.test.espresso.action.ViewActions.pressImeActionButton; import static androidx.test.espresso.action.ViewActions.replaceText; import static androidx.test.espresso.action.ViewActions.typeText; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.hasErrorText; import static androidx.test.espresso.matcher.ViewMatchers.hasFocus; import static androidx.test.espresso.matcher.ViewMatchers.isEnabled; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withTagValue; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static es.iessaladillo.pedrojoya.pr05.utils.Matchers.withBoldTypeface; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.hamcrest.Matchers.not; @RunWith(AndroidJUnit4.class) @LargeTest public class MainActivityTest { @Rule public final IntentsTestRule<MainActivity> testRule = new IntentsTestRule<>(MainActivity.class); @Before public void setup() { onView(withId(R.id.txtName)).perform(closeSoftKeyboard()); } // Initial state. @Test public void shouldNameHasFocusInitially() { onView(withId(R.id.txtName)).check(matches(hasFocus())); } @Test public void shouldLblNameBeBoldInitially() { onView(withId(R.id.lblName)).check( matches(withBoldTypeface(Typeface.DEFAULT_BOLD.isBold()))); } @Test public void shouldAvatarHasDefaultOneInitially() { Avatar avatar = Database.getInstance().getDefaultAvatar(); onView(withId(R.id.imgAvatar)).check( matches(withTagValue(equalTo(avatar.getImageResId())))); onView(withId(R.id.lblAvatar)).check(matches(withText(avatar.getName()))); } // TextView gets bold when editText gets focus. // We need to make the view visible, so we click first. @Test public void shouldNameBeBoldTypefaceWhenFocus() { onView(withId(R.id.txtName)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblName)).check( matches(withBoldTypeface(Typeface.DEFAULT_BOLD.isBold()))); } @Test public void shouldEmailBeBoldTypefaceWhenFocus() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblEmail)).check( matches(withBoldTypeface(Typeface.DEFAULT_BOLD.isBold()))); } @Test public void shouldPhonenumberBeBoldTypefaceWhenFocus() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblPhonenumber)).check( matches(withBoldTypeface(Typeface.DEFAULT_BOLD.isBold()))); } @Test public void shouldAddressBeBoldTypefaceWhenFocus() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblAddress)).check( matches(withBoldTypeface(Typeface.DEFAULT_BOLD.isBold()))); } @Test public void shouldWebBeBoldTypefaceWhenFocus() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblWeb)).check(matches(withBoldTypeface(true))); } // TextView is not bold when editText loses focus. @Test public void shouldNameLabelBeDefaultTypefaceWhenNoFocus() { onView(withId(R.id.txtName)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblName)).check(matches(withBoldTypeface(Typeface.DEFAULT.isBold()))); } @Test public void shouldEmailLabelBeDefaultTypefaceWhenNoFocus() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.txtName)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblEmail)).check(matches(withBoldTypeface(Typeface.DEFAULT.isBold()))); } @Test public void shouldPhonenumberLabelBeDefaultTypefaceWhenNoFocus() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblPhonenumber)).check( matches(withBoldTypeface(Typeface.DEFAULT.isBold()))); } @Test public void shouldAddressLabelBeDefaultTypefaceWhenNoFocus() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblAddress)).check(matches(withBoldTypeface(Typeface.DEFAULT.isBold()))); } @Test public void shouldWebLabelBeDefaultTypefaceWhenNoFocus() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard()); // We need to close the keyboard so lblWeb is visible when checking. onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblWeb)).check(matches(withBoldTypeface(Typeface.DEFAULT.isBold()))); } // ImageView should get disabled when EditText content is invalid. @Test public void shouldEmailIconBeDisabledWhenInvalidData() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.imgEmail)).check(matches(not(isEnabled()))); } @Test public void shouldPhonenumberIconBeDisabledWhenInvalidData() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard(), replaceText("1")); onView(withId(R.id.imgPhonenumber)).check(matches(not(isEnabled()))); } @Test public void shouldAddressIconBeDisabledWhenInvalidData() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard(), replaceText("")); onView(withId(R.id.imgAddress)).check(matches(not(isEnabled()))); } @Test public void shouldWebIconBeDisabledWhenInvalidData() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.imgWeb)).check(matches(not(isEnabled()))); } // ImageView should get enabled when EditText content is valid. @Test public void shouldEmailIconBeEnabledWhenValidData() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard(), replaceText("test@test.com")); onView(withId(R.id.imgEmail)).check(matches(isEnabled())); } @Test public void shouldPhonenumberIconBeEnabledWhenValidData() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard(), replaceText("666666666")); onView(withId(R.id.imgPhonenumber)).check(matches(isEnabled())); } @Test public void shouldAddressIconBeEnabledWhenValidData() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.imgAddress)).check(matches(isEnabled())); } @Test public void shouldWebIconBeEnabledWhenValidData() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard(), replaceText("http://www.test.com")); onView(withId(R.id.imgWeb)).check(matches(isEnabled())); } // TextView should get disabled when EditText content is invalid. @Test public void shouldEmailLabelBeDisabledWhenInvalidData() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.lblEmail)).check(matches(not(isEnabled()))); } @Test public void shouldPhonenumberLabelBeDisabledWhenInvalidData() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard(), replaceText("1")); onView(withId(R.id.lblPhonenumber)).check(matches(not(isEnabled()))); } @Test public void shouldAddressLabelBeDisabledWhenInvalidData() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard(), replaceText("")); onView(withId(R.id.lblAddress)).check(matches(not(isEnabled()))); } @Test public void shouldWebLabelBeDisabledWhenInvalidData() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.lblWeb)).check(matches(not(isEnabled()))); } // TextView should get enabled when EditText content is valid. @Test public void shouldEmailLabelBeEnabledWhenValidData() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard(), replaceText("test@test.com")); onView(withId(R.id.lblEmail)).check(matches(isEnabled())); } @Test public void shouldPhonenumberLabelBeEnabledWhenValidData() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard(), replaceText("666666666")); onView(withId(R.id.lblPhonenumber)).check(matches(isEnabled())); } @Test public void shouldAddressLabelBeEnabledWhenValidData() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.lblAddress)).check(matches(isEnabled())); } @Test public void shouldWebLabelBeEnabledWhenValidData() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard(), replaceText("http://www.test.com")); onView(withId(R.id.lblWeb)).check(matches(isEnabled())); } // EditText should show error when content is invalid. @Test public void shouldNameEditTextShowErrorWhenInvalidData() { onView(withId(R.id.txtName)).perform(click(), closeSoftKeyboard(), replaceText("")); onView(withId(R.id.txtName)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); } @Test public void shouldEmailEditTextShowErrorWhenInvalidData() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.txtEmail)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); } @Test public void shouldPhonenumberEditTextShowErrorWhenInvalidData() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard(), replaceText("1")); onView(withId(R.id.txtPhonenumber)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); } @Test public void shouldAddressEditTextShowErrorWhenInvalidData() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard(), replaceText("")); onView(withId(R.id.txtAddress)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); } @Test public void shouldWebEditTextShowErrorWhenInvalidData() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.txtWeb)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); } // EditText should show no error when content is valid. @Test public void shouldNameEditTextShowNoErrorWhenValidData() { onView(withId(R.id.txtName)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.txtName)).check(matches(hasErrorText(isEmptyOrNullString()))); } @Test public void shouldEmailEditTextShowNoErrorWhenValidData() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard(), replaceText("test@test.com")); onView(withId(R.id.txtEmail)).check(matches(hasErrorText(isEmptyOrNullString()))); } @Test public void shouldPhonenumberEditTextShowNoErrorWhenValidData() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard(), replaceText("666666666")); onView(withId(R.id.txtPhonenumber)).check(matches(hasErrorText(isEmptyOrNullString()))); } @Test public void shouldAddressEditTextShowNoErrorWhenValidData() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.txtAddress)).check(matches(hasErrorText(isEmptyOrNullString()))); } @Test public void shouldWebEditTextShowNoErrorWhenValidData() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard(), replaceText("http://www.test.com")); onView(withId(R.id.txtWeb)).check(matches(hasErrorText(isEmptyOrNullString()))); } // ImageView should be enabled initially. @Test public void shouldEmailIconBeEnabledInitially() { onView(withId(R.id.imgEmail)).check(matches(isEnabled())); } @Test public void shouldPhonenumberIconBeEnabledInitially() { onView(withId(R.id.imgPhonenumber)).check(matches(isEnabled())); } @Test public void shouldAddressIconBeEnabledInitially() { onView(withId(R.id.imgAddress)).check(matches(isEnabled())); } @Test public void shouldWebIconBeEnabledInitially() { onView(withId(R.id.imgWeb)).check(matches(isEnabled())); } // Snackbar @Test public void shouldShowErrorSnackbarWhenSaveMenuItemClickedOnInvalidForm() { onView(withId(R.id.mnuSave)).perform(click()); onView(withId(R.id.imgEmail)).check(matches(not(isEnabled()))); onView(withId(R.id.imgPhonenumber)).check(matches(not(isEnabled()))); onView(withId(R.id.imgAddress)).check(matches(not(isEnabled()))); onView(withId(R.id.imgWeb)).check(matches(not(isEnabled()))); onView(withId(R.id.txtName)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); onView(withId(R.id.txtEmail)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); onView(withId(R.id.txtPhonenumber)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); onView(withId(R.id.txtAddress)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); onView(withId(R.id.txtWeb)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); onView(withId(com.google.android.material.R.id.snackbar_text)).check( matches(withText(R.string.main_error_saving))); } @Test public void shouldShowSuccessSnackbarWhenSaveMenuItemClickedOnValidForm() { onView(withId(R.id.txtName)).perform(click(), replaceText("test"), closeSoftKeyboard()); onView(withId(R.id.txtEmail)).perform(click(), replaceText("test@test.com"), closeSoftKeyboard()); onView(withId(R.id.txtPhonenumber)).perform(click(), replaceText("666666666"), closeSoftKeyboard()); onView(withId(R.id.txtAddress)).perform(click(), replaceText("test"), closeSoftKeyboard()); onView(withId(R.id.txtWeb)).perform(click(), replaceText("http://www.test.com"), closeSoftKeyboard()); onView(withId(R.id.mnuSave)).perform(click()); onView(withId(com.google.android.material.R.id.snackbar_text)).check( matches(withText(R.string.main_saved_succesfully))); } // ImeOptions. @Test public void shouldNameEditTextGoForwardWhenImeOptionsClicked() { onView(withId(R.id.txtName)).perform(typeText("test"), pressImeActionButton()); onView(withId(R.id.txtEmail)).perform(closeSoftKeyboard()).check(matches(hasFocus())); } @Test public void shouldEmailEditTextGoForwardWhenImeOptionsClicked() { onView(withId(R.id.txtEmail)).perform(typeText("test"), pressImeActionButton()); onView(withId(R.id.txtPhonenumber)).perform(closeSoftKeyboard()).check(matches(hasFocus())); } @Test public void shouldPhonenumberEditTextGoForwardWhenImeOptionsClicked() { onView(withId(R.id.txtPhonenumber)).perform(typeText ("66666666"), pressImeActionButton()); onView(withId(R.id.txtAddress)).perform(closeSoftKeyboard()).check(matches(hasFocus())); } @Test public void shouldAddressEditTextGoForwardWhenImeOptionsClicked() { onView(withId(R.id.txtAddress)).perform(typeText("test"), pressImeActionButton()); onView(withId(R.id.txtWeb)).perform(closeSoftKeyboard()).check(matches(hasFocus())); } @Test public void shouldWebEditTextSaveWhenImeOptionsClicked() { onView(withId(R.id.txtWeb)).perform(typeText ("test"), pressImeActionButton()); onView(withId(com.google.android.material.R.id.snackbar_text)).check( matches(withText(R.string.main_error_saving))); } }
UTF-8
Java
17,887
java
MainActivityTest.java
Java
[ { "context": "closeSoftKeyboard(),\n replaceText(\"test@test.com\"));\n onView(withId(R.id.imgEmail)).check(m", "end": 7203, "score": 0.9998971819877625, "start": 7190, "tag": "EMAIL", "value": "test@test.com" }, { "context": "closeSoftKeyboard(),\n ...
null
[]
package es.iessaladillo.pedrojoya.pr05.ui.main; import android.graphics.Typeface; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import androidx.test.espresso.intent.rule.IntentsTestRule; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.LargeTest; import es.iessaladillo.pedrojoya.pr05.R; import es.iessaladillo.pedrojoya.pr05.data.local.Database; import es.iessaladillo.pedrojoya.pr05.data.local.model.Avatar; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard; import static androidx.test.espresso.action.ViewActions.pressImeActionButton; import static androidx.test.espresso.action.ViewActions.replaceText; import static androidx.test.espresso.action.ViewActions.typeText; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.hasErrorText; import static androidx.test.espresso.matcher.ViewMatchers.hasFocus; import static androidx.test.espresso.matcher.ViewMatchers.isEnabled; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withTagValue; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static es.iessaladillo.pedrojoya.pr05.utils.Matchers.withBoldTypeface; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.hamcrest.Matchers.not; @RunWith(AndroidJUnit4.class) @LargeTest public class MainActivityTest { @Rule public final IntentsTestRule<MainActivity> testRule = new IntentsTestRule<>(MainActivity.class); @Before public void setup() { onView(withId(R.id.txtName)).perform(closeSoftKeyboard()); } // Initial state. @Test public void shouldNameHasFocusInitially() { onView(withId(R.id.txtName)).check(matches(hasFocus())); } @Test public void shouldLblNameBeBoldInitially() { onView(withId(R.id.lblName)).check( matches(withBoldTypeface(Typeface.DEFAULT_BOLD.isBold()))); } @Test public void shouldAvatarHasDefaultOneInitially() { Avatar avatar = Database.getInstance().getDefaultAvatar(); onView(withId(R.id.imgAvatar)).check( matches(withTagValue(equalTo(avatar.getImageResId())))); onView(withId(R.id.lblAvatar)).check(matches(withText(avatar.getName()))); } // TextView gets bold when editText gets focus. // We need to make the view visible, so we click first. @Test public void shouldNameBeBoldTypefaceWhenFocus() { onView(withId(R.id.txtName)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblName)).check( matches(withBoldTypeface(Typeface.DEFAULT_BOLD.isBold()))); } @Test public void shouldEmailBeBoldTypefaceWhenFocus() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblEmail)).check( matches(withBoldTypeface(Typeface.DEFAULT_BOLD.isBold()))); } @Test public void shouldPhonenumberBeBoldTypefaceWhenFocus() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblPhonenumber)).check( matches(withBoldTypeface(Typeface.DEFAULT_BOLD.isBold()))); } @Test public void shouldAddressBeBoldTypefaceWhenFocus() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblAddress)).check( matches(withBoldTypeface(Typeface.DEFAULT_BOLD.isBold()))); } @Test public void shouldWebBeBoldTypefaceWhenFocus() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblWeb)).check(matches(withBoldTypeface(true))); } // TextView is not bold when editText loses focus. @Test public void shouldNameLabelBeDefaultTypefaceWhenNoFocus() { onView(withId(R.id.txtName)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblName)).check(matches(withBoldTypeface(Typeface.DEFAULT.isBold()))); } @Test public void shouldEmailLabelBeDefaultTypefaceWhenNoFocus() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.txtName)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblEmail)).check(matches(withBoldTypeface(Typeface.DEFAULT.isBold()))); } @Test public void shouldPhonenumberLabelBeDefaultTypefaceWhenNoFocus() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblPhonenumber)).check( matches(withBoldTypeface(Typeface.DEFAULT.isBold()))); } @Test public void shouldAddressLabelBeDefaultTypefaceWhenNoFocus() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblAddress)).check(matches(withBoldTypeface(Typeface.DEFAULT.isBold()))); } @Test public void shouldWebLabelBeDefaultTypefaceWhenNoFocus() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard()); // We need to close the keyboard so lblWeb is visible when checking. onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard()); onView(withId(R.id.lblWeb)).check(matches(withBoldTypeface(Typeface.DEFAULT.isBold()))); } // ImageView should get disabled when EditText content is invalid. @Test public void shouldEmailIconBeDisabledWhenInvalidData() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.imgEmail)).check(matches(not(isEnabled()))); } @Test public void shouldPhonenumberIconBeDisabledWhenInvalidData() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard(), replaceText("1")); onView(withId(R.id.imgPhonenumber)).check(matches(not(isEnabled()))); } @Test public void shouldAddressIconBeDisabledWhenInvalidData() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard(), replaceText("")); onView(withId(R.id.imgAddress)).check(matches(not(isEnabled()))); } @Test public void shouldWebIconBeDisabledWhenInvalidData() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.imgWeb)).check(matches(not(isEnabled()))); } // ImageView should get enabled when EditText content is valid. @Test public void shouldEmailIconBeEnabledWhenValidData() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard(), replaceText("<EMAIL>")); onView(withId(R.id.imgEmail)).check(matches(isEnabled())); } @Test public void shouldPhonenumberIconBeEnabledWhenValidData() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard(), replaceText("666666666")); onView(withId(R.id.imgPhonenumber)).check(matches(isEnabled())); } @Test public void shouldAddressIconBeEnabledWhenValidData() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.imgAddress)).check(matches(isEnabled())); } @Test public void shouldWebIconBeEnabledWhenValidData() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard(), replaceText("http://www.test.com")); onView(withId(R.id.imgWeb)).check(matches(isEnabled())); } // TextView should get disabled when EditText content is invalid. @Test public void shouldEmailLabelBeDisabledWhenInvalidData() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.lblEmail)).check(matches(not(isEnabled()))); } @Test public void shouldPhonenumberLabelBeDisabledWhenInvalidData() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard(), replaceText("1")); onView(withId(R.id.lblPhonenumber)).check(matches(not(isEnabled()))); } @Test public void shouldAddressLabelBeDisabledWhenInvalidData() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard(), replaceText("")); onView(withId(R.id.lblAddress)).check(matches(not(isEnabled()))); } @Test public void shouldWebLabelBeDisabledWhenInvalidData() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.lblWeb)).check(matches(not(isEnabled()))); } // TextView should get enabled when EditText content is valid. @Test public void shouldEmailLabelBeEnabledWhenValidData() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard(), replaceText("<EMAIL>")); onView(withId(R.id.lblEmail)).check(matches(isEnabled())); } @Test public void shouldPhonenumberLabelBeEnabledWhenValidData() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard(), replaceText("666666666")); onView(withId(R.id.lblPhonenumber)).check(matches(isEnabled())); } @Test public void shouldAddressLabelBeEnabledWhenValidData() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.lblAddress)).check(matches(isEnabled())); } @Test public void shouldWebLabelBeEnabledWhenValidData() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard(), replaceText("http://www.test.com")); onView(withId(R.id.lblWeb)).check(matches(isEnabled())); } // EditText should show error when content is invalid. @Test public void shouldNameEditTextShowErrorWhenInvalidData() { onView(withId(R.id.txtName)).perform(click(), closeSoftKeyboard(), replaceText("")); onView(withId(R.id.txtName)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); } @Test public void shouldEmailEditTextShowErrorWhenInvalidData() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.txtEmail)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); } @Test public void shouldPhonenumberEditTextShowErrorWhenInvalidData() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard(), replaceText("1")); onView(withId(R.id.txtPhonenumber)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); } @Test public void shouldAddressEditTextShowErrorWhenInvalidData() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard(), replaceText("")); onView(withId(R.id.txtAddress)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); } @Test public void shouldWebEditTextShowErrorWhenInvalidData() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.txtWeb)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); } // EditText should show no error when content is valid. @Test public void shouldNameEditTextShowNoErrorWhenValidData() { onView(withId(R.id.txtName)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.txtName)).check(matches(hasErrorText(isEmptyOrNullString()))); } @Test public void shouldEmailEditTextShowNoErrorWhenValidData() { onView(withId(R.id.txtEmail)).perform(click(), closeSoftKeyboard(), replaceText("<EMAIL>")); onView(withId(R.id.txtEmail)).check(matches(hasErrorText(isEmptyOrNullString()))); } @Test public void shouldPhonenumberEditTextShowNoErrorWhenValidData() { onView(withId(R.id.txtPhonenumber)).perform(click(), closeSoftKeyboard(), replaceText("666666666")); onView(withId(R.id.txtPhonenumber)).check(matches(hasErrorText(isEmptyOrNullString()))); } @Test public void shouldAddressEditTextShowNoErrorWhenValidData() { onView(withId(R.id.txtAddress)).perform(click(), closeSoftKeyboard(), replaceText("test")); onView(withId(R.id.txtAddress)).check(matches(hasErrorText(isEmptyOrNullString()))); } @Test public void shouldWebEditTextShowNoErrorWhenValidData() { onView(withId(R.id.txtWeb)).perform(click(), closeSoftKeyboard(), replaceText("http://www.test.com")); onView(withId(R.id.txtWeb)).check(matches(hasErrorText(isEmptyOrNullString()))); } // ImageView should be enabled initially. @Test public void shouldEmailIconBeEnabledInitially() { onView(withId(R.id.imgEmail)).check(matches(isEnabled())); } @Test public void shouldPhonenumberIconBeEnabledInitially() { onView(withId(R.id.imgPhonenumber)).check(matches(isEnabled())); } @Test public void shouldAddressIconBeEnabledInitially() { onView(withId(R.id.imgAddress)).check(matches(isEnabled())); } @Test public void shouldWebIconBeEnabledInitially() { onView(withId(R.id.imgWeb)).check(matches(isEnabled())); } // Snackbar @Test public void shouldShowErrorSnackbarWhenSaveMenuItemClickedOnInvalidForm() { onView(withId(R.id.mnuSave)).perform(click()); onView(withId(R.id.imgEmail)).check(matches(not(isEnabled()))); onView(withId(R.id.imgPhonenumber)).check(matches(not(isEnabled()))); onView(withId(R.id.imgAddress)).check(matches(not(isEnabled()))); onView(withId(R.id.imgWeb)).check(matches(not(isEnabled()))); onView(withId(R.id.txtName)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); onView(withId(R.id.txtEmail)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); onView(withId(R.id.txtPhonenumber)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); onView(withId(R.id.txtAddress)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); onView(withId(R.id.txtWeb)).check(matches(hasErrorText( testRule.getActivity().getString(R.string.main_invalid_data)))); onView(withId(com.google.android.material.R.id.snackbar_text)).check( matches(withText(R.string.main_error_saving))); } @Test public void shouldShowSuccessSnackbarWhenSaveMenuItemClickedOnValidForm() { onView(withId(R.id.txtName)).perform(click(), replaceText("test"), closeSoftKeyboard()); onView(withId(R.id.txtEmail)).perform(click(), replaceText("<EMAIL>"), closeSoftKeyboard()); onView(withId(R.id.txtPhonenumber)).perform(click(), replaceText("666666666"), closeSoftKeyboard()); onView(withId(R.id.txtAddress)).perform(click(), replaceText("test"), closeSoftKeyboard()); onView(withId(R.id.txtWeb)).perform(click(), replaceText("http://www.test.com"), closeSoftKeyboard()); onView(withId(R.id.mnuSave)).perform(click()); onView(withId(com.google.android.material.R.id.snackbar_text)).check( matches(withText(R.string.main_saved_succesfully))); } // ImeOptions. @Test public void shouldNameEditTextGoForwardWhenImeOptionsClicked() { onView(withId(R.id.txtName)).perform(typeText("test"), pressImeActionButton()); onView(withId(R.id.txtEmail)).perform(closeSoftKeyboard()).check(matches(hasFocus())); } @Test public void shouldEmailEditTextGoForwardWhenImeOptionsClicked() { onView(withId(R.id.txtEmail)).perform(typeText("test"), pressImeActionButton()); onView(withId(R.id.txtPhonenumber)).perform(closeSoftKeyboard()).check(matches(hasFocus())); } @Test public void shouldPhonenumberEditTextGoForwardWhenImeOptionsClicked() { onView(withId(R.id.txtPhonenumber)).perform(typeText ("66666666"), pressImeActionButton()); onView(withId(R.id.txtAddress)).perform(closeSoftKeyboard()).check(matches(hasFocus())); } @Test public void shouldAddressEditTextGoForwardWhenImeOptionsClicked() { onView(withId(R.id.txtAddress)).perform(typeText("test"), pressImeActionButton()); onView(withId(R.id.txtWeb)).perform(closeSoftKeyboard()).check(matches(hasFocus())); } @Test public void shouldWebEditTextSaveWhenImeOptionsClicked() { onView(withId(R.id.txtWeb)).perform(typeText ("test"), pressImeActionButton()); onView(withId(com.google.android.material.R.id.snackbar_text)).check( matches(withText(R.string.main_error_saving))); } }
17,863
0.686644
0.683345
430
40.597675
33.63924
100
false
false
0
0
0
0
0
0
0.530233
false
false
11
1c532eb17aed774e00ae2db90caee71a66c8ad54
12,335,146,108,500
1c829cbd333776e1371dd100e2a23e0a64844f03
/app/src/main/java/com/rwz/mvvmsdk/config/IntentCode.java
3374e02e6b677ccf0d76bb0b0214b6756edcf88f
[]
no_license
rwz657026189/mvvmframe
https://github.com/rwz657026189/mvvmframe
581ccb3906c273edc204025344ffa31e6a96d22e
453f763749dbde724720b6d8192a7a8332de72a5
refs/heads/master
2020-04-17T03:53:17.900000
2019-11-11T04:42:06
2019-11-11T04:42:06
166,204,620
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rwz.mvvmsdk.config; public interface IntentCode { //登录请求码 int REQUEST_CODE_LOGIN = 101; }
UTF-8
Java
125
java
IntentCode.java
Java
[]
null
[]
package com.rwz.mvvmsdk.config; public interface IntentCode { //登录请求码 int REQUEST_CODE_LOGIN = 101; }
125
0.678261
0.652174
10
10.5
13.822083
33
false
false
0
0
0
0
0
0
0.2
false
false
11
6242544b74b4702540c9b3c9e05edab13fe20aad
18,408,229,839,953
69d775b376a0a33550901fc9b5fa963ecd4a0910
/app/src/main/java/com/example/niloychowdhury/groceryshopmanagement/Activity/SubCategoryActivity.java
5abc017d6bc3e9f26ccfddc338897692fadd0379
[]
no_license
Niloy2424/GroceryShopManagement
https://github.com/Niloy2424/GroceryShopManagement
5bcf27664691fc6e025d936a08bd7a09f969f144
a0ad1e914960b33d0900bd95fb354976ab227161
refs/heads/master
2021-07-18T05:04:01.902000
2017-10-26T02:21:54
2017-10-26T02:21:54
108,350,537
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.niloychowdhury.groceryshopmanagement.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.example.niloychowdhury.groceryshopmanagement.Controller.CategaryManager; import com.example.niloychowdhury.groceryshopmanagement.Controller.SpinnerAdapter; import com.example.niloychowdhury.groceryshopmanagement.Controller.SubCategoryManager; import com.example.niloychowdhury.groceryshopmanagement.Model.Categary; import com.example.niloychowdhury.groceryshopmanagement.Model.SubCategary; import com.example.niloychowdhury.groceryshopmanagement.R; import java.util.ArrayList; public class SubCategoryActivity extends AppCompatActivity { public EditText subCategoryNameET; public EditText saleET; public EditText stockET; public EditText priceET; public Button addSubItemButton; public Spinner categorySpinner; public Spinner statusSpinner; String subCategoryName; double sale; double stock; double price; String status; int categoryID; public CategaryManager categaryManager; public ArrayList<Categary>categories; public ArrayList<String>categoryNames=new ArrayList<>(); public SubCategary aSubCategory; public SubCategoryManager subCategoryManager; public ArrayList<SubCategary>subCategaries; public ArrayList<String> statuses; public int recivedSubCatageryID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sub_category); subCategoryNameET= (EditText) findViewById(R.id.subCategoryNameET); saleET= (EditText) findViewById(R.id.saleET); stockET= (EditText) findViewById(R.id.stockET); priceET= (EditText) findViewById(R.id.priceET); categorySpinner= (Spinner) findViewById(R.id.categorySpinner); statusSpinner= (Spinner) findViewById(R.id.statusSpinner); addSubItemButton= (Button) findViewById(R.id.addSubItemButton); addValueInSpinner(); categaryManager=new CategaryManager(this); addValueInCategarySpinner(); recivedSubCatageryID=getIntent().getIntExtra("SubCategaryIDSent",0); Toast.makeText(this, "ggdgdt"+recivedSubCatageryID, Toast.LENGTH_SHORT).show(); if (recivedSubCatageryID!=0) { addSubItemButton.setText("UPDATE"); aSubCategory=subCategoryManager.getSelectedSubCategary(recivedSubCatageryID); subCategoryNameET.setText(aSubCategory.getSubCategoryName()); priceET.setText(String.valueOf(aSubCategory.getPrice())); saleET.setText(String.valueOf(aSubCategory.getSale())); stockET.setText(String.valueOf(aSubCategory.getStock())); statusSpinner.setSelection ( statuses.indexOf(aSubCategory.getStatus()) ); categorySpinner.setSelection ( categoryNames.indexOf(aSubCategory.getCategoryID()) ); } } public void addSubItemButton(View view) { sale=Double.valueOf(saleET.getText().toString()); price=Double.valueOf(priceET.getText().toString()); stock=Double.valueOf(stockET.getText().toString()); subCategoryName=subCategoryNameET.getText().toString(); status=statusSpinner.getSelectedItem().toString(); aSubCategory=new SubCategary(subCategoryName,sale,stock,price,status,categoryID); subCategoryManager = new SubCategoryManager(this); boolean insert=subCategoryManager.addSubCategory(aSubCategory); if (insert) { Toast.makeText(this, "Sub Category is Added Successfully", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, " Sorry , Sub Category is not Added", Toast.LENGTH_SHORT).show(); } } public void addValueInSpinner() { statuses = new ArrayList<>(); statuses.add("Active"); statuses.add("Inactive"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, statuses); // ArrayAdapter adapter= ArrayAdapter.createFromResource(this,R.array.status,android.R.layout.simple_spinner_item); statusSpinner.setAdapter(adapter); } public void addValueInCategarySpinner() { categories=categaryManager.getAllActiveCategary(); for (Categary category:categories) { String categoryName= category.getCategaryName(); categoryNames.add(categoryName); } SpinnerAdapter adapter=new SpinnerAdapter(this,categoryNames); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); categorySpinner.setAdapter(adapter); categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { categoryID=categories.get(position).getId(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void ShowButton(View view) { Intent intent=new Intent(this,ShowItemActivity.class); subCategoryManager=new SubCategoryManager(this); subCategaries=subCategoryManager.getSubCategory(); intent.putExtra("SubCategory",subCategaries); startActivity(intent); } }
UTF-8
Java
5,712
java
SubCategoryActivity.java
Java
[]
null
[]
package com.example.niloychowdhury.groceryshopmanagement.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.example.niloychowdhury.groceryshopmanagement.Controller.CategaryManager; import com.example.niloychowdhury.groceryshopmanagement.Controller.SpinnerAdapter; import com.example.niloychowdhury.groceryshopmanagement.Controller.SubCategoryManager; import com.example.niloychowdhury.groceryshopmanagement.Model.Categary; import com.example.niloychowdhury.groceryshopmanagement.Model.SubCategary; import com.example.niloychowdhury.groceryshopmanagement.R; import java.util.ArrayList; public class SubCategoryActivity extends AppCompatActivity { public EditText subCategoryNameET; public EditText saleET; public EditText stockET; public EditText priceET; public Button addSubItemButton; public Spinner categorySpinner; public Spinner statusSpinner; String subCategoryName; double sale; double stock; double price; String status; int categoryID; public CategaryManager categaryManager; public ArrayList<Categary>categories; public ArrayList<String>categoryNames=new ArrayList<>(); public SubCategary aSubCategory; public SubCategoryManager subCategoryManager; public ArrayList<SubCategary>subCategaries; public ArrayList<String> statuses; public int recivedSubCatageryID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sub_category); subCategoryNameET= (EditText) findViewById(R.id.subCategoryNameET); saleET= (EditText) findViewById(R.id.saleET); stockET= (EditText) findViewById(R.id.stockET); priceET= (EditText) findViewById(R.id.priceET); categorySpinner= (Spinner) findViewById(R.id.categorySpinner); statusSpinner= (Spinner) findViewById(R.id.statusSpinner); addSubItemButton= (Button) findViewById(R.id.addSubItemButton); addValueInSpinner(); categaryManager=new CategaryManager(this); addValueInCategarySpinner(); recivedSubCatageryID=getIntent().getIntExtra("SubCategaryIDSent",0); Toast.makeText(this, "ggdgdt"+recivedSubCatageryID, Toast.LENGTH_SHORT).show(); if (recivedSubCatageryID!=0) { addSubItemButton.setText("UPDATE"); aSubCategory=subCategoryManager.getSelectedSubCategary(recivedSubCatageryID); subCategoryNameET.setText(aSubCategory.getSubCategoryName()); priceET.setText(String.valueOf(aSubCategory.getPrice())); saleET.setText(String.valueOf(aSubCategory.getSale())); stockET.setText(String.valueOf(aSubCategory.getStock())); statusSpinner.setSelection ( statuses.indexOf(aSubCategory.getStatus()) ); categorySpinner.setSelection ( categoryNames.indexOf(aSubCategory.getCategoryID()) ); } } public void addSubItemButton(View view) { sale=Double.valueOf(saleET.getText().toString()); price=Double.valueOf(priceET.getText().toString()); stock=Double.valueOf(stockET.getText().toString()); subCategoryName=subCategoryNameET.getText().toString(); status=statusSpinner.getSelectedItem().toString(); aSubCategory=new SubCategary(subCategoryName,sale,stock,price,status,categoryID); subCategoryManager = new SubCategoryManager(this); boolean insert=subCategoryManager.addSubCategory(aSubCategory); if (insert) { Toast.makeText(this, "Sub Category is Added Successfully", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, " Sorry , Sub Category is not Added", Toast.LENGTH_SHORT).show(); } } public void addValueInSpinner() { statuses = new ArrayList<>(); statuses.add("Active"); statuses.add("Inactive"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, statuses); // ArrayAdapter adapter= ArrayAdapter.createFromResource(this,R.array.status,android.R.layout.simple_spinner_item); statusSpinner.setAdapter(adapter); } public void addValueInCategarySpinner() { categories=categaryManager.getAllActiveCategary(); for (Categary category:categories) { String categoryName= category.getCategaryName(); categoryNames.add(categoryName); } SpinnerAdapter adapter=new SpinnerAdapter(this,categoryNames); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); categorySpinner.setAdapter(adapter); categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { categoryID=categories.get(position).getId(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void ShowButton(View view) { Intent intent=new Intent(this,ShowItemActivity.class); subCategoryManager=new SubCategoryManager(this); subCategaries=subCategoryManager.getSubCategory(); intent.putExtra("SubCategory",subCategaries); startActivity(intent); } }
5,712
0.718312
0.717787
150
37.080002
30.258116
127
false
false
0
0
0
0
0
0
0.753333
false
false
11
a9b087270088f8fb2d3cf76fdb62b88c5064e8b7
20,538,533,621,402
88fba8ac1910c69c0d61adbf39a1b6454832df9b
/RxjavaRetrofitPractice/src/main/java/com/example/myapplication/subcribers/SubcriberOnNextListener.java
b9943b3c8f2e361612cc6c2779df0719bbcf8607
[]
no_license
wangrenqi/AndroidPractice
https://github.com/wangrenqi/AndroidPractice
147edf94d69d488d8e6caa1e0c6598549696738f
88f2e4d125ebfb5a131486ca63fe79ba5006eed0
refs/heads/master
2019-07-31T20:26:39.614000
2016-12-18T16:17:16
2016-12-18T16:17:16
75,547,895
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.myapplication.subcribers; import java.lang.reflect.Type; import static android.icu.lang.UCharacter.GraphemeClusterBreak.T; /** * Created by Mccree on 11/12/2016. */ public interface SubcriberOnNextListener<T> { void onNext(T t); }
UTF-8
Java
261
java
SubcriberOnNextListener.java
Java
[ { "context": "aracter.GraphemeClusterBreak.T;\n\n/**\n * Created by Mccree on 11/12/2016.\n */\n\npublic interface SubcriberOnN", "end": 170, "score": 0.999434769153595, "start": 164, "tag": "USERNAME", "value": "Mccree" } ]
null
[]
package com.example.myapplication.subcribers; import java.lang.reflect.Type; import static android.icu.lang.UCharacter.GraphemeClusterBreak.T; /** * Created by Mccree on 11/12/2016. */ public interface SubcriberOnNextListener<T> { void onNext(T t); }
261
0.758621
0.727969
13
19.076923
21.713028
65
false
false
0
0
0
0
0
0
0.307692
false
false
11
4a19ac24ecbf64924122b2d47499e58b69dc585e
12,644,383,768,000
3ac481db9df3e85898124abd149f1613cc30f507
/src/pack1/RedZombieDie.java
cba1631c53a1143c5a5d5eefa941c2d8a9449453
[]
no_license
TheRealGangsir/ZombieDice
https://github.com/TheRealGangsir/ZombieDice
ddb2d34339141919357fbe3455c3dc2e8d4d7cf5
ffe08e4a5b63a37d3db44dd437a10328d12fe514
refs/heads/master
2021-01-22T14:01:59.092000
2015-04-30T18:19:19
2015-04-30T18:19:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pack1; public class RedZombieDie extends ZombieDie { public RedZombieDie(int dieColour) { super(dieColour); } void roll() { int random = ((int) (Math.random() * 6) + 1); if (random <= 2) //2runner { value = ZombieDie.RUNNER;//set value } else if (random == 3) //1brain { value = ZombieDie.BRAIN; //set value } else if (random >= 4) //3shot { value = ZombieDie.SHOT; //set value } } }
UTF-8
Java
521
java
RedZombieDie.java
Java
[]
null
[]
package pack1; public class RedZombieDie extends ZombieDie { public RedZombieDie(int dieColour) { super(dieColour); } void roll() { int random = ((int) (Math.random() * 6) + 1); if (random <= 2) //2runner { value = ZombieDie.RUNNER;//set value } else if (random == 3) //1brain { value = ZombieDie.BRAIN; //set value } else if (random >= 4) //3shot { value = ZombieDie.SHOT; //set value } } }
521
0.50096
0.483685
24
20.708334
19.062351
53
false
false
0
0
0
0
0
0
0.25
false
false
11
0f158cce8441f3f4c0677b36bd60035c4fe9e08f
31,997,506,368,435
16ed72e751dc1393912eb2ef3a830033831862c2
/dataformats/src/test/java/dk/dma/embryo/dataformats/model/ForecastDataIdTest.java
09841864a96153eed1e555a97b97c5c1daf48990
[ "Apache-2.0" ]
permissive
maritime-web/Enav-Services
https://github.com/maritime-web/Enav-Services
43126ac447e82a03834cb49b283abf27432b6de0
e0329646b924d74b7dc45dd2ca21a6ebdde31d9d
refs/heads/master
2022-12-17T17:39:39.004000
2020-04-20T11:36:38
2020-04-20T11:36:38
50,661,158
1
1
Apache-2.0
false
2022-12-05T23:33:40
2016-01-29T12:30:32
2020-04-20T11:36:51
2022-12-05T23:33:40
122,376
1
0
27
Java
false
false
/* Copyright (c) 2011 Danish Maritime Authority. * * 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 dk.dma.embryo.dataformats.model; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * Created by Steen on 12-01-2016. */ public class ForecastDataIdTest { @Test public void shouldCreateIdStringByConcatenatingConstructorInputParameters() throws Exception { String area = "NE"; ForecastProvider provider = ForecastProvider.DMI; Type type = Type.CURRENT_FORECAST; ForecastDataId cut = new ForecastDataId(area, provider, type); assertThat(cut.getId(), is(area + provider + type)); } @Test(expected = NullPointerException.class) public void shouldRequireNonNullValueForArea() throws Exception { String area = null; ForecastProvider provider = ForecastProvider.DMI; Type type = Type.CURRENT_FORECAST; new ForecastDataId(area, provider, type); } @Test(expected = NullPointerException.class) public void shouldRequireNonNullValueForProvider() throws Exception { String area = "NE"; ForecastProvider provider = null; Type type = Type.CURRENT_FORECAST; new ForecastDataId(area, provider, type); } @Test(expected = NullPointerException.class) public void shouldRequireNonNullValueForType() throws Exception { String area = "NE"; ForecastProvider provider = ForecastProvider.DMI; Type type = null; new ForecastDataId(area, provider, type); } }
UTF-8
Java
2,112
java
ForecastDataIdTest.java
Java
[ { "context": "ic org.junit.Assert.assertThat;\n\n/**\n * Created by Steen on 12-01-2016.\n */\npublic class ForecastDataIdTes", "end": 789, "score": 0.9858134984970093, "start": 784, "tag": "NAME", "value": "Steen" } ]
null
[]
/* Copyright (c) 2011 Danish Maritime Authority. * * 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 dk.dma.embryo.dataformats.model; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * Created by Steen on 12-01-2016. */ public class ForecastDataIdTest { @Test public void shouldCreateIdStringByConcatenatingConstructorInputParameters() throws Exception { String area = "NE"; ForecastProvider provider = ForecastProvider.DMI; Type type = Type.CURRENT_FORECAST; ForecastDataId cut = new ForecastDataId(area, provider, type); assertThat(cut.getId(), is(area + provider + type)); } @Test(expected = NullPointerException.class) public void shouldRequireNonNullValueForArea() throws Exception { String area = null; ForecastProvider provider = ForecastProvider.DMI; Type type = Type.CURRENT_FORECAST; new ForecastDataId(area, provider, type); } @Test(expected = NullPointerException.class) public void shouldRequireNonNullValueForProvider() throws Exception { String area = "NE"; ForecastProvider provider = null; Type type = Type.CURRENT_FORECAST; new ForecastDataId(area, provider, type); } @Test(expected = NullPointerException.class) public void shouldRequireNonNullValueForType() throws Exception { String area = "NE"; ForecastProvider provider = ForecastProvider.DMI; Type type = null; new ForecastDataId(area, provider, type); } }
2,112
0.706439
0.698864
64
32
26.928726
98
false
false
0
0
0
0
0
0
0.546875
false
false
11
f158d48ed17e03bf66fd5f85d06a1d770028e537
32,401,233,333,430
7178e494e707ae152d4519b60c95f71b544d96eb
/refactoring/src/main/java/com/liujun/code/refactoring/refactoring/sex/order068/replacemethodwithmethodobject/src/Account.java
8188e44b4bf5716cba35ed2ce44e3cc435fc1234
[]
no_license
kkzfl22/learing
https://github.com/kkzfl22/learing
e24fce455bc8fec027c6009e9cd1becca0ca331b
1a1270bfc9469d23218c88bcd6af0e7aedbe41b6
refs/heads/master
2023-02-07T16:23:27.012000
2020-12-26T04:35:52
2020-12-26T04:35:52
297,195,805
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.liujun.code.refactoring.refactoring.sex.order068.replacemethodwithmethodobject.src; /** * 原始代码 * * 一个包含大量局部变量的函数 * * @author liujun * @version 0.0.1 */ public class Account { public int gama(int inputVal, int quantity, int yarToDate) { int importantValue1 = (inputVal * quantity) + delta(); int importantValue2 = (inputVal * yarToDate) + 100; if (yarToDate - importantValue1 > 1000) { importantValue2 -= 20; } int importantValue3 = importantValue2 * 7; return importantValue3 - 2 * importantValue1; } public int delta() { return 2000; } }
UTF-8
Java
637
java
Account.java
Java
[ { "context": "rc;\n\n/**\n * 原始代码\n *\n * 一个包含大量局部变量的函数\n *\n * @author liujun\n * @version 0.0.1\n */\npublic class Account {\n\n p", "end": 149, "score": 0.9806041717529297, "start": 143, "tag": "USERNAME", "value": "liujun" } ]
null
[]
package com.liujun.code.refactoring.refactoring.sex.order068.replacemethodwithmethodobject.src; /** * 原始代码 * * 一个包含大量局部变量的函数 * * @author liujun * @version 0.0.1 */ public class Account { public int gama(int inputVal, int quantity, int yarToDate) { int importantValue1 = (inputVal * quantity) + delta(); int importantValue2 = (inputVal * yarToDate) + 100; if (yarToDate - importantValue1 > 1000) { importantValue2 -= 20; } int importantValue3 = importantValue2 * 7; return importantValue3 - 2 * importantValue1; } public int delta() { return 2000; } }
637
0.676617
0.628524
26
22.192308
24.772844
95
false
false
0
0
0
0
0
0
0.346154
false
false
11
27b95363c9a7c571b33d22654c0c44ef8dca4daf
4,810,363,424,787
5e4307b9c23b9f1404f13ddf322367f5051e2165
/src/main/java/ru/sbtqa/monte/media/BufferFlag.java
c4960abd0444e6824e63bd6eb644a25f935bcfc2
[ "Apache-2.0" ]
permissive
manuelddahmen/monte-media
https://github.com/manuelddahmen/monte-media
d682bbd010f78707af39c177c02fafe548982c6b
196b1c28d11d23c62442333c6977da9f2536aa8e
refs/heads/master
2023-04-16T07:24:03.788000
2020-05-14T03:02:53
2020-05-14T03:02:53
262,711,212
0
0
NOASSERTION
true
2021-04-26T20:35:29
2020-05-10T04:24:40
2020-05-14T03:02:56
2021-04-26T20:35:29
4,408
0
0
2
Java
false
false
/* @(#)BufferFlag.java * Copyright © 2011 Werner Randelshofer, Switzerland. * You may only use this software in accordance with the license terms. */ package ru.sbtqa.monte.media; /** * {@code BufferFlag}. * * @author Werner Randelshofer * @version $Id: BufferFlag.java 364 2016-11-09 19:54:25Z werner $ */ public enum BufferFlag { /** * Indicates that the data in this buffer should be ignored. */ DISCARD, /** * Indicates that this Buffer holds an intra-coded picture, which can be * decoded independently. */ KEYFRAME, /** * Indicates that the data in this buffer is at the end of the media. */ END_OF_MEDIA, /** * Indicates that the data in this buffer is used for initializing the * decoding queue. * * This flag is used when the media time of a track is set to a non-keyframe * sample. Thus decoding must start at a keyframe at an earlier time. * * Decoders should decode the buffer. Encoders and Multiplexers should * discard the buffer. */ PREFETCH, /** * Indicates that this buffer is known to have the same data as the previous * buffer. This may improve encoding performance. */ SAME_DATA; }
UTF-8
Java
1,252
java
BufferFlag.java
Java
[ { "context": "/* @(#)BufferFlag.java\n * Copyright © 2011 Werner Randelshofer, Switzerland. \n * You may only use this software ", "end": 62, "score": 0.9998810887336731, "start": 43, "tag": "NAME", "value": "Werner Randelshofer" }, { "context": "e.media;\n\n/**\n * {@code BufferFlag...
null
[]
/* @(#)BufferFlag.java * Copyright © 2011 <NAME>, Switzerland. * You may only use this software in accordance with the license terms. */ package ru.sbtqa.monte.media; /** * {@code BufferFlag}. * * @author <NAME> * @version $Id: BufferFlag.java 364 2016-11-09 19:54:25Z werner $ */ public enum BufferFlag { /** * Indicates that the data in this buffer should be ignored. */ DISCARD, /** * Indicates that this Buffer holds an intra-coded picture, which can be * decoded independently. */ KEYFRAME, /** * Indicates that the data in this buffer is at the end of the media. */ END_OF_MEDIA, /** * Indicates that the data in this buffer is used for initializing the * decoding queue. * * This flag is used when the media time of a track is set to a non-keyframe * sample. Thus decoding must start at a keyframe at an earlier time. * * Decoders should decode the buffer. Encoders and Multiplexers should * discard the buffer. */ PREFETCH, /** * Indicates that this buffer is known to have the same data as the previous * buffer. This may improve encoding performance. */ SAME_DATA; }
1,226
0.647482
0.630695
44
27.431818
27.455252
80
false
false
0
0
0
0
0
0
0.181818
false
false
11
9b26a999bae99456e197c8de7fe2808ccb91ba3b
16,063,177,708,916
8b4b5b439931568b96533d2884b0110ee60028f3
/DatabaseConnect_Oracle/src/TestDB.java
6800f67ffc64610567b456917da81f31fc87152a
[]
no_license
gaikwadgaurav997/DatabaseConnectUsingJDBC
https://github.com/gaikwadgaurav997/DatabaseConnectUsingJDBC
1c3c6696139c5e96eaecb4faa3b060428f3b005e
b5da628c6aa8bb9e74246478eda03f504f723cc5
refs/heads/master
2020-09-12T12:40:31.635000
2019-11-18T11:04:36
2019-11-18T11:04:36
222,428,797
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; public class TestDB { public static void main(String[] args) throws SQLException { // TODO Auto-generated method stub Statement stmt = null; Connection conn = null; try { conn = DbUtil.getConnection(); if(conn!=null) System.out.println("Connected"); String sql = "insert into employee_gaurav values(2, 10, 'diksha', 7800260170)"; stmt = conn.createStatement(); stmt.executeUpdate(sql); System.out.println("Data updated"); stmt.close(); conn.close(); } catch(Exception e) { System.out.println("Statement not executed"); } } }
UTF-8
Java
659
java
TestDB.java
Java
[ { "context": "sql = \"insert into employee_gaurav values(2, 10, 'diksha', 7800260170)\";\n\t\tstmt = conn.createStatement", "end": 417, "score": 0.7219857573509216, "start": 415, "tag": "USERNAME", "value": "di" }, { "context": "l = \"insert into employee_gaurav values(2, 10, 'diksha...
null
[]
import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; public class TestDB { public static void main(String[] args) throws SQLException { // TODO Auto-generated method stub Statement stmt = null; Connection conn = null; try { conn = DbUtil.getConnection(); if(conn!=null) System.out.println("Connected"); String sql = "insert into employee_gaurav values(2, 10, 'diksha', 7800260170)"; stmt = conn.createStatement(); stmt.executeUpdate(sql); System.out.println("Data updated"); stmt.close(); conn.close(); } catch(Exception e) { System.out.println("Statement not executed"); } } }
659
0.69044
0.670713
30
20.966667
19.231022
81
false
false
0
0
0
0
0
0
2.033333
false
false
11
cc163315f5e854f8b4e0238e3d5fdeac37dc3938
32,976,758,941,112
76427a65b7da7b1eb28deec9af803632266dbe54
/src/main/java/com/jeeplus/modules/meiguotong/web/productcar/ProductCarController.java
94c7b3ecb50c3e34b9c730e369ce773050923f5c
[]
no_license
wmzrPsz/meiguotong
https://github.com/wmzrPsz/meiguotong
9225eb103e60769aa46ccefb5c45e91368b40137
7eb89d08b0f271fab2544512969015f2ecd1df13
refs/heads/master
2022-12-22T09:01:38.852000
2019-06-07T07:26:28
2019-06-07T07:26:28
190,703,947
0
0
null
false
2022-12-16T10:51:45
2019-06-07T07:22:54
2019-10-13T05:58:33
2022-12-16T10:51:41
60,180
0
0
25
Java
false
false
/** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.meiguotong.web.productcar; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.google.common.collect.Lists; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.config.Global; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.modules.meiguotong.entity.productcar.ProductCar; import com.jeeplus.modules.meiguotong.service.productcar.ProductCarService; /** * 购物车Controller * @author dong * @version 2018-09-17 */ @Controller @RequestMapping(value = "${adminPath}/meiguotong/productcar/productCar") public class ProductCarController extends BaseController { @Autowired private ProductCarService productCarService; @ModelAttribute public ProductCar get(@RequestParam(required=false) String id) { ProductCar entity = null; if (StringUtils.isNotBlank(id)){ entity = productCarService.get(id); } if (entity == null){ entity = new ProductCar(); } return entity; } /** * 购物车列表页面 */ @RequiresPermissions("meiguotong:productcar:productCar:list") @RequestMapping(value = {"list", ""}) public String list() { return "modules/meiguotong/productcar/productCarList"; } /** * 购物车列表数据 */ @ResponseBody @RequiresPermissions("meiguotong:productcar:productCar:list") @RequestMapping(value = "data") public Map<String, Object> data(ProductCar productCar, HttpServletRequest request, HttpServletResponse response, Model model) { Page<ProductCar> page = productCarService.findPage(new Page<ProductCar>(request, response), productCar); return getBootstrapData(page); } /** * 查看,增加,编辑购物车表单页面 */ @RequiresPermissions(value={"meiguotong:productcar:productCar:view","meiguotong:productcar:productCar:add","meiguotong:productcar:productCar:edit"},logical=Logical.OR) @RequestMapping(value = "form") public String form(ProductCar productCar, Model model) { model.addAttribute("productCar", productCar); return "modules/meiguotong/productcar/productCarForm"; } /** * 保存购物车 */ @ResponseBody @RequiresPermissions(value={"meiguotong:productcar:productCar:add","meiguotong:productcar:productCar:edit"},logical=Logical.OR) @RequestMapping(value = "save") public AjaxJson save(ProductCar productCar, Model model, RedirectAttributes redirectAttributes) throws Exception{ AjaxJson j = new AjaxJson(); if (!beanValidator(model, productCar)){ j.setSuccess(false); j.setMsg("非法参数!"); return j; } productCarService.save(productCar);//新建或者编辑保存 j.setSuccess(true); j.setMsg("保存购物车成功"); return j; } /** * 删除购物车 */ @ResponseBody @RequiresPermissions("meiguotong:productcar:productCar:del") @RequestMapping(value = "delete") public AjaxJson delete(ProductCar productCar, RedirectAttributes redirectAttributes) { AjaxJson j = new AjaxJson(); productCarService.delete(productCar); j.setMsg("删除购物车成功"); return j; } /** * 批量删除购物车 */ @ResponseBody @RequiresPermissions("meiguotong:productcar:productCar:del") @RequestMapping(value = "deleteAll") public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) { AjaxJson j = new AjaxJson(); String idArray[] =ids.split(","); for(String id : idArray){ productCarService.delete(productCarService.get(id)); } j.setMsg("删除购物车成功"); return j; } /** * 导出excel文件 */ @ResponseBody @RequiresPermissions("meiguotong:productcar:productCar:export") @RequestMapping(value = "export", method=RequestMethod.POST) public AjaxJson exportFile(ProductCar productCar, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) { AjaxJson j = new AjaxJson(); try { String fileName = "购物车"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; Page<ProductCar> page = productCarService.findPage(new Page<ProductCar>(request, response, -1), productCar); new ExportExcel("购物车", ProductCar.class).setDataList(page.getList()).write(response, fileName).dispose(); j.setSuccess(true); j.setMsg("导出成功!"); return j; } catch (Exception e) { j.setSuccess(false); j.setMsg("导出购物车记录失败!失败信息:"+e.getMessage()); } return j; } /** * 导入Excel数据 */ @RequiresPermissions("meiguotong:productcar:productCar:import") @RequestMapping(value = "import", method=RequestMethod.POST) public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) { try { int successNum = 0; int failureNum = 0; StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); List<ProductCar> list = ei.getDataList(ProductCar.class); for (ProductCar productCar : list){ try{ productCarService.save(productCar); successNum++; }catch(ConstraintViolationException ex){ failureNum++; }catch (Exception ex) { failureNum++; } } if (failureNum>0){ failureMsg.insert(0, ",失败 "+failureNum+" 条购物车记录。"); } addMessage(redirectAttributes, "已成功导入 "+successNum+" 条购物车记录"+failureMsg); } catch (Exception e) { addMessage(redirectAttributes, "导入购物车失败!失败信息:"+e.getMessage()); } return "redirect:"+Global.getAdminPath()+"/meiguotong/productcar/productCar/?repage"; } /** * 下载导入购物车数据模板 */ @RequiresPermissions("meiguotong:productcar:productCar:import") @RequestMapping(value = "import/template") public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) { try { String fileName = "购物车数据导入模板.xlsx"; List<ProductCar> list = Lists.newArrayList(); new ExportExcel("购物车数据", ProductCar.class, 1).setDataList(list).write(response, fileName).dispose(); return null; } catch (Exception e) { addMessage(redirectAttributes, "导入模板下载失败!失败信息:"+e.getMessage()); } return "redirect:"+Global.getAdminPath()+"/meiguotong/productcar/productCar/?repage"; } }
UTF-8
Java
7,414
java
ProductCarController.java
Java
[ { "context": "roductCarService;\n\n/**\n * 购物车Controller\n * @author dong\n * @version 2018-09-17\n */\n@Controller\n@RequestMa", "end": 1634, "score": 0.9993853569030762, "start": 1630, "tag": "USERNAME", "value": "dong" } ]
null
[]
/** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.meiguotong.web.productcar; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.google.common.collect.Lists; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.config.Global; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.modules.meiguotong.entity.productcar.ProductCar; import com.jeeplus.modules.meiguotong.service.productcar.ProductCarService; /** * 购物车Controller * @author dong * @version 2018-09-17 */ @Controller @RequestMapping(value = "${adminPath}/meiguotong/productcar/productCar") public class ProductCarController extends BaseController { @Autowired private ProductCarService productCarService; @ModelAttribute public ProductCar get(@RequestParam(required=false) String id) { ProductCar entity = null; if (StringUtils.isNotBlank(id)){ entity = productCarService.get(id); } if (entity == null){ entity = new ProductCar(); } return entity; } /** * 购物车列表页面 */ @RequiresPermissions("meiguotong:productcar:productCar:list") @RequestMapping(value = {"list", ""}) public String list() { return "modules/meiguotong/productcar/productCarList"; } /** * 购物车列表数据 */ @ResponseBody @RequiresPermissions("meiguotong:productcar:productCar:list") @RequestMapping(value = "data") public Map<String, Object> data(ProductCar productCar, HttpServletRequest request, HttpServletResponse response, Model model) { Page<ProductCar> page = productCarService.findPage(new Page<ProductCar>(request, response), productCar); return getBootstrapData(page); } /** * 查看,增加,编辑购物车表单页面 */ @RequiresPermissions(value={"meiguotong:productcar:productCar:view","meiguotong:productcar:productCar:add","meiguotong:productcar:productCar:edit"},logical=Logical.OR) @RequestMapping(value = "form") public String form(ProductCar productCar, Model model) { model.addAttribute("productCar", productCar); return "modules/meiguotong/productcar/productCarForm"; } /** * 保存购物车 */ @ResponseBody @RequiresPermissions(value={"meiguotong:productcar:productCar:add","meiguotong:productcar:productCar:edit"},logical=Logical.OR) @RequestMapping(value = "save") public AjaxJson save(ProductCar productCar, Model model, RedirectAttributes redirectAttributes) throws Exception{ AjaxJson j = new AjaxJson(); if (!beanValidator(model, productCar)){ j.setSuccess(false); j.setMsg("非法参数!"); return j; } productCarService.save(productCar);//新建或者编辑保存 j.setSuccess(true); j.setMsg("保存购物车成功"); return j; } /** * 删除购物车 */ @ResponseBody @RequiresPermissions("meiguotong:productcar:productCar:del") @RequestMapping(value = "delete") public AjaxJson delete(ProductCar productCar, RedirectAttributes redirectAttributes) { AjaxJson j = new AjaxJson(); productCarService.delete(productCar); j.setMsg("删除购物车成功"); return j; } /** * 批量删除购物车 */ @ResponseBody @RequiresPermissions("meiguotong:productcar:productCar:del") @RequestMapping(value = "deleteAll") public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) { AjaxJson j = new AjaxJson(); String idArray[] =ids.split(","); for(String id : idArray){ productCarService.delete(productCarService.get(id)); } j.setMsg("删除购物车成功"); return j; } /** * 导出excel文件 */ @ResponseBody @RequiresPermissions("meiguotong:productcar:productCar:export") @RequestMapping(value = "export", method=RequestMethod.POST) public AjaxJson exportFile(ProductCar productCar, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) { AjaxJson j = new AjaxJson(); try { String fileName = "购物车"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; Page<ProductCar> page = productCarService.findPage(new Page<ProductCar>(request, response, -1), productCar); new ExportExcel("购物车", ProductCar.class).setDataList(page.getList()).write(response, fileName).dispose(); j.setSuccess(true); j.setMsg("导出成功!"); return j; } catch (Exception e) { j.setSuccess(false); j.setMsg("导出购物车记录失败!失败信息:"+e.getMessage()); } return j; } /** * 导入Excel数据 */ @RequiresPermissions("meiguotong:productcar:productCar:import") @RequestMapping(value = "import", method=RequestMethod.POST) public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) { try { int successNum = 0; int failureNum = 0; StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); List<ProductCar> list = ei.getDataList(ProductCar.class); for (ProductCar productCar : list){ try{ productCarService.save(productCar); successNum++; }catch(ConstraintViolationException ex){ failureNum++; }catch (Exception ex) { failureNum++; } } if (failureNum>0){ failureMsg.insert(0, ",失败 "+failureNum+" 条购物车记录。"); } addMessage(redirectAttributes, "已成功导入 "+successNum+" 条购物车记录"+failureMsg); } catch (Exception e) { addMessage(redirectAttributes, "导入购物车失败!失败信息:"+e.getMessage()); } return "redirect:"+Global.getAdminPath()+"/meiguotong/productcar/productCar/?repage"; } /** * 下载导入购物车数据模板 */ @RequiresPermissions("meiguotong:productcar:productCar:import") @RequestMapping(value = "import/template") public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) { try { String fileName = "购物车数据导入模板.xlsx"; List<ProductCar> list = Lists.newArrayList(); new ExportExcel("购物车数据", ProductCar.class, 1).setDataList(list).write(response, fileName).dispose(); return null; } catch (Exception e) { addMessage(redirectAttributes, "导入模板下载失败!失败信息:"+e.getMessage()); } return "redirect:"+Global.getAdminPath()+"/meiguotong/productcar/productCar/?repage"; } }
7,414
0.744953
0.741541
212
32.183964
31.782413
168
false
false
0
0
0
0
0
0
1.867925
false
false
11
8aae7a4bd27a64b08e5d38fdec149091ccd694f9
10,857,677,354,870
8ff6c3e513e17be6c51b484bed81d03150bdd175
/2004-08-brmc1000/Z80.java
379d680a98ab3d0c4ec4d4749b902a4894f8941c
[]
no_license
ricbit/Oldies
https://github.com/ricbit/Oldies
f1a2ac520b64e43d11c250cc372d526e9febeedd
2d884c61ac777605f7260cd4d36a13ed5a2c6a58
refs/heads/master
2023-04-27T20:35:19.485000
2023-04-26T04:45:44
2023-04-26T04:45:44
2,050,140
40
8
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Z80 cpu core - Written from scratch by Romain Tisserand */ /* Bugs fixed by Ricardo Bittencourt */ /* History : 2004-08-10 : [ricbit] Fixed RLD,RRD,ADD,ADC,SUB,SBC,OR,AND,XOR,CP 2004-08-09 : [ricbit] Fixed CPL,SBC16,ADC16,RLA,RLCA,RRCA,RRA 2002-11-19 : Fixed nasty bug involving the HALT instruction and IRQ system 2002-11-13 : 1st release This source code is part of the Javel Project */ import java.math.BigInteger; public final class Z80 implements Cpu { private int AF, BC, DE, HL, AF2, BC2, DE2, HL2, IX, IY, XY, PC, SP, IFF1, IFF2, IM, word, addr; private int I, R, vector; private int cyclesToDo; private int sliceClocks; private BigInteger totalClocks; private MC1000machine machine; int NMIInt, IRQ; private boolean intel8080 = false; private boolean running = false; private static final byte PF_Table[] = new byte[256]; private int enable; private long frequency; private boolean halted = false; private final int NMI_PC; private Ports port; private Memory mem; public void setPorts(Ports p) { this.port = p; } Z80(MC1000machine m, boolean intel8080, int startAddr) { machine=m; this.mem = machine.memory; this.port = machine.ports; this.frequency = frequency; this.intel8080 = intel8080; if (intel8080 == true) { NMI_PC = 0x10; } else { NMI_PC = 0x66; } PF_Table_init(); reset(startAddr); start(); } Z80(Memory m, Ports p, boolean intel8080, int startAddr) { this.mem = m; this.port = p; this.frequency = frequency; this.intel8080 = intel8080; if (intel8080 == true) { NMI_PC = 0x10; } else { NMI_PC = 0x66; } PF_Table_init(); reset(startAddr); start(); } public void dump() { System.out.println("PC=" + Integer.toHexString(PC)); } public final void start() { running = true; } public final void stop() { running = false; } public final void reset(int startAddr) { PC = startAddr; SP = 0xDFF0; AF = 0x0040; AF2 = BC = DE = HL = BC2 = DE2 = HL2 = 0; IRQ = NMIInt = 0; vector = 0; IM = 0; IFF1 = IFF2 = 0; I = R = 0; IX = IY = XY = 0xFFFF; enable = 0; cyclesToDo = 0; totalClocks=BigInteger.ZERO; sliceClocks=0; } private final void UpdateR() { R = ((R & 0x80) | ((R + 1) & 0x7F)); } private final void memWriteByte(int addr, int data) { mem.writeByte(addr, data); } private final int memReadByte(int addr) { return mem.readByte(addr); } private final void ioWriteByte(int p, int data) { port.out(p, data, totalClocks.add(BigInteger.valueOf(sliceClocks-cyclesToDo))); } private final int ioReadByte(int p) { return port.in(p,totalClocks.add(BigInteger.valueOf(sliceClocks-cyclesToDo))); } private final void memWriteWord(int address, int data) { memWriteByte(address, (data & 0xFF)); memWriteByte(address + 1, ((data & 0xFF00) >> 8)); } private final int memReadWord(int address) { return ((memReadByte(address)) | (memReadByte((address + 1)) << 8)); } private final void setA(int v) { AF = (AF & 0xFF) | ((v) << 8); } private final void setF(int v) { AF = (AF & 0xFF00) | (v); } private final void setB(int v) { BC = (BC & 0xFF) | ((v) << 8); } private final void setC(int v) { BC = (BC & 0xFF00) | (v); } private final void setD(int v) { DE = (DE & 0xFF) | ((v) << 8); } private final void setE(int v) { DE = (DE & 0xFF00) | (v); } private final void setH(int v) { HL = (HL & 0xFF) | ((v) << 8); } private final void setL(int v) { HL = (HL & 0xFF00) | (v); } private final void setIXL(int v) { IX = (IX & 0xFF00) | (v); } private final void setIXH(int v) { IX = (IX & 0xFF) | ((v) << 8); } private final void setIYL(int v) { IY = (IY & 0xFF00) | (v); } private final void setIYH(int v) { IY = (IY & 0xFF) | ((v) << 8); } private final void setXYL(int v) { XY = (XY & 0xFF00) | (v); } private final void setXYH(int v) { XY = (XY & 0xFF) | ((v) << 8); } private final int getA() { return (AF >> 8); } private final int getB() { return (BC >> 8); } private final int getC() { return (BC & 0xFF); } private final int getD() { return (DE >> 8); } private final int getE() { return (DE & 0xFF); } private final int getH() { return (HL >> 8); } private final int getL() { return (HL & 0xFF); } private final int getIXH() { return (IX >> 8); } private final int getIXL() { return IX & 0xFF; } private final int getIYH() { return (IY >> 8); } private final int getIYL() { return IY & 0xFF; } private final int getXYH() { return (XY >> 8); } private final int getXYL() { return XY & 0xFF; } private final void decB() { setB((getB() - 1) & 0xFF); } private final void ClearCF() { AF &= 0xFFFE; } private final void ClearNF() { AF &= 0xFFFD; } private final void ClearVF() { AF &= 0xFFFB; } private final void ClearHF() { AF &= 0xFFEF; } private final void ClearZF() { AF &= 0xFFBF; } private final void ClearSF() { AF &= 0xFF7F; } private final void SetCF() { AF |= 0x01; } private final void SetNF() { AF |= 0x02; } private final void SetVF() { AF |= 0x04; } private final void SetHF() { AF |= 0x10; } private final void SetZF() { AF |= 0x40; } private final void SetSF() { AF |= 0x80; } private final void YF_XF_FLAGS(int x) { if ((x & 0x08) != 0) { AF |= 0x08; } else { AF &= 0xFFF7; } if ((x & 0x20) != 0) { AF |= 0x20; } else { AF &= 0xFFDF; } } private final void PARI_FLAG(int x) { if (PF_Table[x & 0xFF] != 0) { SetVF(); } else { ClearVF(); } } private final void SIGN_FLAG(int value, int size) { if ((value & (1 << (size - 1))) != 0) { SetSF(); } else { ClearSF(); } } private final void ZERO_FLAG(int value) { if (value == 0) { SetZF(); } else { ClearZF(); } } private final void HC_FLAG(int v1, int v2, int v3) { if (((v1 ^ v2 ^ v3) & 0x10) != 0) { SetHF(); } else { ClearHF(); } } private final void CARRY_FLAG(long value, int size) { if ((value & (1 << size)) != 0) { SetCF(); } else { ClearCF(); } } private final void OVER_FLAG(int v1, int v2, long v3, int size) { if ((((v2 ^ v1 ^ 0x80) & (v2 ^ v3) & (1 << (size - 1))) >> 5) != 0) { SetVF(); } else { ClearVF(); } } private final void OVER_FLAG2(int v1, int v2, long v3, int size) { if ((((v2 ^ v1) & (v1 ^ v3) & (1 << (size - 1))) >> 5) != 0) { SetVF(); } else { ClearVF(); } } private final void ADD(int x) { int temp = x; int acu = (AF >> 8); int sum = acu + temp; int cbits = acu ^ temp ^ sum; AF = ((sum & 0xff) << 8) | (sum & 0xa8) | (((sum & 0xff) == 0 ? 1 : 0) << 6) | (cbits & 0x10) | (((cbits >> 6) ^ (cbits >> 5)) & 4) | ((cbits >> 8) & 1); } private final void ADC(int x) { int temp = x; int acu = (AF >> 8); int sum = acu + temp + (AF & 1); int cbits = acu ^ temp ^ sum; AF = ((sum & 0xff) << 8) | (sum & 0xa8) | (((sum & 0xff) == 0 ? 1 : 0) << 6) | (cbits & 0x10) | (((cbits >> 6) ^ (cbits >> 5)) & 4) | ((cbits >> 8) & 1); } private final void SBC(int x) { int temp = x; int acu = (AF >> 8); int sum = acu - temp - (AF & 1); int cbits = acu ^ temp ^ sum; AF = ((sum & 0xff) << 8) | (sum & 0xa8) | (((sum & 0xff) == 0 ? 1 : 0) << 6) | (cbits & 0x10) | (((cbits >> 6) ^ (cbits >> 5)) & 4) | 2 | ((cbits >> 8) & 1); } private final int INC(int x) { int val = x + 1; OVER_FLAG(x, 1, val, 8); HC_FLAG(x, 1, val); x = (val & 0xFF); SIGN_FLAG(x, 8); ZERO_FLAG(x); ClearNF(); return x; } private final int DEC(int x) { int val = x - 1; OVER_FLAG2(x, 1, val, 8); HC_FLAG(x, 1, val); x = (val & 0xFF); SIGN_FLAG(x, 8); ZERO_FLAG(x); SetNF(); return x; } private final void SUB(int v) { int temp = v; int acu = (AF >> 8); int sum = acu - temp; int cbits = acu ^ temp ^ sum; AF = ((sum & 0xff) << 8) | (sum & 0xa8) | (((sum & 0xff) == 0 ? 1 : 0) << 6) | (cbits & 0x10) | (((cbits >> 6) ^ (cbits >> 5)) & 4) | 2 | ((cbits >> 8) & 1); } private final void AND(int v) { int sum = ((AF >> 8) & v) & 0xff; AF = (sum << 8) | (sum & 0xa8) | 0x10 | ((sum == 0 ? 1 : 0) << 6) | ((PF_Table[sum & 0xff] ^ 1) << 2); } private final void XOR(int v) { int sum = ((AF >> 8) ^ v) & 0xff; AF = (sum << 8) | (sum & 0xa8) | ((sum == 0 ? 1 : 0) << 6) | ((PF_Table[sum & 0xff] ^ 1) << 2); } private final void OR(int v) { int sum = ((AF >> 8) | v) & 0xff; AF = (sum << 8) | (sum & 0xa8) | ((sum == 0 ? 1 : 0) << 6) | ((PF_Table[sum & 0xff] ^ 1) << 2); } private final void CP(int v) { int temp = v; AF = (AF & ((~0x28) & 0xFFFF)) | (temp & 0x28); int acu = (AF >> 8); int sum = acu - temp; int cbits = acu ^ temp ^ sum; AF = (AF & 0xff00) | (sum & 0x80) | (((sum & 0xff) == 0 ? 1 : 0) << 6) | (temp & 0x28) | (((cbits >> 6) ^ (cbits >> 5)) & 4) | 2 | (cbits & 0x10) | ((cbits >> 8) & 1); } private final void DAA() { int val = getA(); if ((AF & 0x01) != 0) { val |= 256; } if ((AF & 0x10) != 0) { val |= 512; } if ((AF & 0x02) != 0) { val |= 1024; } AF = DAATable2[val]; } /* fixed by ricbit */ private final void CPL() { setA(0xFF & (~getA())); SetHF(); SetNF(); YF_XF_FLAGS(getA()); } private final void EXX() { word = BC; BC = BC2; BC2 = word; word = DE; DE = DE2; DE2 = word; word = HL; HL = HL2; HL2 = word; } private final void SCF() { ClearHF(); ClearNF(); SetCF(); YF_XF_FLAGS(getA()); } private final void CCF() { ClearNF(); if ((AF & 0x01) != 0) { SetHF(); ClearCF(); } else { ClearHF(); SetCF(); } YF_XF_FLAGS(getA()); } private final void PUSH(int v) { SP -= 2; SP &= 0xFFFF; memWriteWord(SP, v & 0xFFFF); } private final int POP() { int val = memReadWord(SP); val &= 0xFFFF; SP += 2; SP &= 0xFFFF; return val; } private final void RST(int v) { PUSH(PC); PC = v; } private final void RET() { PC = memReadWord(SP); SP += 2; SP &= 0xFFFF; } private final void CALL() { SP -= 2; SP &= 0xFFFF; memWriteWord(SP, (PC + 2)); PC = memReadWord(PC); } private final void NEG() { int val = getA(); setA(0); SUB(val); } private final int ADD16(int x, int y) { ClearNF(); int val = (x) + (y); if ((((y ^ x ^ val)) & 0x1000) != 0) { SetHF(); } else { ClearHF(); } CARRY_FLAG(val, 16); YF_XF_FLAGS(val >> 8); return val & 0xFFFF; } private final void SBC_HL(int x) { HL &= 0xffff; x &= 0xffff; int sum = HL - x - (AF & 1); int cbits = (HL ^ x ^ sum) >> 8; HL = sum & 0xFFFF; AF = (AF & 0xff00) | ((sum >> 8) & 0xa8) | (((sum & 0xffff) == 0 ? 1 : 0) << 6) | (((cbits >> 6) ^ (cbits >> 5)) & 4) | (cbits & 0x10) | 2 | ((cbits >> 8) & 1); } private final void ADC_HL(int x) { HL &= 0xffff; x &= 0xffff; int sum = HL + x + (AF & 1); int cbits = (HL ^ x ^ sum) >> 8; HL = sum & 0xffff; AF = (AF & 0xff00) | ((sum >> 8) & 0xa8) | (((sum & 0xffff) == 0 ? 1 : 0) << 6) | (((cbits >> 6) ^ (cbits >> 5)) & 4) | (cbits & 0x10) | ((cbits >> 8) & 1); } private final void cbFlag(int temp, int cbits) { AF = (AF & 0xff00) | (temp & 0xa8) | (((temp & 0xff) == 0 ? 1 : 0) << 6) | ((PF_Table[temp & 0xff] ^ 1) << 2) | (cbits == 0 ? 0 : 1); } private final int RR(int x) { /* int old_x=x&0xFF; int val=old_x; val=(((val>>1))|((AF&0x01)<<7))&0xFF; ZERO_FLAG(val); SIGN_FLAG(val,8); PARI_FLAG(val); if ((old_x&0x01)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); */ int temp = (x >> 1) | ((AF & 1) << 7); int cbits = x & 1; cbFlag(temp, cbits); return temp; } private final int RL(int x) { /* int old_x=x&0xFF; int val=old_x; val=((val<<1)|(AF&0x01))&0xFF; ZERO_FLAG(val); SIGN_FLAG(val,8); PARI_FLAG(val); if ((old_x&0x80)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); */ int temp = (x << 1) | (AF & 1); int cbits = x & 0x80; cbFlag(temp, cbits); return temp; } private final int RRC(int x) { /* int old_x=x&0xFF; int val=old_x; val=((val>>1)|(val<<7))&0xFF; ZERO_FLAG(val); SIGN_FLAG(val,8); PARI_FLAG(val); if ((old_x&0x01)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); return val&0xFF; */ int temp = (x >> 1) | (x << 7); int cbits = temp & 0x80; cbFlag(temp, cbits); return temp; } private final int RLC(int x) { /* int old_x=x&0xFF; int val=old_x; val=((val<<1)|(val>>7))&0xFF; ZERO_FLAG(val); SIGN_FLAG(val,8); PARI_FLAG(val); if ((old_x&0x80)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); return val; */ int temp = (x << 1) | (x >> 7); int cbits = temp & 1; cbFlag(temp, cbits); return temp; } private final void RRA() { int temp = (AF >> 8) & 0xFF; int sum = temp >> 1; AF = ((AF & 1) << 15) | (sum << 8) | (sum & 0x28) | (AF & 0xc4) | (temp & 1); } private final void RLA() { AF = ((AF << 8) & 0x0100) | ((AF >> 7) & 0x28) | ((AF << 1) & ((~0x1ff) & 0xFFFF)) | (AF & 0xc4) | ((AF >> 15) & 1); } private final void RRCA() { int temp = (AF >> 8) & 0xFF; int sum = temp >> 1; AF = ((temp & 1) << 15) | (sum << 8) | (sum & 0x28) | (AF & 0xc4) | (temp & 1); } private final void RLCA() { AF = ((AF >> 7) & 0x0128) | ((AF << 1) & ((~0x1ff) & 0xFFFF)) | (AF & 0xc4) | ((AF >> 15) & 1); } private final void RLD() { int temp = memReadByte(HL); int acu = (AF >> 8) & 0xFF; memWriteByte(HL, ((temp & 0xf) << 4) | (acu & 0xf)); acu = (acu & 0xf0) | ((temp >> 4) & 0xf); AF = (acu << 8) | (acu & 0xa8) | (((acu & 0xff) == 0 ? 1 : 0) << 6) | ((PF_Table[acu] ^ 1) << 2) | (AF & 1); } private final void RRD() { int temp = memReadByte(HL); int acu = (AF >> 8) & 0xFF; memWriteByte(HL, ((temp >> 4) & 0xf) | ((acu & 0xf) << 4)); acu = (acu & 0xf0) | (temp & 0xf); AF = (acu << 8) | (acu & 0xa8) | (((acu & 0xff) == 0 ? 1 : 0) << 6) | ((PF_Table[acu] ^ 1) << 2) | (AF & 1); } private final int IN() { int val = ioReadByte(BC); ClearHF(); ClearNF(); SIGN_FLAG(val, 8); ZERO_FLAG(val); PARI_FLAG(val); YF_XF_FLAGS(val); return val; } private final void INI() { int byte2 = ioReadByte(BC) & 0xFF; memWriteByte(HL, byte2); HL++; HL &= 0xFFFF; decB(); SIGN_FLAG(getB(), 8); ZERO_FLAG(getB()); /* if (((((getC()+1)&0xFF)+byte2)&0x100)!=0) { SetCF(); SetHF(); } else { ClearCF(); ClearHF(); }*/ if ((byte2 & 0x80) != 0) { SetNF(); } else { ClearNF(); } } private final void IND() { int byte2 = ioReadByte(BC) & 0xFF; memWriteByte(HL, byte2); HL--; HL &= 0xFFFF; decB(); SIGN_FLAG(getB(), 8); ZERO_FLAG(getB()); /* if (((((getC()+1)&0xFF)+byte2)&0x100)!=0) { SetCF(); SetHF(); } else { ClearCF(); ClearHF(); }*/ if ((byte2 & 0x80) != 0) { SetNF(); } else { ClearNF(); } } private final void INIR() { INI(); if (getB() != 0) { PC -= 2; } } private final void INDR() { IND(); if (getB() != 0) { PC -= 2; } } private final void OUTI() { int byte2 = memReadByte(HL); ioWriteByte(BC, byte2); HL++; HL &= 0xFFFF; decB(); SIGN_FLAG(getB(), 8); ZERO_FLAG(getB()); if ((byte2 & 0x80) != 0) { SetNF(); } else { ClearNF(); } /* if (((byte2+getL())&0x100)!=0) { SetCF(); SetHF(); } else { ClearCF(); ClearHF(); }*/ } private final void OUTD() { int byte2 = memReadByte(HL); ioWriteByte(BC, byte2); HL--; HL &= 0xFFFF; decB(); SIGN_FLAG(getB(), 8); ZERO_FLAG(getB()); if ((byte2 & 0x80) != 0) { SetNF(); } else { ClearNF(); } /* if (((byte2+getL())&0x100)!=0) { SetCF(); SetHF(); } else { ClearCF(); ClearHF(); }*/ } private final void OUTDR() { OUTD(); if (getB() != 0) { PC -= 2; } } private final void OUTIR() { OUTI(); if (getB() != 0) { PC -= 2; } } private final void LDI() { ClearHF(); ClearNF(); int byte2 = memReadByte(HL) & 0xFF; memWriteByte(DE, byte2); DE++; HL++; BC--; DE &= 0xFFFF; HL &= 0xFFFF; BC &= 0xFFFF; if ((BC) != 0) { SetVF(); } else { ClearVF(); } byte2 += getA(); byte2 &= 0xFF; if ((byte2 & 0x02) != 0) { AF |= 0x20; } else { AF &= 0xFFDF; } if ((byte2 & 0x08) != 0) { AF |= 0x08; } else { AF &= 0xFFF7; } UpdateR(); } private final void LDD() { ClearHF(); ClearNF(); int byte2 = memReadByte(HL) & 0xFF; memWriteByte(DE, byte2); DE--; HL--; BC--; DE &= 0xFFFF; HL &= 0xFFFF; BC &= 0xFFFF; if ((BC) != 0) { SetVF(); } else { ClearVF(); } byte2 += getA(); byte2 &= 0xFF; if ((byte2 & 0x02) != 0) { AF |= 0x20; } else { AF &= 0xFFDF; } if ((byte2 & 0x08) != 0) { AF |= 0x08; } else { AF &= 0xFFF7; } UpdateR(); } private final void LDIR() { LDI(); if (BC != 0) { PC -= 2; } } private final void LDDR() { LDD(); if (BC != 0) { PC -= 2; } } private final void CPI() { SetNF(); int byte2 = memReadByte(HL); HL++; HL &= 0xFFFF; BC--; BC &= 0xFFFF; int val = byte2 & 0xFF; int res = getA() - val; res &= 0xFF; ZERO_FLAG(res); if (((getA() ^ res ^ val) & 0x10) != 0) { SetHF(); } else { ClearHF(); } SIGN_FLAG(res, 8); YF_XF_FLAGS((getA() - byte2 - ((AF & 0x10) >> 4))); if ((BC) != 0) { SetVF(); } else { ClearVF(); } } private final void CPD() { SetNF(); int byte2 = memReadByte(HL); HL--; HL &= 0xFFFF; BC--; BC &= 0xFFFF; int val = byte2 & 0xFF; int res = getA() - val; res &= 0xFF; ZERO_FLAG(res); if (((getA() ^ res ^ val) & 0x10) != 0) { SetHF(); } else { ClearHF(); } SIGN_FLAG(res, 8); YF_XF_FLAGS((getA() - byte2 - ((AF & 0x10) >> 4))); if ((BC) != 0) { SetVF(); } else { ClearVF(); } } private final void CPIR() { CPI(); if ((BC != 0) && ((AF & 0x40) == 0)) { PC -= 2; } } private final void CPDR() { CPD(); if ((BC != 0) && ((AF & 0x40) == 0)) { PC -= 2; } } private final void BIT(int y, int x) { if ((x & (1 << y)) != 0) { ClearZF(); ClearVF(); switch (y) { case 7: SetSF(); break; case 5: AF |= 0x20; break; case 3: AF |= 0x08; break; } } else { SetZF(); SetVF(); } ClearNF(); SetHF(); } private final int RES(int y, int x) { return (x & (~(1 << y))) & 0xFF; } private final int SET(int y, int x) { return (x | (1 << y)) & 0xFF; } private final int SRA(int x) { /* int old_x=x&0xFF; x=old_x; x=(x&0x80)|((x>>1)); x&=0xFF; ZERO_FLAG(x); SIGN_FLAG(x,8); PARI_FLAG(x); if ((old_x&0x01)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); return x; */ int temp = (x >> 1) | (x & 0x80); int cbits = x & 1; cbFlag(temp, cbits); return temp; } private final int SRL(int x) { /* int old_x=x&0xFF; x=old_x; x=(x>>1)&0xFF; ZERO_FLAG(x); SIGN_FLAG(x,8); PARI_FLAG(x); if ((old_x&0x01)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); return x; }*/ int temp = x >> 1; int cbits = x & 1; cbFlag(temp, cbits); return temp; } private final int SLA(int x) { /* int old_x=x&0xFF; x=old_x; x=(x<<1)&0xFF; ZERO_FLAG(x); SIGN_FLAG(x,8); PARI_FLAG(x); if ((old_x&0x80)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); return x; }*/ int temp = x << 1; int cbits = x & 0x80; cbFlag(temp, cbits); return temp; } private final int SLL(int x) { /* int old_x=x&0xFF; x=old_x; x=((x<<1)|0x01)&0xFF; ZERO_FLAG(x); SIGN_FLAG(x,8); PARI_FLAG(x); if ((old_x&0x80)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); return x; }*/ int temp = (x << 1) | 1; int cbits = x & 0x80; cbFlag(temp, cbits); return temp; } private final int LD_RES(int i, int y) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = RES(y, memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_SET(int i, int y) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = SET(y, memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_RLC(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = RLC(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_RRC(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = RRC(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_RL(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = RL(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_RR(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = RR(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_SRA(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = SRA(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_SLA(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = SLA(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_SRL(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = SRL(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_SLL(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = SLL(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final void exeOpcode(int opcode) { switch (opcode) { case 0xCB: exe_cb_opcode(memReadByte(PC++)); break; // Prefix case 0xED: exe_ed_opcode(memReadByte(PC++)); break; // Prefix case 0xDD: IX = exe_dd_opcode(IX, memReadByte(PC++)); break; // Prefix case 0xFD: IY = exe_dd_opcode(IY, memReadByte(PC++)); break; // Prefix case 0x00: break; // NOP case 0x01: BC = memReadWord(PC); PC += 2; break; // LD BC,NN case 0x02: memWriteByte(BC, getA()); break; // LD (BC),A case 0x03: BC++; BC &= 0xFFFF; break; // INC BC case 0x04: setB(INC(getB())); break; // INC B case 0x05: setB(DEC(getB())); break; // DEC B case 0x06: setB(memReadByte(PC++)); break; // LD B,N case 0x07: RLCA(); break; // RLCA case 0x08: word = AF; AF = AF2; AF2 = word; break; // EX AF,AF' case 0x09: HL = ADD16(HL, BC); break; // ADD HL,BC case 0x0A: setA(memReadByte(BC)); break; // LD A,(BC) case 0x0B: BC--; BC &= 0xFFFF; break; // DEC BC case 0x0C: setC(INC(getC())); break; // INC C case 0x0D: setC(DEC(getC())); break; // DEC C case 0x0E: setC(memReadByte(PC++)); break; // LD C,N case 0x0F: RRCA(); break; // RRCA case 0x10: decB(); if (getB() != 0) { cyclesToDo -= 3; PC += 1 + (byte) (memReadByte(PC)); } else { PC++; } break; // DJNZ (PC+dd) case 0x11: DE = memReadWord(PC); PC += 2; break; // LD DE,NN case 0x12: memWriteByte(DE, getA()); break; // LD (DE),A case 0x13: DE++; DE &= 0xFFFF; break; // INC DE case 0x14: setD(INC(getD())); break; // INC D case 0x15: setD(DEC(getD())); break; // DEC D case 0x16: setD(memReadByte(PC++)); break; // LD D,N case 0x17: RLA(); break; // RLA case 0x18: PC += 1 + (byte) (memReadByte(PC)); break; // JR e case 0x19: HL = ADD16(HL, DE); break; // ADD HL,DE case 0x1A: setA(memReadByte(DE)); break; // LD A,(DE) case 0x1B: DE--; DE &= 0xFFFF; break; // DEC DE case 0x1C: setE(INC(getE())); break; // INC E case 0x1D: setE(DEC(getE())); break; // DEC E case 0x1E: setE(memReadByte(PC++)); break; // LD E,N case 0x1F: RRA(); break; // RRA case 0x20: if ((AF & 0x40) == 0) { cyclesToDo -= 5; PC += 1 + (byte) (memReadByte(PC)); } else { PC++; } break; // JR NZ,n case 0x21: HL = memReadWord(PC); PC += 2; break; // LD HL,NN case 0x22: memWriteWord(memReadWord(PC), HL); PC += 2; break; // LD (NN),HL case 0x23: HL++; HL &= 0xFFFF; break; // INC HL case 0x24: setH(INC(getH())); break; // INC H case 0x25: setH(DEC(getH())); break; // DEC H case 0x26: setH(memReadByte(PC++)); break; // LD H,N case 0x27: DAA(); break; // DAA case 0x28: if ((AF & 0x40) != 0) { cyclesToDo -= 5; PC += 1 + (byte) (memReadByte(PC)); } else { PC++; } break; // JR Z,n case 0x29: HL = ADD16(HL, HL); break; // ADD HL,HL case 0x2A: HL = memReadWord(memReadWord(PC)); PC += 2; break; // LD HL,(NN) case 0x2B: HL--; HL &= 0xFFFF; break; // DEC HL case 0x2C: setL(INC(getL())); break; // INC L case 0x2D: setL(DEC(getL())); break; // DEC L case 0x2E: setL(memReadByte(PC++)); break; // LD L,N case 0x2F: CPL(); break; // CPL case 0x30: if ((AF & 0x01) == 0) { cyclesToDo -= 5; PC += 1 + (byte) (memReadByte(PC)); } else { PC++; } break; // JR NC,n case 0x31: SP = memReadWord(PC); PC += 2; break; // LD SP,NN case 0x32: memWriteByte(memReadWord(PC), getA()); PC += 2; break; // LD (NN),A case 0x33: SP++; SP &= 0xFFFF; break; // INC SP case 0x34: memWriteByte(HL, INC(memReadByte(HL))); break; // INC (HL) case 0x35: memWriteByte(HL, DEC(memReadByte(HL))); break; // DEC (HL) case 0x36: memWriteByte(HL, memReadByte(PC++)); break; // LD (HL),N case 0x37: SCF(); break; // SCF case 0x38: if ((AF & 0x01) != 0) { cyclesToDo -= 5; PC += 1 + (byte) (memReadByte(PC)); } else { PC++; } break; // JR C,n case 0x39: HL = ADD16(HL, SP); break; // ADD HL,SP case 0x3A: setA(memReadByte(memReadWord(PC))); PC += 2; break; // LD A,(NN) case 0x3B: SP--; SP &= 0xFFFF; break; // DEC SP case 0x3C: setA(INC(getA())); break; // INC A case 0x3D: setA(DEC(getA())); break; // DEC A case 0x3E: setA(memReadByte(PC++)); break; // LD A,N case 0x3F: CCF(); break; // CCF case 0x40: break; // LD B,B case 0x41: setB(getC()); break; // LD B,C case 0x42: setB(getD()); break; // LD B,D case 0x43: setB(getE()); break; // LD B,E case 0x44: setB(getH()); break; // LD B,H case 0x45: setB(getL()); break; // LD B,L case 0x46: setB(memReadByte(HL)); break; // LD B,(HL) case 0x47: setB(getA()); break; // LD B,A case 0x48: setC(getB()); break; // LD C,B case 0x49: break; // LD C,C case 0x4A: setC(getD()); break; // LD C,D case 0x4B: setC(getE()); break; // LD C,E case 0x4C: setC(getH()); break; // LD C,H case 0x4D: setC(getL()); break; // LD C,L case 0x4E: setC(memReadByte(HL)); break; // LD C,(HL) case 0x4F: setC(getA()); break; // LD C,A case 0x50: setD(getB()); break; // LD D,B case 0x51: setD(getC()); break; // LD D,C case 0x52: break; // LD D,D case 0x53: setD(getE()); break; // LD D,E case 0x54: setD(getH()); break; // LD D,H case 0x55: setD(getL()); break; // LD D,L case 0x56: setD(memReadByte(HL)); break; // LD D,(HL) case 0x57: setD(getA()); break; // LD D,A case 0x58: setE(getB()); break; // LD E,B case 0x59: setE(getC()); break; // LD E,C case 0x5A: setE(getD()); break; // LD E,D case 0x5B: break; // LD E,E case 0x5C: setE(getH()); break; // LD E,H case 0x5D: setE(getL()); break; // LD E,L case 0x5E: setE(memReadByte(HL)); break; // LD E,(HL) case 0x5F: setE(getA()); break; // LD E,A case 0x60: setH(getB()); break; // LD H,B case 0x61: setH(getC()); break; // LD H,C case 0x62: setH(getD()); break; // LD H,D case 0x63: setH(getE()); break; // LD H,E case 0x64: break; // LD H,H case 0x65: setH(getL()); break; // LD H,L case 0x66: setH(memReadByte(HL)); break; // LD H,(HL) case 0x67: setH(getA()); break; // LD H,A case 0x68: setL(getB()); break; // LD L,B case 0x69: setL(getC()); break; // LD L,C case 0x6A: setL(getD()); break; // LD L,D case 0x6B: setL(getE()); break; // LD L,E case 0x6C: setL(getH()); break; // LD L,H case 0x6D: break; // LD L,L case 0x6E: setL(memReadByte(HL)); break; // LD L,(HL) case 0x6F: setL(getA()); break; // LD L,A case 0x70: memWriteByte(HL, getB()); break; // LD (HL),B case 0x71: memWriteByte(HL, getC()); break; // LD (HL),C case 0x72: memWriteByte(HL, getD()); break; // LD (HL),D case 0x73: memWriteByte(HL, getE()); break; // LD (HL),E case 0x74: memWriteByte(HL, getH()); break; // LD (HL),H case 0x75: memWriteByte(HL, getL()); break; // LD (HL),L case 0x76: halted = true; break; // HALT case 0x77: memWriteByte(HL, getA()); break; // LD (HL),A case 0x78: setA(getB()); break; // LD A,B case 0x79: setA(getC()); break; // LD A,C case 0x7A: setA(getD()); break; // LD A,D case 0x7B: setA(getE()); break; // LD A,E case 0x7C: setA(getH()); break; // LD A,H case 0x7D: setA(getL()); break; // LD A,L case 0x7E: setA(memReadByte(HL)); break; // LD A,(HL) case 0x7F: break; // LD A,A case 0x80: ADD(getB()); break; // ADD A,B case 0x81: ADD(getC()); break; // ADD A,C case 0x82: ADD(getD()); break; // ADD A,D case 0x83: ADD(getE()); break; // ADD A,E case 0x84: ADD(getH()); break; // ADD A,H case 0x85: ADD(getL()); break; // ADD A,L case 0x86: ADD(memReadByte(HL)); break; // ADD (HL) case 0x87: ADD(getA()); break; // ADD A,A case 0x88: ADC(getB()); break; // ADC A,B case 0x89: ADC(getC()); break; // ADC A,C case 0x8A: ADC(getD()); break; // ADC A,D case 0x8B: ADC(getE()); break; // ADC A,E case 0x8C: ADC(getH()); break; // ADC A,H case 0x8D: ADC(getL()); break; // ADC A,L case 0x8E: ADC(memReadByte(HL)); break; // ADC (HL) case 0x8F: ADC(getA()); break; // ADC A,A case 0x90: SUB(getB()); break; // SUB B case 0x91: SUB(getC()); break; // SUB C case 0x92: SUB(getD()); break; // SUB D case 0x93: SUB(getE()); break; // SUB E case 0x94: SUB(getH()); break; // SUB H case 0x95: SUB(getL()); break; // SUB L case 0x96: SUB(memReadByte(HL)); break; // SUB (HL) case 0x97: SUB(getA()); break; // SUB A case 0x98: SBC(getB()); break; // SBC B case 0x99: SBC(getC()); break; // SBC C case 0x9A: SBC(getD()); break; // SBC D case 0x9B: SBC(getE()); break; // SBC E case 0x9C: SBC(getH()); break; // SBC H case 0x9D: SBC(getL()); break; // SBC L case 0x9E: SBC(memReadByte(HL)); break; // SBC (HL) case 0x9F: SBC(getA()); break; // SBC A case 0xA0: AND(getB()); break; // AND B case 0xA1: AND(getC()); break; // AND C case 0xA2: AND(getD()); break; // AND D case 0xA3: AND(getE()); break; // AND E case 0xA4: AND(getH()); break; // AND H case 0xA5: AND(getL()); break; // AND L case 0xA6: AND(memReadByte(HL)); break; // AND (HL) case 0xA7: AND(getA()); break; // AND A case 0xA8: XOR(getB()); break; // XOR B case 0xA9: XOR(getC()); break; // XOR C case 0xAA: XOR(getD()); break; // XOR D case 0xAB: XOR(getE()); break; // XOR E case 0xAC: XOR(getH()); break; // XOR H case 0xAD: XOR(getL()); break; // XOR L case 0xAE: XOR(memReadByte(HL)); break; // XOR (HL) case 0xAF: XOR(getA()); break; // XOR A case 0xB0: OR(getB()); break; // OR B case 0xB1: OR(getC()); break; // OR C case 0xB2: OR(getD()); break; // OR D case 0xB3: OR(getE()); break; // OR E case 0xB4: OR(getH()); break; // OR H case 0xB5: OR(getL()); break; // OR L case 0xB6: OR(memReadByte(HL)); break; // OR (HL) case 0xB7: OR(getA()); break; // OR A case 0xB8: CP(getB()); break; // CP B case 0xB9: CP(getC()); break; // CP C case 0xBA: CP(getD()); break; // CP D case 0xBB: CP(getE()); break; // CP E case 0xBC: CP(getH()); break; // CP H case 0xBD: CP(getL()); break; // CP L case 0xBE: CP(memReadByte(HL)); break; // CP (HL) case 0xBF: CP(getA()); break; // CP A case 0xC0: if ((AF & 0x40) == 0) { cyclesToDo -= 6; RET(); } break; // RET NZ case 0xC1: BC = POP(); break; // POP BC case 0xC2: if ((AF & 0x40) == 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP NZ,nn case 0xC3: PC = memReadWord(PC); break; // JP nn case 0xC4: if ((AF & 0x40) == 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL NZ,nn case 0xC5: PUSH(BC); break; // PUSH BC case 0xC6: ADD(memReadByte(PC++)); break; // ADD nn case 0xC7: RST(0x00); break; // RST 00h case 0xC8: if ((AF & 0x40) != 0) { cyclesToDo -= 6; RET(); } break; // RET Z case 0xC9: RET(); break; // RET case 0xCA: if ((AF & 0x40) != 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP Z,nn case 0xCC: if ((AF & 0x40) != 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL Z,nn case 0xCD: CALL(); break; // CALL case 0xCE: ADC(memReadByte(PC++)); break; // ADC nn case 0xCF: RST(0x08); break; // RST 08h case 0xD0: if ((AF & 0x01) == 0) { RET(); } break; // RET NC case 0xD1: DE = POP(); break; // POP DE case 0xD2: if ((AF & 0x01) == 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP NC,nn case 0xD3: ioWriteByte((getA() << 8) | memReadByte(PC++), getA()); break; // OUT (N),A case 0xD4: if ((AF & 0x01) == 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL NC,nn case 0xD5: PUSH(DE); break; // PUSH DE case 0xD6: SUB(memReadByte(PC++)); break; // SUB n case 0xD7: RST(0x10); break; // RST 10h case 0xD8: if ((AF & 0x01) != 0) { RET(); } break; // RET C case 0xD9: EXX(); break; // EXX case 0xDA: if ((AF & 0x01) != 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP C,nn case 0xDB: setA(ioReadByte((getA() << 8) | memReadByte(PC++))); break; // IN A,N case 0xDC: if ((AF & 0x01) != 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL C,nn case 0xDE: SBC(memReadByte(PC++)); break; // SBC n case 0xDF: RST(0x18); break; // RST 18h case 0xE0: if ((AF & 0x04) == 0) { cyclesToDo -= 6; RET(); } break; // RET PO case 0xE1: HL = POP(); break; // POP HL case 0xE2: if ((AF & 0x04) == 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP PO,nn case 0xE3: word = HL; HL = memReadWord(SP); memWriteWord(SP, word); break; // EX (SP),HL case 0xE4: if ((AF & 0x04) == 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL PO,nn case 0xE5: PUSH(HL); break; // PUSH HL case 0xE6: AND(memReadByte(PC++)); break; // AND n case 0xE7: RST(0x20); break; // RST 20h case 0xE8: if ((AF & 0x04) != 0) { cyclesToDo -= 6; RET(); } break; // RET PE case 0xE9: PC = HL; break; // JP HL case 0xEA: if ((AF & 0x04) != 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP PE,nn case 0xEB: word = DE; DE = HL; HL = word; break; // EX DE,HL case 0xEC: if ((AF & 0x04) != 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL PE,nn case 0xEE: XOR(memReadByte(PC++)); break; // XOR n case 0xEF: RST(0x28); break; // RST 28h case 0xF0: if ((AF & 0x80) == 0) { cyclesToDo -= 6; RET(); } break; // RET P case 0xF1: AF = POP(); break; // POP AF case 0xF2: if ((AF & 0x80) == 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP P,nn case 0xF3: IFF1 = IFF2 = 0; break; // DI case 0xF4: if ((AF & 0x80) == 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL P,nn case 0xF5: PUSH(AF); break; // PUSH AF case 0xF6: OR(memReadByte(PC++)); break; // OR n case 0xF7: RST(0x30); break; // RST 30h case 0xF8: if ((AF & 0x80) != 0) { cyclesToDo -= 6; RET(); } break; // RET M case 0xF9: SP = HL; break; // LD SP,HL case 0xFA: if ((AF & 0x80) != 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP M,nn case 0xFB: enable = 1; break; // EI case 0xFC: if ((AF & 0x80) != 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL M,nn case 0xFE: CP(memReadByte(PC++)); break; // CP nn case 0xFF: RST(0x38); break; // RST 38h } cyclesToDo -= cycles_main_opcode[opcode]; } private final void exe_ed_opcode(int opcode) { switch (opcode) { // CASE TABLE FOR ED OPCODES case 0x40: setB(IN()); break; // IN B,(C) case 0x41: ioWriteByte(BC, getB()); break; // OUT (C),B case 0x42: SBC_HL(BC); break; // * SBC HL,BC case 0x43: memWriteWord(memReadWord(PC), BC); PC += 2; break; // LD (NN),BC case 0x44: NEG(); break; // NEG case 0x45: IFF1 = IFF2; RET(); Interrupt(); break; // * RETN case 0x46: IM = 0; break; // * IM 0 case 0x47: I = getA(); break; // LD I,A (incomplete) case 0x48: setC(IN()); break; // IN C,(C) case 0x49: ioWriteByte(BC, getC()); break; // OUT (C),C case 0x4A: ADC_HL(BC); break; // * ADC HL,BC case 0x4B: BC = memReadWord(memReadWord(PC)); PC += 2; break; // LD BC,(NN) case 0x4C: NEG(); break; // NEG case 0x4D: IFF1 = 1; RET(); break; // * RETI case 0x4E: IM = 0; break; // IM 0 case 0x4F: R = getA(); break; // LD R,A case 0x50: setD(IN()); break; // IN D,(C) case 0x51: ioWriteByte(BC, getD()); break; // OUT (C),D case 0x52: SBC_HL(DE); break; // * SBC HL,DE case 0x53: memWriteWord(memReadWord(PC), DE); PC += 2; break; // LD (NN),DE case 0x54: NEG(); break; // NEG case 0x55: IFF1 = IFF2; RET(); Interrupt(); break; // * RETN case 0x56: IM = 1; break; // * IM 1 case 0x57: setA(I); if ((IFF2) != 0) { SetVF(); } else { ClearVF(); } SIGN_FLAG(getA(), 8); ZERO_FLAG(getA()); ClearHF(); YF_XF_FLAGS(getA()); break; // LD A,I case 0x58: setE(IN()); break; // IN E,(C) case 0x59: ioWriteByte(BC, getE()); break; // OUT (C),E case 0x5A: ADC_HL(DE); break; // ADC HL,DE case 0x5B: DE = memReadWord(memReadWord(PC)); PC += 2; break; // LD DE,(NN) case 0x5C: NEG(); break; // NEG case 0x5D: IFF1 = IFF2; RET(); Interrupt(); break; // RETN case 0x5E: IM = 2; break; // IM 2 case 0x5F: setA(R); if ((IFF2) != 0) { SetVF(); } else { ClearVF(); } SIGN_FLAG(getA(), 8); ZERO_FLAG(getA()); ClearHF(); YF_XF_FLAGS(getA()); ClearNF(); break; // LD A,R case 0x60: setH(IN()); break; // IN H,(C) case 0x61: ioWriteByte(BC, getH()); break; // OUT (C),H case 0x62: SBC_HL(HL); break; // SBC HL,HL case 0x63: memWriteWord(memReadWord(PC), HL); PC += 2; break; // LD (NN),HL case 0x64: NEG(); break; // NEG case 0x65: IFF1 = IFF2; RET(); Interrupt(); break; // RETN case 0x66: IM = 0; break; // IM 0 case 0x67: RRD(); break; // * RRD case 0x68: setL(IN()); break; // IN L,(C) case 0x69: ioWriteByte(BC, getL()); break; // OUT (C),L case 0x6A: ADC_HL(HL); break; // * ADC HL,HL case 0x6B: HL = memReadWord(memReadWord(PC)); PC += 2; break; // LD HL,(NN) case 0x6C: NEG(); break; // NEG case 0x6D: IFF1 = IFF2; RET(); Interrupt(); break; // * RETN case 0x6E: IM = 0; break; // * IM 0 case 0x6F: RLD(); break; // * RLD case 0x70: IN(); break; // IN (C) case 0x71: ioWriteByte(BC, 0); break; // OUT (C),0 case 0x72: SBC_HL(SP); break; // SBC HL,SP case 0x73: memWriteWord(memReadWord(PC), SP); PC += 2; break; // LD (NN),SP case 0x74: NEG(); break; // NEG case 0x75: IFF1 = IFF2; RET(); Interrupt(); break; // * RETN case 0x76: IM = 2; break; // * IM 2 case 0x78: setA(IN()); break; // IN A,(C) case 0x79: ioWriteByte(BC, getA()); break; // OUT (C),A case 0x7A: ADC_HL(SP); break; // * ADC HL,SP case 0x7B: SP = memReadWord(memReadWord(PC)); PC += 2; break; // LD SP,(NN) case 0x7C: NEG(); break; // NEG case 0x7D: IFF1 = IFF2; RET(); Interrupt(); break; // * RETN case 0x7E: IM = 2; break; // * IM 2 case 0xA0: LDI(); break; // LDI case 0xA1: CPI(); break; // CPI case 0xA2: INI(); break; // INI case 0xA3: OUTI(); break; // OUTI case 0xA8: LDD(); break; // LDD case 0xA9: CPD(); break; // CPD case 0xAA: IND(); break; // IND case 0xAB: OUTD(); break; // OUTD case 0xB0: LDIR(); break; // LDIR case 0xB1: CPIR(); break; // CPIR case 0xB2: INIR(); break; // INIR case 0xB3: OUTIR(); break; // OUTIR case 0xB8: LDDR(); break; // LDDR case 0xB9: CPDR(); break; // CPDR case 0xBA: INDR(); break; // INDR case 0xBB: OUTDR(); break; // OUTDR default: // Should not happen :) break; } cyclesToDo -= cycles_ed_opcode[opcode]; } private final void exe_cb_opcode(int opcode) { switch (opcode) { // CASE TABLE FOR CB OPCODES case 0x00: setB(RLC(getB())); break; case 0x01: setC(RLC(getC())); break; case 0x02: setD(RLC(getD())); break; case 0x03: setE(RLC(getE())); break; case 0x04: setH(RLC(getH())); break; case 0x05: setL(RLC(getL())); break; case 0x06: memWriteByte(HL, RLC(memReadByte(HL))); break; case 0x07: setA(RLC(getA())); break; case 0x08: setB(RRC(getB())); break; case 0x09: setC(RRC(getC())); break; case 0x0A: setD(RRC(getD())); break; case 0x0B: setE(RRC(getE())); break; case 0x0C: setH(RRC(getH())); break; case 0x0D: setL(RRC(getL())); break; case 0x0E: memWriteByte(HL, RRC(memReadByte(HL))); break; case 0x0F: setA(RRC(getA())); break; case 0x10: setB(RL(getB())); break; case 0x11: setC(RL(getC())); break; case 0x12: setD(RL(getD())); break; case 0x13: setE(RL(getE())); break; case 0x14: setH(RL(getH())); break; case 0x15: setL(RL(getL())); break; case 0x16: memWriteByte(HL, RL(memReadByte(HL))); break; case 0x17: setA(RL(getA())); break; case 0x18: setB(RR(getB())); break; case 0x19: setC(RR(getC())); break; case 0x1A: setD(RR(getD())); break; case 0x1B: setE(RR(getE())); break; case 0x1C: setH(RR(getH())); break; case 0x1D: setL(RR(getL())); break; case 0x1E: memWriteByte(HL, RR(memReadByte(HL))); break; case 0x1F: setA(RR(getA())); break; case 0x20: setB(SLA(getB())); break; case 0x21: setC(SLA(getC())); break; case 0x22: setD(SLA(getD())); break; case 0x23: setE(SLA(getE())); break; case 0x24: setH(SLA(getH())); break; case 0x25: setL(SLA(getL())); break; case 0x26: memWriteByte(HL, SLA(memReadByte(HL))); break; case 0x27: setA(SLA(getA())); break; case 0x28: setB(SRA(getB())); break; case 0x29: setC(SRA(getC())); break; case 0x2A: setD(SRA(getD())); break; case 0x2B: setE(SRA(getE())); break; case 0x2C: setH(SRA(getH())); break; case 0x2D: setL(SRA(getL())); break; case 0x2E: memWriteByte(HL, SRA(memReadByte(HL))); break; case 0x2F: setA(SRA(getA())); break; case 0x30: setB(SLL(getB())); break; case 0x31: setC(SLL(getC())); break; case 0x32: setD(SLL(getD())); break; case 0x33: setE(SLL(getE())); break; case 0x34: setH(SLL(getH())); break; case 0x35: setL(SLL(getL())); break; case 0x36: memWriteByte(HL, SLL(memReadByte(HL))); break; case 0x37: setA(SLL(getA())); break; case 0x38: setB(SRL(getB())); break; case 0x39: setC(SRL(getC())); break; case 0x3A: setD(SRL(getD())); break; case 0x3B: setE(SRL(getE())); break; case 0x3C: setH(SRL(getH())); break; case 0x3D: setL(SRL(getL())); break; case 0x3E: memWriteByte(HL, SRL(memReadByte(HL))); break; case 0x3F: setA(SRL(getA())); break; case 0x40: BIT(0, getB()); break; case 0x41: BIT(0, getC()); break; case 0x42: BIT(0, getD()); break; case 0x43: BIT(0, getE()); break; case 0x44: BIT(0, getH()); break; case 0x45: BIT(0, getL()); break; case 0x46: BIT(0, memReadByte(HL)); break; case 0x47: BIT(0, getA()); break; case 0x48: BIT(1, getB()); break; case 0x49: BIT(1, getC()); break; case 0x4A: BIT(1, getD()); break; case 0x4B: BIT(1, getE()); break; case 0x4C: BIT(1, getH()); break; case 0x4D: BIT(1, getL()); break; case 0x4E: BIT(1, memReadByte(HL)); break; case 0x4F: BIT(1, getA()); break; case 0x50: BIT(2, getB()); break; case 0x51: BIT(2, getC()); break; case 0x52: BIT(2, getD()); break; case 0x53: BIT(2, getE()); break; case 0x54: BIT(2, getH()); break; case 0x55: BIT(2, getL()); break; case 0x56: BIT(2, memReadByte(HL)); break; case 0x57: BIT(2, getA()); break; case 0x58: BIT(3, getB()); break; case 0x59: BIT(3, getC()); break; case 0x5A: BIT(3, getD()); break; case 0x5B: BIT(3, getE()); break; case 0x5C: BIT(3, getH()); break; case 0x5D: BIT(3, getL()); break; case 0x5E: BIT(3, memReadByte(HL)); break; case 0x5F: BIT(3, getA()); break; case 0x60: BIT(4, getB()); break; case 0x61: BIT(4, getC()); break; case 0x62: BIT(4, getD()); break; case 0x63: BIT(4, getE()); break; case 0x64: BIT(4, getH()); break; case 0x65: BIT(4, getL()); break; case 0x66: BIT(4, memReadByte(HL)); break; case 0x67: BIT(4, getA()); break; case 0x68: BIT(5, getB()); break; case 0x69: BIT(5, getC()); break; case 0x6A: BIT(5, getD()); break; case 0x6B: BIT(5, getE()); break; case 0x6C: BIT(5, getH()); break; case 0x6D: BIT(5, getL()); break; case 0x6E: BIT(5, memReadByte(HL)); break; case 0x6F: BIT(5, getA()); break; case 0x70: BIT(6, getB()); break; case 0x71: BIT(6, getC()); break; case 0x72: BIT(6, getD()); break; case 0x73: BIT(6, getE()); break; case 0x74: BIT(6, getH()); break; case 0x75: BIT(6, getL()); break; case 0x76: BIT(6, memReadByte(HL)); break; case 0x77: BIT(6, getA()); break; case 0x78: BIT(7, getB()); break; case 0x79: BIT(7, getC()); break; case 0x7A: BIT(7, getD()); break; case 0x7B: BIT(7, getE()); break; case 0x7C: BIT(7, getH()); break; case 0x7D: BIT(7, getL()); break; case 0x7E: BIT(7, memReadByte(HL)); break; case 0x7F: BIT(7, getA()); break; case 0x80: setB(RES(0, getB())); break; case 0x81: setC(RES(0, getC())); break; case 0x82: setD(RES(0, getD())); break; case 0x83: setE(RES(0, getE())); break; case 0x84: setH(RES(0, getH())); break; case 0x85: setL(RES(0, getL())); break; case 0x86: memWriteByte(HL, RES(0, memReadByte(HL))); break; case 0x87: setA(RES(0, getA())); break; case 0x88: setB(RES(1, getB())); break; case 0x89: setC(RES(1, getC())); break; case 0x8A: setD(RES(1, getD())); break; case 0x8B: setE(RES(1, getE())); break; case 0x8C: setH(RES(1, getH())); break; case 0x8D: setL(RES(1, getL())); break; case 0x8E: memWriteByte(HL, RES(1, memReadByte(HL))); break; case 0x8F: setA(RES(1, getA())); break; case 0x90: setB(RES(2, getB())); break; case 0x91: setC(RES(2, getC())); break; case 0x92: setD(RES(2, getD())); break; case 0x93: setE(RES(2, getE())); break; case 0x94: setH(RES(2, getH())); break; case 0x95: setL(RES(2, getL())); break; case 0x96: memWriteByte(HL, RES(2, memReadByte(HL))); break; case 0x97: setA(RES(2, getA())); break; case 0x98: setB(RES(3, getB())); break; case 0x99: setC(RES(3, getC())); break; case 0x9A: setD(RES(3, getD())); break; case 0x9B: setE(RES(3, getE())); break; case 0x9C: setH(RES(3, getH())); break; case 0x9D: setL(RES(3, getL())); break; case 0x9E: memWriteByte(HL, RES(3, memReadByte(HL))); break; case 0x9F: setA(RES(3, getA())); break; case 0xA0: setB(RES(4, getB())); break; case 0xA1: setC(RES(4, getC())); break; case 0xA2: setD(RES(4, getD())); break; case 0xA3: setE(RES(4, getE())); break; case 0xA4: setH(RES(4, getH())); break; case 0xA5: setL(RES(4, getL())); break; case 0xA6: memWriteByte(HL, RES(4, memReadByte(HL))); break; case 0xA7: setA(RES(4, getA())); break; case 0xA8: setB(RES(5, getB())); break; case 0xA9: setC(RES(5, getC())); break; case 0xAA: setD(RES(5, getD())); break; case 0xAB: setE(RES(5, getE())); break; case 0xAC: setH(RES(5, getH())); break; case 0xAD: setL(RES(5, getL())); break; case 0xAE: memWriteByte(HL, RES(5, memReadByte(HL))); break; case 0xAF: setA(RES(5, getA())); break; case 0xB0: setB(RES(6, getB())); break; case 0xB1: setC(RES(6, getC())); break; case 0xB2: setD(RES(6, getD())); break; case 0xB3: setE(RES(6, getE())); break; case 0xB4: setH(RES(6, getH())); break; case 0xB5: setL(RES(6, getL())); break; case 0xB6: memWriteByte(HL, RES(6, memReadByte(HL))); break; case 0xB7: setA(RES(6, getA())); break; case 0xB8: setB(RES(7, getB())); break; case 0xB9: setC(RES(7, getC())); break; case 0xBA: setD(RES(7, getD())); break; case 0xBB: setE(RES(7, getE())); break; case 0xBC: setH(RES(7, getH())); break; case 0xBD: setL(RES(7, getL())); break; case 0xBE: memWriteByte(HL, RES(7, memReadByte(HL))); break; case 0xBF: setA(RES(7, getA())); break; case 0xC0: setB(SET(0, getB())); break; case 0xC1: setC(SET(0, getC())); break; case 0xC2: setD(SET(0, getD())); break; case 0xC3: setE(SET(0, getE())); break; case 0xC4: setH(SET(0, getH())); break; case 0xC5: setL(SET(0, getL())); break; case 0xC6: memWriteByte(HL, SET(0, memReadByte(HL))); break; case 0xC7: setA(SET(0, getA())); break; case 0xC8: setB(SET(1, getB())); break; case 0xC9: setC(SET(1, getC())); break; case 0xCA: setD(SET(1, getD())); break; case 0xCB: setE(SET(1, getE())); break; case 0xCC: setH(SET(1, getH())); break; case 0xCD: setL(SET(1, getL())); break; case 0xCE: memWriteByte(HL, SET(1, memReadByte(HL))); break; case 0xCF: setA(SET(1, getA())); break; case 0xD0: setB(SET(2, getB())); break; case 0xD1: setC(SET(2, getC())); break; case 0xD2: setD(SET(2, getD())); break; case 0xD3: setE(SET(2, getE())); break; case 0xD4: setH(SET(2, getH())); break; case 0xD5: setL(SET(2, getL())); break; case 0xD6: memWriteByte(HL, SET(2, memReadByte(HL))); break; case 0xD7: setA(SET(2, getA())); break; case 0xD8: setB(SET(3, getB())); break; case 0xD9: setC(SET(3, getC())); break; case 0xDA: setD(SET(3, getD())); break; case 0xDB: setE(SET(3, getE())); break; case 0xDC: setH(SET(3, getH())); break; case 0xDD: setL(SET(3, getL())); break; case 0xDE: memWriteByte(HL, SET(3, memReadByte(HL))); break; case 0xDF: setA(SET(3, getA())); break; case 0xE0: setB(SET(4, getB())); break; case 0xE1: setC(SET(4, getC())); break; case 0xE2: setD(SET(4, getD())); break; case 0xE3: setE(SET(4, getE())); break; case 0xE4: setH(SET(4, getH())); break; case 0xE5: setL(SET(4, getL())); break; case 0xE6: memWriteByte(HL, SET(4, memReadByte(HL))); break; case 0xE7: setA(SET(4, getA())); break; case 0xE8: setB(SET(5, getB())); break; case 0xE9: setC(SET(5, getC())); break; case 0xEA: setD(SET(5, getD())); break; case 0xEB: setE(SET(5, getE())); break; case 0xEC: setH(SET(5, getH())); break; case 0xED: setL(SET(5, getL())); break; case 0xEE: memWriteByte(HL, SET(5, memReadByte(HL))); break; case 0xEF: setA(SET(5, getA())); break; case 0xF0: setB(SET(6, getB())); break; case 0xF1: setC(SET(6, getC())); break; case 0xF2: setD(SET(6, getD())); break; case 0xF3: setE(SET(6, getE())); break; case 0xF4: setH(SET(6, getH())); break; case 0xF5: setL(SET(6, getL())); break; case 0xF6: memWriteByte(HL, SET(6, memReadByte(HL))); break; case 0xF7: setA(SET(6, getA())); break; case 0xF8: setB(SET(7, getB())); break; case 0xF9: setC(SET(7, getC())); break; case 0xFA: setD(SET(7, getD())); break; case 0xFB: setE(SET(7, getE())); break; case 0xFC: setH(SET(7, getH())); break; case 0xFD: setL(SET(7, getL())); break; case 0xFE: memWriteByte(HL, SET(7, memReadByte(HL))); break; case 0xFF: setA(SET(7, getA())); break; } cyclesToDo -= cycles_cb_opcode[opcode]; } private final int exe_dd_opcode(int index, int opcode) { XY = index; switch (opcode) { // CASE TABLE FOR DD OPCODES case 0xCB: exe_dd_cb_opcode(memReadByte(++PC)); break; // Prefix case 0xED: exe_ed_opcode(memReadByte(PC++)); break; // Redirecting case 0xDD: IX = exe_dd_opcode(IX, memReadByte(PC++)); break; // Redirecting case 0xFD: IY = exe_dd_opcode(IY, memReadByte(PC++)); break; // Redirecting case 0x09: XY = ADD16(XY, BC); break; // ADD XY,BC case 0x19: XY = ADD16(XY, DE); break; // ADD XY,DE case 0x21: XY = memReadWord(PC); PC += 2; break; // LD XY,NN case 0x22: memWriteWord(memReadWord(PC), XY); PC += 2; break; // LD (NN),XY case 0x23: XY++; XY &= 0xFFFF; break; // INC XY case 0x24: setXYH(INC(getXYH())); break; // INC XYH case 0x25: setXYH(DEC(getXYH())); break; // DEC XYH case 0x26: setXYH(memReadByte(PC++)); break; // LD XYH,N case 0x29: XY = ADD16(XY, XY); break; // ADD XY,XY case 0x2A: XY = memReadWord(memReadWord(PC)); PC += 2; break; // LD XY,(NN) case 0x2B: XY--; XY &= 0xFFFF; break; // DEC XY case 0x2C: setXYL(INC(getXYL())); break; // INC XYL case 0x2D: setXYL(DEC(getXYL())); break; // DEC XYL case 0x2E: setXYL(memReadByte(PC++)); break; // LD XYL,N case 0x34: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, INC(memReadByte(word))); break; // INC (XY+dd) case 0x35: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, DEC(memReadByte(word))); break; // DEC (XY+dd) case 0x36: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, memReadByte(PC++)); break; // LD (XY+d),N case 0x39: XY = ADD16(XY, SP); break; // ADD XY,SP case 0x44: setB(getXYH()); break; // LD B,XYH case 0x45: setB(getXYL()); break; // LD B,XYL case 0x46: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; setB(memReadByte(word)); break; // LD B,(XY+N) case 0x4C: setC(getXYH()); break; // LD C,XYH case 0x4D: setC(getXYL()); break; // LD C,XYL case 0x4E: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; setC(memReadByte(word)); break; // LD C,(XY+N) case 0x54: setD(getXYH()); break; // LD D,XYH case 0x55: setD(getXYL()); break; // LD D,XYL case 0x56: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; setD(memReadByte(word)); break; // LD D,(XY+N) case 0x5C: setE(getXYH()); break; // LD E,XYH case 0x5D: setE(getXYL()); break; // LD E,XYL case 0x5E: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; setE(memReadByte(word)); break; // LD E,(XY+N) case 0x60: setXYH(getB()); break; // LD XYH,B case 0x61: setXYH(getC()); break; // LD XYH,C case 0x62: setXYH(getD()); break; // LD XYH,D case 0x63: setXYH(getE()); break; // LD XYH,E case 0x64: break; // LD XYH,XYH case 0x65: setXYH(getXYL()); break; // LD XYH,XYL case 0x66: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; setH(memReadByte(word)); break; // LD H,(XY+d) case 0x67: setXYH(getA()); break; // LD XYH,A case 0x68: setXYL(getB()); break; // LD XYL,B case 0x69: setXYL(getC()); break; // LD XYL,C case 0x6A: setXYL(getD()); break; // LD XYL,D case 0x6B: setXYL(getE()); break; // LD XYL,E case 0x6C: setXYL(getXYH()); break; // LD XYL,XYH case 0x6D: break; // LD XYL,XYL case 0x6E: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; setL(memReadByte(word)); break; // LD L,(XY+d) case 0x6F: setXYL(getA()); break; // LD XYL,A case 0x70: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, getB()); break; // LD (XY+d),B case 0x71: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, getC()); break; // LD (XY+d),C case 0x72: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, getD()); break; // LD (XY+d),D case 0x73: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, getE()); break; // LD (XY+d,E case 0x74: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, getH()); break; // LD (XY+d),H case 0x75: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, getL()); break; // LD (XY+d),L case 0x77: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, getA()); break; // LD (XY+d),A case 0x7C: setA(getXYH()); break; case 0x7D: setA(getXYL()); break; case 0x7E: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; setA(memReadByte(word)); break; // LD A,(XY+d) case 0x84: ADD(getXYH()); break; // ADD A,XYH case 0x85: ADD(getXYL()); break; // ADD A,XYL case 0x86: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; ADD(memReadByte(word)); break; // ADD A,(XY+d) case 0x8C: ADC(getXYH()); break; // ADC A,XYH case 0x8D: ADC(getXYL()); break; // ADC A,XYL case 0x8E: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; ADC(memReadByte(word)); break; // ADC A,(XY+d) case 0x94: SUB(getXYH()); break; // SUB A,XYH case 0x95: SUB(getXYL()); break; // SUB A,XYL case 0x96: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; SUB(memReadByte(word)); break; // SUB A,(XY+d) case 0x9C: SBC(getXYH()); break; // SBC A,XYH case 0x9D: SBC(getXYL()); break; // SBC A,XYL case 0x9E: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; SBC(memReadByte(word)); break; // SBC A,(XY+d) case 0xA4: AND(getXYH()); break; // AND XYH case 0xA5: AND(getXYL()); break; // AND XYL case 0xA6: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; AND(memReadByte(word)); break; // AND (XY+d) case 0xAC: XOR(getXYH()); break; // XOR XYH case 0xAD: XOR(getXYL()); break; // XOR XYL case 0xAE: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; XOR(memReadByte(word)); break; // XOR (XY+d) case 0xB4: OR(getXYH()); break; // OR XYH case 0xB5: OR(getXYL()); break; // OR XYL case 0xB6: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; OR(memReadByte(word)); break; // OR (XY+d) case 0xBC: CP(getXYH()); break; // CP XYH case 0xBD: CP(getXYL()); break; // CP XYL case 0xBE: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; CP(memReadByte(word)); break; // CP (XY+d) case 0xE1: XY = POP(); break; // POP XY case 0xE3: word = memReadWord(SP); memWriteWord(SP, XY); XY = word; break; // EX (SP),XY case 0xE5: PUSH(XY); break; // PUSH XY case 0xE9: PC = XY; break; // JP XY case 0xF9: SP = XY; break; // LD SP,XY } cyclesToDo -= cycles_dd_opcode[opcode]; return XY; } private final void exe_dd_cb_opcode(int opcode) { PC--; switch (opcode) { // CASE TABLE FOR DD-CB OPCODES case 0x00: setB(LD_RLC(XY)); break; case 0x01: setC(LD_RLC(XY)); break; case 0x02: setD(LD_RLC(XY)); break; case 0x03: setE(LD_RLC(XY)); break; case 0x04: setH(LD_RLC(XY)); break; case 0x05: setL(LD_RLC(XY)); break; case 0x06: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RLC(memReadByte(addr))); break; case 0x07: setA(LD_RLC(XY)); break; case 0x08: setB(LD_RRC(XY)); break; case 0x09: setC(LD_RRC(XY)); break; case 0x0A: setD(LD_RRC(XY)); break; case 0x0B: setE(LD_RRC(XY)); break; case 0x0C: setH(LD_RRC(XY)); break; case 0x0D: setL(LD_RRC(XY)); break; case 0x0E: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RRC(memReadByte(addr))); break; case 0x0F: setA(LD_RRC(XY)); break; case 0x10: setB(LD_RL(XY)); break; case 0x11: setC(LD_RL(XY)); break; case 0x12: setD(LD_RL(XY)); break; case 0x13: setE(LD_RL(XY)); break; case 0x14: setH(LD_RL(XY)); break; case 0x15: setL(LD_RL(XY)); break; case 0x16: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RL(memReadByte(addr))); break; case 0x17: setA(LD_RL(XY)); break; case 0x18: setB(LD_RR(XY)); break; case 0x19: setC(LD_RR(XY)); break; case 0x1A: setD(LD_RR(XY)); break; case 0x1B: setE(LD_RR(XY)); break; case 0x1C: setH(LD_RR(XY)); break; case 0x1D: setL(LD_RR(XY)); break; case 0x1E: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RR(memReadByte(addr))); break; case 0x1F: setA(LD_RR(XY)); break; case 0x20: setB(LD_SLA(XY)); break; case 0x21: setC(LD_SLA(XY)); break; case 0x22: setD(LD_SLA(XY)); break; case 0x23: setE(LD_SLA(XY)); break; case 0x24: setH(LD_SLA(XY)); break; case 0x25: setL(LD_SLA(XY)); break; case 0x26: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SLA(memReadByte(addr))); break; case 0x27: setA(LD_SLA(XY)); break; case 0x28: setB(LD_SRA(XY)); break; case 0x29: setC(LD_SRA(XY)); break; case 0x2A: setD(LD_SRA(XY)); break; case 0x2B: setE(LD_SRA(XY)); break; case 0x2C: setH(LD_SRA(XY)); break; case 0x2D: setL(LD_SRA(XY)); break; case 0x2E: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SRA(memReadByte(addr))); break; case 0x2F: setA(LD_SRA(XY)); break; case 0x30: setB(LD_SLL(XY)); break; case 0x31: setC(LD_SLL(XY)); break; case 0x32: setD(LD_SLL(XY)); break; case 0x33: setE(LD_SLL(XY)); break; case 0x34: setH(LD_SLL(XY)); break; case 0x35: setL(LD_SLL(XY)); break; case 0x36: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SLL(memReadByte(addr))); break; case 0x37: setA(LD_SLL(XY)); break; case 0x38: setB(LD_SRL(XY)); break; case 0x39: setC(LD_SRL(XY)); break; case 0x3A: setD(LD_SRL(XY)); break; case 0x3B: setE(LD_SRL(XY)); break; case 0x3C: setH(LD_SRL(XY)); break; case 0x3D: setL(LD_SRL(XY)); break; case 0x3E: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SRL(memReadByte(addr))); break; case 0x3F: setA(LD_SRL(XY)); break; case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: BIT(0, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: BIT(1, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: BIT(2, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x58: case 0x59: case 0x5A: case 0x5B: case 0x5C: case 0x5D: case 0x5E: case 0x5F: BIT(3, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: BIT(4, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: BIT(5, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: BIT(6, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x78: case 0x79: case 0x7A: case 0x7B: case 0x7C: case 0x7D: case 0x7E: case 0x7F: BIT(7, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x80: setB(LD_RES(XY, 0)); break; case 0x81: setC(LD_RES(XY, 0)); break; case 0x82: setD(LD_RES(XY, 0)); break; case 0x83: setE(LD_RES(XY, 0)); break; case 0x84: setH(LD_RES(XY, 0)); break; case 0x85: setL(LD_RES(XY, 0)); break; case 0x86: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(0, memReadByte(addr))); break; case 0x87: setA(LD_RES(XY, 0)); break; case 0x88: setB(LD_RES(XY, 1)); break; case 0x89: setC(LD_RES(XY, 1)); break; case 0x8A: setD(LD_RES(XY, 1)); break; case 0x8B: setE(LD_RES(XY, 1)); break; case 0x8C: setH(LD_RES(XY, 1)); break; case 0x8D: setL(LD_RES(XY, 1)); break; case 0x8E: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(1, memReadByte(addr))); break; case 0x8F: setA(LD_RES(XY, 1)); break; case 0x90: setB(LD_RES(XY, 2)); break; case 0x91: setC(LD_RES(XY, 2)); break; case 0x92: setD(LD_RES(XY, 2)); break; case 0x93: setE(LD_RES(XY, 2)); break; case 0x94: setH(LD_RES(XY, 2)); break; case 0x95: setL(LD_RES(XY, 2)); break; case 0x96: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(2, memReadByte(addr))); break; case 0x97: setA(LD_RES(XY, 2)); break; case 0x98: setB(LD_RES(XY, 3)); break; case 0x99: setC(LD_RES(XY, 3)); break; case 0x9A: setD(LD_RES(XY, 3)); break; case 0x9B: setE(LD_RES(XY, 3)); break; case 0x9C: setH(LD_RES(XY, 3)); break; case 0x9D: setL(LD_RES(XY, 3)); break; case 0x9E: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(3, memReadByte(addr))); break; case 0x9F: setA(LD_RES(XY, 3)); break; case 0xA0: setB(LD_RES(XY, 4)); break; case 0xA1: setC(LD_RES(XY, 4)); break; case 0xA2: setD(LD_RES(XY, 4)); break; case 0xA3: setE(LD_RES(XY, 4)); break; case 0xA4: setH(LD_RES(XY, 4)); break; case 0xA5: setL(LD_RES(XY, 4)); break; case 0xA6: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(4, memReadByte(addr))); break; case 0xA7: setA(LD_RES(XY, 4)); break; case 0xA8: setB(LD_RES(XY, 5)); break; case 0xA9: setC(LD_RES(XY, 5)); break; case 0xAA: setD(LD_RES(XY, 5)); break; case 0xAB: setE(LD_RES(XY, 5)); break; case 0xAC: setH(LD_RES(XY, 5)); break; case 0xAD: setL(LD_RES(XY, 5)); break; case 0xAE: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(5, memReadByte(addr))); break; case 0xAF: setA(LD_RES(XY, 5)); break; case 0xB0: setB(LD_RES(XY, 6)); break; case 0xB1: setC(LD_RES(XY, 6)); break; case 0xB2: setD(LD_RES(XY, 6)); break; case 0xB3: setE(LD_RES(XY, 6)); break; case 0xB4: setH(LD_RES(XY, 6)); break; case 0xB5: setL(LD_RES(XY, 6)); break; case 0xB6: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(6, memReadByte(addr))); break; case 0xB7: setA(LD_RES(XY, 6)); break; case 0xB8: setB(LD_RES(XY, 7)); break; case 0xB9: setC(LD_RES(XY, 7)); break; case 0xBA: setD(LD_RES(XY, 7)); break; case 0xBB: setE(LD_RES(XY, 7)); break; case 0xBC: setH(LD_RES(XY, 7)); break; case 0xBD: setL(LD_RES(XY, 7)); break; case 0xBE: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(7, memReadByte(addr))); break; case 0xBF: setA(LD_RES(XY, 7)); break; case 0xC0: setB(LD_SET(XY, 0)); break; case 0xC1: setC(LD_SET(XY, 0)); break; case 0xC2: setD(LD_SET(XY, 0)); break; case 0xC3: setE(LD_SET(XY, 0)); break; case 0xC4: setH(LD_SET(XY, 0)); break; case 0xC5: setL(LD_SET(XY, 0)); break; case 0xC6: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(0, memReadByte(addr))); break; case 0xC7: setA(LD_SET(XY, 0)); break; case 0xC8: setB(LD_SET(XY, 1)); break; case 0xC9: setC(LD_SET(XY, 1)); break; case 0xCA: setD(LD_SET(XY, 1)); break; case 0xCB: setE(LD_SET(XY, 1)); break; case 0xCC: setH(LD_SET(XY, 1)); break; case 0xCD: setL(LD_SET(XY, 1)); break; case 0xCE: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(1, memReadByte(addr))); break; case 0xCF: setA(LD_SET(XY, 1)); break; case 0xD0: setB(LD_SET(XY, 2)); break; case 0xD1: setC(LD_SET(XY, 2)); break; case 0xD2: setD(LD_SET(XY, 2)); break; case 0xD3: setE(LD_SET(XY, 2)); break; case 0xD4: setH(LD_SET(XY, 2)); break; case 0xD5: setL(LD_SET(XY, 2)); break; case 0xD6: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(2, memReadByte(addr))); break; case 0xD7: setA(LD_SET(XY, 2)); break; case 0xD8: setB(LD_SET(XY, 3)); break; case 0xD9: setC(LD_SET(XY, 3)); break; case 0xDA: setD(LD_SET(XY, 3)); break; case 0xDB: setE(LD_SET(XY, 3)); break; case 0xDC: setH(LD_SET(XY, 3)); break; case 0xDD: setL(LD_SET(XY, 3)); break; case 0xDE: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(3, memReadByte(addr))); break; case 0xDF: setA(LD_SET(XY, 3)); break; case 0xE0: setB(LD_SET(XY, 4)); break; case 0xE1: setC(LD_SET(XY, 4)); break; case 0xE2: setD(LD_SET(XY, 4)); break; case 0xE3: setE(LD_SET(XY, 4)); break; case 0xE4: setH(LD_SET(XY, 4)); break; case 0xE5: setL(LD_SET(XY, 4)); break; case 0xE6: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(4, memReadByte(addr))); break; case 0xE7: setA(LD_SET(XY, 4)); break; case 0xE8: setB(LD_SET(XY, 5)); break; case 0xE9: setC(LD_SET(XY, 5)); break; case 0xEA: setD(LD_SET(XY, 5)); break; case 0xEB: setE(LD_SET(XY, 5)); break; case 0xEC: setH(LD_SET(XY, 5)); break; case 0xED: setL(LD_SET(XY, 5)); break; case 0xEE: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(5, memReadByte(addr))); break; case 0xEF: setA(LD_SET(XY, 5)); break; case 0xF0: setB(LD_SET(XY, 6)); break; case 0xF1: setC(LD_SET(XY, 6)); break; case 0xF2: setD(LD_SET(XY, 6)); break; case 0xF3: setE(LD_SET(XY, 6)); break; case 0xF4: setH(LD_SET(XY, 6)); break; case 0xF5: setL(LD_SET(XY, 6)); break; case 0xF6: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(6, memReadByte(addr))); break; case 0xF7: setA(LD_SET(XY, 6)); break; case 0xF8: setB(LD_SET(XY, 7)); break; case 0xF9: setC(LD_SET(XY, 7)); break; case 0xFA: setD(LD_SET(XY, 7)); break; case 0xFB: setE(LD_SET(XY, 7)); break; case 0xFC: setH(LD_SET(XY, 7)); break; case 0xFD: setL(LD_SET(XY, 7)); break; case 0xFE: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(7, memReadByte(addr))); break; case 0xFF: setA(LD_SET(XY, 7)); break; } PC++; cyclesToDo -= cycles_xx_cb_opcode[opcode]; } public final void run(int nbCycles) { totalClocks=totalClocks.add(BigInteger.valueOf(sliceClocks-cyclesToDo)); sliceClocks=nbCycles; cyclesToDo += nbCycles; Interrupt(); while (cyclesToDo > 0) { UpdateR(); // Accepts interrupts the intruction AFTER EI switch (enable) { case 2: IFF1 = IFF2 = 1; Interrupt(); enable = 0; break; case 1: enable = 2; break; } if (halted == false) { exeOpcode(memReadByte(PC++)); PC &= 0xFFFF; } else { cyclesToDo -= 4; Interrupt(); } } } public final void PendingIRQ(int value) { vector = value; IRQ = 1; if (IFF1 != 0) { CheckIRQ(); } } public final void PendingNMI() { NMIInt = 1; } public final void CheckIRQ() { if ((IFF1 == 0) || (IRQ == 0)) { return; } IRQ = IFF1 = IFF2 = 0; halted = false; UpdateR(); switch (IM) { // 8080 compatible mode case 0: exeOpcode(vector); break; // RST 38h case 1: SP -= 2; SP &= 0xFFFF; memWriteWord(SP, PC); PC = 0x0038; cyclesToDo -= 13; break; // CALL (address I*256+(value read on the bus)) case 2: SP -= 2; SP &= 0xFFFF; memWriteWord(SP, PC); PC = memReadWord(((I) << 8) + vector); cyclesToDo -= 19; break; } } private final void PF_Table_init() { int c; byte d; int m; for (c = 0; c <= 255; c++) { d = 0; for (m = 0; m <= 7; m++) { if ((c & (1 << m)) != 0) { d ^= 1; } } PF_Table[c] = d; } } public final void NMI() { NMIInt = IFF1 = 0; // Disable interrupts and ack the interrupt halted = false; // Unhalt the CPU SP -= 2; SP &= 0xFFFF; memWriteWord(SP, PC); PC = NMI_PC; // NMI ! } public final void Interrupt() { if (NMIInt != 0) { NMI(); cyclesToDo -= 11; return; } if ((IFF1 != 0) && (IRQ != 0)) { CheckIRQ(); cyclesToDo += 19; return; } } private static final int cycles_main_opcode[] = { 4, 10, 7, 6, 4, 4, 7, 4, 4, 11, 7, 6, 4, 4, 7, 4, 10, 10, 7, 6, 4, 4, 7, 4, 12, 11, 7, 6, 4, 4, 7, 4, 7, 10, 16, 6, 4, 4, 7, 4, 7, 11, 16, 6, 4, 4, 7, 4, 7, 10, 13, 6, 11, 11, 10, 4, 7, 11, 13, 6, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 7, 7, 7, 7, 7, 7, 4, 7, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 5, 10, 10, 10, 10, 11, 7, 11, 5, 10, 10, 0, 10, 17, 7, 11, 5, 10, 10, 11, 10, 11, 7, 11, 5, 4, 10, 11, 10, 0, 7, 11, 5, 10, 10, 19, 10, 11, 7, 11, 5, 4, 10, 4, 10, 0, 7, 11, 5, 10, 10, 4, 10, 11, 7, 11, 5, 6, 10, 4, 10, 0, 7, 11 }; private static final int cycles_ed_opcode[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 12, 15, 20, 8, 8, 8, 9, 12, 12, 15, 20, 8, 8, 8, 9, 12, 12, 15, 20, 8, 8, 8, 9, 12, 12, 15, 20, 8, 8, 8, 9, 12, 12, 15, 20, 8, 8, 8, 18, 12, 12, 15, 20, 8, 8, 8, 18, 12, 12, 15, 20, 8, 8, 8, 8, 12, 12, 15, 20, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 8, 8, 8, 8, 16, 16, 16, 16, 8, 8, 8, 8, 16, 16, 16, 16, 8, 8, 8, 8, 16, 16, 16, 16, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; private static final int cycles_dd_opcode[] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 15, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 15, 4, 4, 4, 4, 4, 4, 4, 14, 20, 10, 8, 8, 11, 4, 4, 15, 20, 10, 8, 8, 11, 4, 4, 4, 4, 4, 23, 23, 19, 4, 4, 15, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8, 8, 8, 8, 8, 19, 8, 19, 19, 19, 19, 19, 19, 4, 19, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, }; private static final int cycles_cb_opcode[] = { 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, }; private static final int cycles_xx_cb_opcode[] = { 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, }; private static final int DAATable2[] = { 0x0044, 0x0100, 0x0200, 0x0304, 0x0400, 0x0504, 0x0604, 0x0700, 0x0808, 0x090C, 0x1010, 0x1114, 0x1214, 0x1310, 0x1414, 0x1510, 0x1000, 0x1104, 0x1204, 0x1300, 0x1404, 0x1500, 0x1600, 0x1704, 0x180C, 0x1908, 0x2030, 0x2134, 0x2234, 0x2330, 0x2434, 0x2530, 0x2020, 0x2124, 0x2224, 0x2320, 0x2424, 0x2520, 0x2620, 0x2724, 0x282C, 0x2928, 0x3034, 0x3130, 0x3230, 0x3334, 0x3430, 0x3534, 0x3024, 0x3120, 0x3220, 0x3324, 0x3420, 0x3524, 0x3624, 0x3720, 0x3828, 0x392C, 0x4010, 0x4114, 0x4214, 0x4310, 0x4414, 0x4510, 0x4000, 0x4104, 0x4204, 0x4300, 0x4404, 0x4500, 0x4600, 0x4704, 0x480C, 0x4908, 0x5014, 0x5110, 0x5210, 0x5314, 0x5410, 0x5514, 0x5004, 0x5100, 0x5200, 0x5304, 0x5400, 0x5504, 0x5604, 0x5700, 0x5808, 0x590C, 0x6034, 0x6130, 0x6230, 0x6334, 0x6430, 0x6534, 0x6024, 0x6120, 0x6220, 0x6324, 0x6420, 0x6524, 0x6624, 0x6720, 0x6828, 0x692C, 0x7030, 0x7134, 0x7234, 0x7330, 0x7434, 0x7530, 0x7020, 0x7124, 0x7224, 0x7320, 0x7424, 0x7520, 0x7620, 0x7724, 0x782C, 0x7928, 0x8090, 0x8194, 0x8294, 0x8390, 0x8494, 0x8590, 0x8080, 0x8184, 0x8284, 0x8380, 0x8484, 0x8580, 0x8680, 0x8784, 0x888C, 0x8988, 0x9094, 0x9190, 0x9290, 0x9394, 0x9490, 0x9594, 0x9084, 0x9180, 0x9280, 0x9384, 0x9480, 0x9584, 0x9684, 0x9780, 0x9888, 0x998C, 0x0055, 0x0111, 0x0211, 0x0315, 0x0411, 0x0515, 0x0045, 0x0101, 0x0201, 0x0305, 0x0401, 0x0505, 0x0605, 0x0701, 0x0809, 0x090D, 0x1011, 0x1115, 0x1215, 0x1311, 0x1415, 0x1511, 0x1001, 0x1105, 0x1205, 0x1301, 0x1405, 0x1501, 0x1601, 0x1705, 0x180D, 0x1909, 0x2031, 0x2135, 0x2235, 0x2331, 0x2435, 0x2531, 0x2021, 0x2125, 0x2225, 0x2321, 0x2425, 0x2521, 0x2621, 0x2725, 0x282D, 0x2929, 0x3035, 0x3131, 0x3231, 0x3335, 0x3431, 0x3535, 0x3025, 0x3121, 0x3221, 0x3325, 0x3421, 0x3525, 0x3625, 0x3721, 0x3829, 0x392D, 0x4011, 0x4115, 0x4215, 0x4311, 0x4415, 0x4511, 0x4001, 0x4105, 0x4205, 0x4301, 0x4405, 0x4501, 0x4601, 0x4705, 0x480D, 0x4909, 0x5015, 0x5111, 0x5211, 0x5315, 0x5411, 0x5515, 0x5005, 0x5101, 0x5201, 0x5305, 0x5401, 0x5505, 0x5605, 0x5701, 0x5809, 0x590D, 0x6035, 0x6131, 0x6231, 0x6335, 0x6431, 0x6535, 0x6025, 0x6121, 0x6221, 0x6325, 0x6421, 0x6525, 0x6625, 0x6721, 0x6829, 0x692D, 0x7031, 0x7135, 0x7235, 0x7331, 0x7435, 0x7531, 0x7021, 0x7125, 0x7225, 0x7321, 0x7425, 0x7521, 0x7621, 0x7725, 0x782D, 0x7929, 0x8091, 0x8195, 0x8295, 0x8391, 0x8495, 0x8591, 0x8081, 0x8185, 0x8285, 0x8381, 0x8485, 0x8581, 0x8681, 0x8785, 0x888D, 0x8989, 0x9095, 0x9191, 0x9291, 0x9395, 0x9491, 0x9595, 0x9085, 0x9181, 0x9281, 0x9385, 0x9481, 0x9585, 0x9685, 0x9781, 0x9889, 0x998D, 0xA0B5, 0xA1B1, 0xA2B1, 0xA3B5, 0xA4B1, 0xA5B5, 0xA0A5, 0xA1A1, 0xA2A1, 0xA3A5, 0xA4A1, 0xA5A5, 0xA6A5, 0xA7A1, 0xA8A9, 0xA9AD, 0xB0B1, 0xB1B5, 0xB2B5, 0xB3B1, 0xB4B5, 0xB5B1, 0xB0A1, 0xB1A5, 0xB2A5, 0xB3A1, 0xB4A5, 0xB5A1, 0xB6A1, 0xB7A5, 0xB8AD, 0xB9A9, 0xC095, 0xC191, 0xC291, 0xC395, 0xC491, 0xC595, 0xC085, 0xC181, 0xC281, 0xC385, 0xC481, 0xC585, 0xC685, 0xC781, 0xC889, 0xC98D, 0xD091, 0xD195, 0xD295, 0xD391, 0xD495, 0xD591, 0xD081, 0xD185, 0xD285, 0xD381, 0xD485, 0xD581, 0xD681, 0xD785, 0xD88D, 0xD989, 0xE0B1, 0xE1B5, 0xE2B5, 0xE3B1, 0xE4B5, 0xE5B1, 0xE0A1, 0xE1A5, 0xE2A5, 0xE3A1, 0xE4A5, 0xE5A1, 0xE6A1, 0xE7A5, 0xE8AD, 0xE9A9, 0xF0B5, 0xF1B1, 0xF2B1, 0xF3B5, 0xF4B1, 0xF5B5, 0xF0A5, 0xF1A1, 0xF2A1, 0xF3A5, 0xF4A1, 0xF5A5, 0xF6A5, 0xF7A1, 0xF8A9, 0xF9AD, 0x0055, 0x0111, 0x0211, 0x0315, 0x0411, 0x0515, 0x0045, 0x0101, 0x0201, 0x0305, 0x0401, 0x0505, 0x0605, 0x0701, 0x0809, 0x090D, 0x1011, 0x1115, 0x1215, 0x1311, 0x1415, 0x1511, 0x1001, 0x1105, 0x1205, 0x1301, 0x1405, 0x1501, 0x1601, 0x1705, 0x180D, 0x1909, 0x2031, 0x2135, 0x2235, 0x2331, 0x2435, 0x2531, 0x2021, 0x2125, 0x2225, 0x2321, 0x2425, 0x2521, 0x2621, 0x2725, 0x282D, 0x2929, 0x3035, 0x3131, 0x3231, 0x3335, 0x3431, 0x3535, 0x3025, 0x3121, 0x3221, 0x3325, 0x3421, 0x3525, 0x3625, 0x3721, 0x3829, 0x392D, 0x4011, 0x4115, 0x4215, 0x4311, 0x4415, 0x4511, 0x4001, 0x4105, 0x4205, 0x4301, 0x4405, 0x4501, 0x4601, 0x4705, 0x480D, 0x4909, 0x5015, 0x5111, 0x5211, 0x5315, 0x5411, 0x5515, 0x5005, 0x5101, 0x5201, 0x5305, 0x5401, 0x5505, 0x5605, 0x5701, 0x5809, 0x590D, 0x6035, 0x6131, 0x6231, 0x6335, 0x6431, 0x6535, 0x0604, 0x0700, 0x0808, 0x090C, 0x0A0C, 0x0B08, 0x0C0C, 0x0D08, 0x0E08, 0x0F0C, 0x1010, 0x1114, 0x1214, 0x1310, 0x1414, 0x1510, 0x1600, 0x1704, 0x180C, 0x1908, 0x1A08, 0x1B0C, 0x1C08, 0x1D0C, 0x1E0C, 0x1F08, 0x2030, 0x2134, 0x2234, 0x2330, 0x2434, 0x2530, 0x2620, 0x2724, 0x282C, 0x2928, 0x2A28, 0x2B2C, 0x2C28, 0x2D2C, 0x2E2C, 0x2F28, 0x3034, 0x3130, 0x3230, 0x3334, 0x3430, 0x3534, 0x3624, 0x3720, 0x3828, 0x392C, 0x3A2C, 0x3B28, 0x3C2C, 0x3D28, 0x3E28, 0x3F2C, 0x4010, 0x4114, 0x4214, 0x4310, 0x4414, 0x4510, 0x4600, 0x4704, 0x480C, 0x4908, 0x4A08, 0x4B0C, 0x4C08, 0x4D0C, 0x4E0C, 0x4F08, 0x5014, 0x5110, 0x5210, 0x5314, 0x5410, 0x5514, 0x5604, 0x5700, 0x5808, 0x590C, 0x5A0C, 0x5B08, 0x5C0C, 0x5D08, 0x5E08, 0x5F0C, 0x6034, 0x6130, 0x6230, 0x6334, 0x6430, 0x6534, 0x6624, 0x6720, 0x6828, 0x692C, 0x6A2C, 0x6B28, 0x6C2C, 0x6D28, 0x6E28, 0x6F2C, 0x7030, 0x7134, 0x7234, 0x7330, 0x7434, 0x7530, 0x7620, 0x7724, 0x782C, 0x7928, 0x7A28, 0x7B2C, 0x7C28, 0x7D2C, 0x7E2C, 0x7F28, 0x8090, 0x8194, 0x8294, 0x8390, 0x8494, 0x8590, 0x8680, 0x8784, 0x888C, 0x8988, 0x8A88, 0x8B8C, 0x8C88, 0x8D8C, 0x8E8C, 0x8F88, 0x9094, 0x9190, 0x9290, 0x9394, 0x9490, 0x9594, 0x9684, 0x9780, 0x9888, 0x998C, 0x9A8C, 0x9B88, 0x9C8C, 0x9D88, 0x9E88, 0x9F8C, 0x0055, 0x0111, 0x0211, 0x0315, 0x0411, 0x0515, 0x0605, 0x0701, 0x0809, 0x090D, 0x0A0D, 0x0B09, 0x0C0D, 0x0D09, 0x0E09, 0x0F0D, 0x1011, 0x1115, 0x1215, 0x1311, 0x1415, 0x1511, 0x1601, 0x1705, 0x180D, 0x1909, 0x1A09, 0x1B0D, 0x1C09, 0x1D0D, 0x1E0D, 0x1F09, 0x2031, 0x2135, 0x2235, 0x2331, 0x2435, 0x2531, 0x2621, 0x2725, 0x282D, 0x2929, 0x2A29, 0x2B2D, 0x2C29, 0x2D2D, 0x2E2D, 0x2F29, 0x3035, 0x3131, 0x3231, 0x3335, 0x3431, 0x3535, 0x3625, 0x3721, 0x3829, 0x392D, 0x3A2D, 0x3B29, 0x3C2D, 0x3D29, 0x3E29, 0x3F2D, 0x4011, 0x4115, 0x4215, 0x4311, 0x4415, 0x4511, 0x4601, 0x4705, 0x480D, 0x4909, 0x4A09, 0x4B0D, 0x4C09, 0x4D0D, 0x4E0D, 0x4F09, 0x5015, 0x5111, 0x5211, 0x5315, 0x5411, 0x5515, 0x5605, 0x5701, 0x5809, 0x590D, 0x5A0D, 0x5B09, 0x5C0D, 0x5D09, 0x5E09, 0x5F0D, 0x6035, 0x6131, 0x6231, 0x6335, 0x6431, 0x6535, 0x6625, 0x6721, 0x6829, 0x692D, 0x6A2D, 0x6B29, 0x6C2D, 0x6D29, 0x6E29, 0x6F2D, 0x7031, 0x7135, 0x7235, 0x7331, 0x7435, 0x7531, 0x7621, 0x7725, 0x782D, 0x7929, 0x7A29, 0x7B2D, 0x7C29, 0x7D2D, 0x7E2D, 0x7F29, 0x8091, 0x8195, 0x8295, 0x8391, 0x8495, 0x8591, 0x8681, 0x8785, 0x888D, 0x8989, 0x8A89, 0x8B8D, 0x8C89, 0x8D8D, 0x8E8D, 0x8F89, 0x9095, 0x9191, 0x9291, 0x9395, 0x9491, 0x9595, 0x9685, 0x9781, 0x9889, 0x998D, 0x9A8D, 0x9B89, 0x9C8D, 0x9D89, 0x9E89, 0x9F8D, 0xA0B5, 0xA1B1, 0xA2B1, 0xA3B5, 0xA4B1, 0xA5B5, 0xA6A5, 0xA7A1, 0xA8A9, 0xA9AD, 0xAAAD, 0xABA9, 0xACAD, 0xADA9, 0xAEA9, 0xAFAD, 0xB0B1, 0xB1B5, 0xB2B5, 0xB3B1, 0xB4B5, 0xB5B1, 0xB6A1, 0xB7A5, 0xB8AD, 0xB9A9, 0xBAA9, 0xBBAD, 0xBCA9, 0xBDAD, 0xBEAD, 0xBFA9, 0xC095, 0xC191, 0xC291, 0xC395, 0xC491, 0xC595, 0xC685, 0xC781, 0xC889, 0xC98D, 0xCA8D, 0xCB89, 0xCC8D, 0xCD89, 0xCE89, 0xCF8D, 0xD091, 0xD195, 0xD295, 0xD391, 0xD495, 0xD591, 0xD681, 0xD785, 0xD88D, 0xD989, 0xDA89, 0xDB8D, 0xDC89, 0xDD8D, 0xDE8D, 0xDF89, 0xE0B1, 0xE1B5, 0xE2B5, 0xE3B1, 0xE4B5, 0xE5B1, 0xE6A1, 0xE7A5, 0xE8AD, 0xE9A9, 0xEAA9, 0xEBAD, 0xECA9, 0xEDAD, 0xEEAD, 0xEFA9, 0xF0B5, 0xF1B1, 0xF2B1, 0xF3B5, 0xF4B1, 0xF5B5, 0xF6A5, 0xF7A1, 0xF8A9, 0xF9AD, 0xFAAD, 0xFBA9, 0xFCAD, 0xFDA9, 0xFEA9, 0xFFAD, 0x0055, 0x0111, 0x0211, 0x0315, 0x0411, 0x0515, 0x0605, 0x0701, 0x0809, 0x090D, 0x0A0D, 0x0B09, 0x0C0D, 0x0D09, 0x0E09, 0x0F0D, 0x1011, 0x1115, 0x1215, 0x1311, 0x1415, 0x1511, 0x1601, 0x1705, 0x180D, 0x1909, 0x1A09, 0x1B0D, 0x1C09, 0x1D0D, 0x1E0D, 0x1F09, 0x2031, 0x2135, 0x2235, 0x2331, 0x2435, 0x2531, 0x2621, 0x2725, 0x282D, 0x2929, 0x2A29, 0x2B2D, 0x2C29, 0x2D2D, 0x2E2D, 0x2F29, 0x3035, 0x3131, 0x3231, 0x3335, 0x3431, 0x3535, 0x3625, 0x3721, 0x3829, 0x392D, 0x3A2D, 0x3B29, 0x3C2D, 0x3D29, 0x3E29, 0x3F2D, 0x4011, 0x4115, 0x4215, 0x4311, 0x4415, 0x4511, 0x4601, 0x4705, 0x480D, 0x4909, 0x4A09, 0x4B0D, 0x4C09, 0x4D0D, 0x4E0D, 0x4F09, 0x5015, 0x5111, 0x5211, 0x5315, 0x5411, 0x5515, 0x5605, 0x5701, 0x5809, 0x590D, 0x5A0D, 0x5B09, 0x5C0D, 0x5D09, 0x5E09, 0x5F0D, 0x6035, 0x6131, 0x6231, 0x6335, 0x6431, 0x6535, 0x0046, 0x0102, 0x0202, 0x0306, 0x0402, 0x0506, 0x0606, 0x0702, 0x080A, 0x090E, 0x0402, 0x0506, 0x0606, 0x0702, 0x080A, 0x090E, 0x1002, 0x1106, 0x1206, 0x1302, 0x1406, 0x1502, 0x1602, 0x1706, 0x180E, 0x190A, 0x1406, 0x1502, 0x1602, 0x1706, 0x180E, 0x190A, 0x2022, 0x2126, 0x2226, 0x2322, 0x2426, 0x2522, 0x2622, 0x2726, 0x282E, 0x292A, 0x2426, 0x2522, 0x2622, 0x2726, 0x282E, 0x292A, 0x3026, 0x3122, 0x3222, 0x3326, 0x3422, 0x3526, 0x3626, 0x3722, 0x382A, 0x392E, 0x3422, 0x3526, 0x3626, 0x3722, 0x382A, 0x392E, 0x4002, 0x4106, 0x4206, 0x4302, 0x4406, 0x4502, 0x4602, 0x4706, 0x480E, 0x490A, 0x4406, 0x4502, 0x4602, 0x4706, 0x480E, 0x490A, 0x5006, 0x5102, 0x5202, 0x5306, 0x5402, 0x5506, 0x5606, 0x5702, 0x580A, 0x590E, 0x5402, 0x5506, 0x5606, 0x5702, 0x580A, 0x590E, 0x6026, 0x6122, 0x6222, 0x6326, 0x6422, 0x6526, 0x6626, 0x6722, 0x682A, 0x692E, 0x6422, 0x6526, 0x6626, 0x6722, 0x682A, 0x692E, 0x7022, 0x7126, 0x7226, 0x7322, 0x7426, 0x7522, 0x7622, 0x7726, 0x782E, 0x792A, 0x7426, 0x7522, 0x7622, 0x7726, 0x782E, 0x792A, 0x8082, 0x8186, 0x8286, 0x8382, 0x8486, 0x8582, 0x8682, 0x8786, 0x888E, 0x898A, 0x8486, 0x8582, 0x8682, 0x8786, 0x888E, 0x898A, 0x9086, 0x9182, 0x9282, 0x9386, 0x9482, 0x9586, 0x9686, 0x9782, 0x988A, 0x998E, 0x3423, 0x3527, 0x3627, 0x3723, 0x382B, 0x392F, 0x4003, 0x4107, 0x4207, 0x4303, 0x4407, 0x4503, 0x4603, 0x4707, 0x480F, 0x490B, 0x4407, 0x4503, 0x4603, 0x4707, 0x480F, 0x490B, 0x5007, 0x5103, 0x5203, 0x5307, 0x5403, 0x5507, 0x5607, 0x5703, 0x580B, 0x590F, 0x5403, 0x5507, 0x5607, 0x5703, 0x580B, 0x590F, 0x6027, 0x6123, 0x6223, 0x6327, 0x6423, 0x6527, 0x6627, 0x6723, 0x682B, 0x692F, 0x6423, 0x6527, 0x6627, 0x6723, 0x682B, 0x692F, 0x7023, 0x7127, 0x7227, 0x7323, 0x7427, 0x7523, 0x7623, 0x7727, 0x782F, 0x792B, 0x7427, 0x7523, 0x7623, 0x7727, 0x782F, 0x792B, 0x8083, 0x8187, 0x8287, 0x8383, 0x8487, 0x8583, 0x8683, 0x8787, 0x888F, 0x898B, 0x8487, 0x8583, 0x8683, 0x8787, 0x888F, 0x898B, 0x9087, 0x9183, 0x9283, 0x9387, 0x9483, 0x9587, 0x9687, 0x9783, 0x988B, 0x998F, 0x9483, 0x9587, 0x9687, 0x9783, 0x988B, 0x998F, 0xA0A7, 0xA1A3, 0xA2A3, 0xA3A7, 0xA4A3, 0xA5A7, 0xA6A7, 0xA7A3, 0xA8AB, 0xA9AF, 0xA4A3, 0xA5A7, 0xA6A7, 0xA7A3, 0xA8AB, 0xA9AF, 0xB0A3, 0xB1A7, 0xB2A7, 0xB3A3, 0xB4A7, 0xB5A3, 0xB6A3, 0xB7A7, 0xB8AF, 0xB9AB, 0xB4A7, 0xB5A3, 0xB6A3, 0xB7A7, 0xB8AF, 0xB9AB, 0xC087, 0xC183, 0xC283, 0xC387, 0xC483, 0xC587, 0xC687, 0xC783, 0xC88B, 0xC98F, 0xC483, 0xC587, 0xC687, 0xC783, 0xC88B, 0xC98F, 0xD083, 0xD187, 0xD287, 0xD383, 0xD487, 0xD583, 0xD683, 0xD787, 0xD88F, 0xD98B, 0xD487, 0xD583, 0xD683, 0xD787, 0xD88F, 0xD98B, 0xE0A3, 0xE1A7, 0xE2A7, 0xE3A3, 0xE4A7, 0xE5A3, 0xE6A3, 0xE7A7, 0xE8AF, 0xE9AB, 0xE4A7, 0xE5A3, 0xE6A3, 0xE7A7, 0xE8AF, 0xE9AB, 0xF0A7, 0xF1A3, 0xF2A3, 0xF3A7, 0xF4A3, 0xF5A7, 0xF6A7, 0xF7A3, 0xF8AB, 0xF9AF, 0xF4A3, 0xF5A7, 0xF6A7, 0xF7A3, 0xF8AB, 0xF9AF, 0x0047, 0x0103, 0x0203, 0x0307, 0x0403, 0x0507, 0x0607, 0x0703, 0x080B, 0x090F, 0x0403, 0x0507, 0x0607, 0x0703, 0x080B, 0x090F, 0x1003, 0x1107, 0x1207, 0x1303, 0x1407, 0x1503, 0x1603, 0x1707, 0x180F, 0x190B, 0x1407, 0x1503, 0x1603, 0x1707, 0x180F, 0x190B, 0x2023, 0x2127, 0x2227, 0x2323, 0x2427, 0x2523, 0x2623, 0x2727, 0x282F, 0x292B, 0x2427, 0x2523, 0x2623, 0x2727, 0x282F, 0x292B, 0x3027, 0x3123, 0x3223, 0x3327, 0x3423, 0x3527, 0x3627, 0x3723, 0x382B, 0x392F, 0x3423, 0x3527, 0x3627, 0x3723, 0x382B, 0x392F, 0x4003, 0x4107, 0x4207, 0x4303, 0x4407, 0x4503, 0x4603, 0x4707, 0x480F, 0x490B, 0x4407, 0x4503, 0x4603, 0x4707, 0x480F, 0x490B, 0x5007, 0x5103, 0x5203, 0x5307, 0x5403, 0x5507, 0x5607, 0x5703, 0x580B, 0x590F, 0x5403, 0x5507, 0x5607, 0x5703, 0x580B, 0x590F, 0x6027, 0x6123, 0x6223, 0x6327, 0x6423, 0x6527, 0x6627, 0x6723, 0x682B, 0x692F, 0x6423, 0x6527, 0x6627, 0x6723, 0x682B, 0x692F, 0x7023, 0x7127, 0x7227, 0x7323, 0x7427, 0x7523, 0x7623, 0x7727, 0x782F, 0x792B, 0x7427, 0x7523, 0x7623, 0x7727, 0x782F, 0x792B, 0x8083, 0x8187, 0x8287, 0x8383, 0x8487, 0x8583, 0x8683, 0x8787, 0x888F, 0x898B, 0x8487, 0x8583, 0x8683, 0x8787, 0x888F, 0x898B, 0x9087, 0x9183, 0x9283, 0x9387, 0x9483, 0x9587, 0x9687, 0x9783, 0x988B, 0x998F, 0x9483, 0x9587, 0x9687, 0x9783, 0x988B, 0x998F, 0xFABE, 0xFBBA, 0xFCBE, 0xFDBA, 0xFEBA, 0xFFBE, 0x0046, 0x0102, 0x0202, 0x0306, 0x0402, 0x0506, 0x0606, 0x0702, 0x080A, 0x090E, 0x0A1E, 0x0B1A, 0x0C1E, 0x0D1A, 0x0E1A, 0x0F1E, 0x1002, 0x1106, 0x1206, 0x1302, 0x1406, 0x1502, 0x1602, 0x1706, 0x180E, 0x190A, 0x1A1A, 0x1B1E, 0x1C1A, 0x1D1E, 0x1E1E, 0x1F1A, 0x2022, 0x2126, 0x2226, 0x2322, 0x2426, 0x2522, 0x2622, 0x2726, 0x282E, 0x292A, 0x2A3A, 0x2B3E, 0x2C3A, 0x2D3E, 0x2E3E, 0x2F3A, 0x3026, 0x3122, 0x3222, 0x3326, 0x3422, 0x3526, 0x3626, 0x3722, 0x382A, 0x392E, 0x3A3E, 0x3B3A, 0x3C3E, 0x3D3A, 0x3E3A, 0x3F3E, 0x4002, 0x4106, 0x4206, 0x4302, 0x4406, 0x4502, 0x4602, 0x4706, 0x480E, 0x490A, 0x4A1A, 0x4B1E, 0x4C1A, 0x4D1E, 0x4E1E, 0x4F1A, 0x5006, 0x5102, 0x5202, 0x5306, 0x5402, 0x5506, 0x5606, 0x5702, 0x580A, 0x590E, 0x5A1E, 0x5B1A, 0x5C1E, 0x5D1A, 0x5E1A, 0x5F1E, 0x6026, 0x6122, 0x6222, 0x6326, 0x6422, 0x6526, 0x6626, 0x6722, 0x682A, 0x692E, 0x6A3E, 0x6B3A, 0x6C3E, 0x6D3A, 0x6E3A, 0x6F3E, 0x7022, 0x7126, 0x7226, 0x7322, 0x7426, 0x7522, 0x7622, 0x7726, 0x782E, 0x792A, 0x7A3A, 0x7B3E, 0x7C3A, 0x7D3E, 0x7E3E, 0x7F3A, 0x8082, 0x8186, 0x8286, 0x8382, 0x8486, 0x8582, 0x8682, 0x8786, 0x888E, 0x898A, 0x8A9A, 0x8B9E, 0x8C9A, 0x8D9E, 0x8E9E, 0x8F9A, 0x9086, 0x9182, 0x9282, 0x9386, 0x3423, 0x3527, 0x3627, 0x3723, 0x382B, 0x392F, 0x3A3F, 0x3B3B, 0x3C3F, 0x3D3B, 0x3E3B, 0x3F3F, 0x4003, 0x4107, 0x4207, 0x4303, 0x4407, 0x4503, 0x4603, 0x4707, 0x480F, 0x490B, 0x4A1B, 0x4B1F, 0x4C1B, 0x4D1F, 0x4E1F, 0x4F1B, 0x5007, 0x5103, 0x5203, 0x5307, 0x5403, 0x5507, 0x5607, 0x5703, 0x580B, 0x590F, 0x5A1F, 0x5B1B, 0x5C1F, 0x5D1B, 0x5E1B, 0x5F1F, 0x6027, 0x6123, 0x6223, 0x6327, 0x6423, 0x6527, 0x6627, 0x6723, 0x682B, 0x692F, 0x6A3F, 0x6B3B, 0x6C3F, 0x6D3B, 0x6E3B, 0x6F3F, 0x7023, 0x7127, 0x7227, 0x7323, 0x7427, 0x7523, 0x7623, 0x7727, 0x782F, 0x792B, 0x7A3B, 0x7B3F, 0x7C3B, 0x7D3F, 0x7E3F, 0x7F3B, 0x8083, 0x8187, 0x8287, 0x8383, 0x8487, 0x8583, 0x8683, 0x8787, 0x888F, 0x898B, 0x8A9B, 0x8B9F, 0x8C9B, 0x8D9F, 0x8E9F, 0x8F9B, 0x9087, 0x9183, 0x9283, 0x9387, 0x9483, 0x9587, 0x9687, 0x9783, 0x988B, 0x998F, 0x9A9F, 0x9B9B, 0x9C9F, 0x9D9B, 0x9E9B, 0x9F9F, 0xA0A7, 0xA1A3, 0xA2A3, 0xA3A7, 0xA4A3, 0xA5A7, 0xA6A7, 0xA7A3, 0xA8AB, 0xA9AF, 0xAABF, 0xABBB, 0xACBF, 0xADBB, 0xAEBB, 0xAFBF, 0xB0A3, 0xB1A7, 0xB2A7, 0xB3A3, 0xB4A7, 0xB5A3, 0xB6A3, 0xB7A7, 0xB8AF, 0xB9AB, 0xBABB, 0xBBBF, 0xBCBB, 0xBDBF, 0xBEBF, 0xBFBB, 0xC087, 0xC183, 0xC283, 0xC387, 0xC483, 0xC587, 0xC687, 0xC783, 0xC88B, 0xC98F, 0xCA9F, 0xCB9B, 0xCC9F, 0xCD9B, 0xCE9B, 0xCF9F, 0xD083, 0xD187, 0xD287, 0xD383, 0xD487, 0xD583, 0xD683, 0xD787, 0xD88F, 0xD98B, 0xDA9B, 0xDB9F, 0xDC9B, 0xDD9F, 0xDE9F, 0xDF9B, 0xE0A3, 0xE1A7, 0xE2A7, 0xE3A3, 0xE4A7, 0xE5A3, 0xE6A3, 0xE7A7, 0xE8AF, 0xE9AB, 0xEABB, 0xEBBF, 0xECBB, 0xEDBF, 0xEEBF, 0xEFBB, 0xF0A7, 0xF1A3, 0xF2A3, 0xF3A7, 0xF4A3, 0xF5A7, 0xF6A7, 0xF7A3, 0xF8AB, 0xF9AF, 0xFABF, 0xFBBB, 0xFCBF, 0xFDBB, 0xFEBB, 0xFFBF, 0x0047, 0x0103, 0x0203, 0x0307, 0x0403, 0x0507, 0x0607, 0x0703, 0x080B, 0x090F, 0x0A1F, 0x0B1B, 0x0C1F, 0x0D1B, 0x0E1B, 0x0F1F, 0x1003, 0x1107, 0x1207, 0x1303, 0x1407, 0x1503, 0x1603, 0x1707, 0x180F, 0x190B, 0x1A1B, 0x1B1F, 0x1C1B, 0x1D1F, 0x1E1F, 0x1F1B, 0x2023, 0x2127, 0x2227, 0x2323, 0x2427, 0x2523, 0x2623, 0x2727, 0x282F, 0x292B, 0x2A3B, 0x2B3F, 0x2C3B, 0x2D3F, 0x2E3F, 0x2F3B, 0x3027, 0x3123, 0x3223, 0x3327, 0x3423, 0x3527, 0x3627, 0x3723, 0x382B, 0x392F, 0x3A3F, 0x3B3B, 0x3C3F, 0x3D3B, 0x3E3B, 0x3F3F, 0x4003, 0x4107, 0x4207, 0x4303, 0x4407, 0x4503, 0x4603, 0x4707, 0x480F, 0x490B, 0x4A1B, 0x4B1F, 0x4C1B, 0x4D1F, 0x4E1F, 0x4F1B, 0x5007, 0x5103, 0x5203, 0x5307, 0x5403, 0x5507, 0x5607, 0x5703, 0x580B, 0x590F, 0x5A1F, 0x5B1B, 0x5C1F, 0x5D1B, 0x5E1B, 0x5F1F, 0x6027, 0x6123, 0x6223, 0x6327, 0x6423, 0x6527, 0x6627, 0x6723, 0x682B, 0x692F, 0x6A3F, 0x6B3B, 0x6C3F, 0x6D3B, 0x6E3B, 0x6F3F, 0x7023, 0x7127, 0x7227, 0x7323, 0x7427, 0x7523, 0x7623, 0x7727, 0x782F, 0x792B, 0x7A3B, 0x7B3F, 0x7C3B, 0x7D3F, 0x7E3F, 0x7F3B, 0x8083, 0x8187, 0x8287, 0x8383, 0x8487, 0x8583, 0x8683, 0x8787, 0x888F, 0x898B, 0x8A9B, 0x8B9F, 0x8C9B, 0x8D9F, 0x8E9F, 0x8F9B, 0x9087, 0x9183, 0x9283, 0x9387, 0x9483, 0x9587, 0x9687, 0x9783, 0x988B, 0x998F }; }
UTF-8
Java
109,936
java
Z80.java
Java
[ { "context": "/* Z80 cpu core - Written from scratch by Romain Tisserand */\n\n/* Bugs fixed by Ricardo Bittencourt */\n\n/* H", "end": 58, "score": 0.9998908042907715, "start": 42, "tag": "NAME", "value": "Romain Tisserand" }, { "context": "m scratch by Romain Tisserand */\n\n/* Bug...
null
[]
/* Z80 cpu core - Written from scratch by <NAME> */ /* Bugs fixed by <NAME> */ /* History : 2004-08-10 : [ricbit] Fixed RLD,RRD,ADD,ADC,SUB,SBC,OR,AND,XOR,CP 2004-08-09 : [ricbit] Fixed CPL,SBC16,ADC16,RLA,RLCA,RRCA,RRA 2002-11-19 : Fixed nasty bug involving the HALT instruction and IRQ system 2002-11-13 : 1st release This source code is part of the Javel Project */ import java.math.BigInteger; public final class Z80 implements Cpu { private int AF, BC, DE, HL, AF2, BC2, DE2, HL2, IX, IY, XY, PC, SP, IFF1, IFF2, IM, word, addr; private int I, R, vector; private int cyclesToDo; private int sliceClocks; private BigInteger totalClocks; private MC1000machine machine; int NMIInt, IRQ; private boolean intel8080 = false; private boolean running = false; private static final byte PF_Table[] = new byte[256]; private int enable; private long frequency; private boolean halted = false; private final int NMI_PC; private Ports port; private Memory mem; public void setPorts(Ports p) { this.port = p; } Z80(MC1000machine m, boolean intel8080, int startAddr) { machine=m; this.mem = machine.memory; this.port = machine.ports; this.frequency = frequency; this.intel8080 = intel8080; if (intel8080 == true) { NMI_PC = 0x10; } else { NMI_PC = 0x66; } PF_Table_init(); reset(startAddr); start(); } Z80(Memory m, Ports p, boolean intel8080, int startAddr) { this.mem = m; this.port = p; this.frequency = frequency; this.intel8080 = intel8080; if (intel8080 == true) { NMI_PC = 0x10; } else { NMI_PC = 0x66; } PF_Table_init(); reset(startAddr); start(); } public void dump() { System.out.println("PC=" + Integer.toHexString(PC)); } public final void start() { running = true; } public final void stop() { running = false; } public final void reset(int startAddr) { PC = startAddr; SP = 0xDFF0; AF = 0x0040; AF2 = BC = DE = HL = BC2 = DE2 = HL2 = 0; IRQ = NMIInt = 0; vector = 0; IM = 0; IFF1 = IFF2 = 0; I = R = 0; IX = IY = XY = 0xFFFF; enable = 0; cyclesToDo = 0; totalClocks=BigInteger.ZERO; sliceClocks=0; } private final void UpdateR() { R = ((R & 0x80) | ((R + 1) & 0x7F)); } private final void memWriteByte(int addr, int data) { mem.writeByte(addr, data); } private final int memReadByte(int addr) { return mem.readByte(addr); } private final void ioWriteByte(int p, int data) { port.out(p, data, totalClocks.add(BigInteger.valueOf(sliceClocks-cyclesToDo))); } private final int ioReadByte(int p) { return port.in(p,totalClocks.add(BigInteger.valueOf(sliceClocks-cyclesToDo))); } private final void memWriteWord(int address, int data) { memWriteByte(address, (data & 0xFF)); memWriteByte(address + 1, ((data & 0xFF00) >> 8)); } private final int memReadWord(int address) { return ((memReadByte(address)) | (memReadByte((address + 1)) << 8)); } private final void setA(int v) { AF = (AF & 0xFF) | ((v) << 8); } private final void setF(int v) { AF = (AF & 0xFF00) | (v); } private final void setB(int v) { BC = (BC & 0xFF) | ((v) << 8); } private final void setC(int v) { BC = (BC & 0xFF00) | (v); } private final void setD(int v) { DE = (DE & 0xFF) | ((v) << 8); } private final void setE(int v) { DE = (DE & 0xFF00) | (v); } private final void setH(int v) { HL = (HL & 0xFF) | ((v) << 8); } private final void setL(int v) { HL = (HL & 0xFF00) | (v); } private final void setIXL(int v) { IX = (IX & 0xFF00) | (v); } private final void setIXH(int v) { IX = (IX & 0xFF) | ((v) << 8); } private final void setIYL(int v) { IY = (IY & 0xFF00) | (v); } private final void setIYH(int v) { IY = (IY & 0xFF) | ((v) << 8); } private final void setXYL(int v) { XY = (XY & 0xFF00) | (v); } private final void setXYH(int v) { XY = (XY & 0xFF) | ((v) << 8); } private final int getA() { return (AF >> 8); } private final int getB() { return (BC >> 8); } private final int getC() { return (BC & 0xFF); } private final int getD() { return (DE >> 8); } private final int getE() { return (DE & 0xFF); } private final int getH() { return (HL >> 8); } private final int getL() { return (HL & 0xFF); } private final int getIXH() { return (IX >> 8); } private final int getIXL() { return IX & 0xFF; } private final int getIYH() { return (IY >> 8); } private final int getIYL() { return IY & 0xFF; } private final int getXYH() { return (XY >> 8); } private final int getXYL() { return XY & 0xFF; } private final void decB() { setB((getB() - 1) & 0xFF); } private final void ClearCF() { AF &= 0xFFFE; } private final void ClearNF() { AF &= 0xFFFD; } private final void ClearVF() { AF &= 0xFFFB; } private final void ClearHF() { AF &= 0xFFEF; } private final void ClearZF() { AF &= 0xFFBF; } private final void ClearSF() { AF &= 0xFF7F; } private final void SetCF() { AF |= 0x01; } private final void SetNF() { AF |= 0x02; } private final void SetVF() { AF |= 0x04; } private final void SetHF() { AF |= 0x10; } private final void SetZF() { AF |= 0x40; } private final void SetSF() { AF |= 0x80; } private final void YF_XF_FLAGS(int x) { if ((x & 0x08) != 0) { AF |= 0x08; } else { AF &= 0xFFF7; } if ((x & 0x20) != 0) { AF |= 0x20; } else { AF &= 0xFFDF; } } private final void PARI_FLAG(int x) { if (PF_Table[x & 0xFF] != 0) { SetVF(); } else { ClearVF(); } } private final void SIGN_FLAG(int value, int size) { if ((value & (1 << (size - 1))) != 0) { SetSF(); } else { ClearSF(); } } private final void ZERO_FLAG(int value) { if (value == 0) { SetZF(); } else { ClearZF(); } } private final void HC_FLAG(int v1, int v2, int v3) { if (((v1 ^ v2 ^ v3) & 0x10) != 0) { SetHF(); } else { ClearHF(); } } private final void CARRY_FLAG(long value, int size) { if ((value & (1 << size)) != 0) { SetCF(); } else { ClearCF(); } } private final void OVER_FLAG(int v1, int v2, long v3, int size) { if ((((v2 ^ v1 ^ 0x80) & (v2 ^ v3) & (1 << (size - 1))) >> 5) != 0) { SetVF(); } else { ClearVF(); } } private final void OVER_FLAG2(int v1, int v2, long v3, int size) { if ((((v2 ^ v1) & (v1 ^ v3) & (1 << (size - 1))) >> 5) != 0) { SetVF(); } else { ClearVF(); } } private final void ADD(int x) { int temp = x; int acu = (AF >> 8); int sum = acu + temp; int cbits = acu ^ temp ^ sum; AF = ((sum & 0xff) << 8) | (sum & 0xa8) | (((sum & 0xff) == 0 ? 1 : 0) << 6) | (cbits & 0x10) | (((cbits >> 6) ^ (cbits >> 5)) & 4) | ((cbits >> 8) & 1); } private final void ADC(int x) { int temp = x; int acu = (AF >> 8); int sum = acu + temp + (AF & 1); int cbits = acu ^ temp ^ sum; AF = ((sum & 0xff) << 8) | (sum & 0xa8) | (((sum & 0xff) == 0 ? 1 : 0) << 6) | (cbits & 0x10) | (((cbits >> 6) ^ (cbits >> 5)) & 4) | ((cbits >> 8) & 1); } private final void SBC(int x) { int temp = x; int acu = (AF >> 8); int sum = acu - temp - (AF & 1); int cbits = acu ^ temp ^ sum; AF = ((sum & 0xff) << 8) | (sum & 0xa8) | (((sum & 0xff) == 0 ? 1 : 0) << 6) | (cbits & 0x10) | (((cbits >> 6) ^ (cbits >> 5)) & 4) | 2 | ((cbits >> 8) & 1); } private final int INC(int x) { int val = x + 1; OVER_FLAG(x, 1, val, 8); HC_FLAG(x, 1, val); x = (val & 0xFF); SIGN_FLAG(x, 8); ZERO_FLAG(x); ClearNF(); return x; } private final int DEC(int x) { int val = x - 1; OVER_FLAG2(x, 1, val, 8); HC_FLAG(x, 1, val); x = (val & 0xFF); SIGN_FLAG(x, 8); ZERO_FLAG(x); SetNF(); return x; } private final void SUB(int v) { int temp = v; int acu = (AF >> 8); int sum = acu - temp; int cbits = acu ^ temp ^ sum; AF = ((sum & 0xff) << 8) | (sum & 0xa8) | (((sum & 0xff) == 0 ? 1 : 0) << 6) | (cbits & 0x10) | (((cbits >> 6) ^ (cbits >> 5)) & 4) | 2 | ((cbits >> 8) & 1); } private final void AND(int v) { int sum = ((AF >> 8) & v) & 0xff; AF = (sum << 8) | (sum & 0xa8) | 0x10 | ((sum == 0 ? 1 : 0) << 6) | ((PF_Table[sum & 0xff] ^ 1) << 2); } private final void XOR(int v) { int sum = ((AF >> 8) ^ v) & 0xff; AF = (sum << 8) | (sum & 0xa8) | ((sum == 0 ? 1 : 0) << 6) | ((PF_Table[sum & 0xff] ^ 1) << 2); } private final void OR(int v) { int sum = ((AF >> 8) | v) & 0xff; AF = (sum << 8) | (sum & 0xa8) | ((sum == 0 ? 1 : 0) << 6) | ((PF_Table[sum & 0xff] ^ 1) << 2); } private final void CP(int v) { int temp = v; AF = (AF & ((~0x28) & 0xFFFF)) | (temp & 0x28); int acu = (AF >> 8); int sum = acu - temp; int cbits = acu ^ temp ^ sum; AF = (AF & 0xff00) | (sum & 0x80) | (((sum & 0xff) == 0 ? 1 : 0) << 6) | (temp & 0x28) | (((cbits >> 6) ^ (cbits >> 5)) & 4) | 2 | (cbits & 0x10) | ((cbits >> 8) & 1); } private final void DAA() { int val = getA(); if ((AF & 0x01) != 0) { val |= 256; } if ((AF & 0x10) != 0) { val |= 512; } if ((AF & 0x02) != 0) { val |= 1024; } AF = DAATable2[val]; } /* fixed by ricbit */ private final void CPL() { setA(0xFF & (~getA())); SetHF(); SetNF(); YF_XF_FLAGS(getA()); } private final void EXX() { word = BC; BC = BC2; BC2 = word; word = DE; DE = DE2; DE2 = word; word = HL; HL = HL2; HL2 = word; } private final void SCF() { ClearHF(); ClearNF(); SetCF(); YF_XF_FLAGS(getA()); } private final void CCF() { ClearNF(); if ((AF & 0x01) != 0) { SetHF(); ClearCF(); } else { ClearHF(); SetCF(); } YF_XF_FLAGS(getA()); } private final void PUSH(int v) { SP -= 2; SP &= 0xFFFF; memWriteWord(SP, v & 0xFFFF); } private final int POP() { int val = memReadWord(SP); val &= 0xFFFF; SP += 2; SP &= 0xFFFF; return val; } private final void RST(int v) { PUSH(PC); PC = v; } private final void RET() { PC = memReadWord(SP); SP += 2; SP &= 0xFFFF; } private final void CALL() { SP -= 2; SP &= 0xFFFF; memWriteWord(SP, (PC + 2)); PC = memReadWord(PC); } private final void NEG() { int val = getA(); setA(0); SUB(val); } private final int ADD16(int x, int y) { ClearNF(); int val = (x) + (y); if ((((y ^ x ^ val)) & 0x1000) != 0) { SetHF(); } else { ClearHF(); } CARRY_FLAG(val, 16); YF_XF_FLAGS(val >> 8); return val & 0xFFFF; } private final void SBC_HL(int x) { HL &= 0xffff; x &= 0xffff; int sum = HL - x - (AF & 1); int cbits = (HL ^ x ^ sum) >> 8; HL = sum & 0xFFFF; AF = (AF & 0xff00) | ((sum >> 8) & 0xa8) | (((sum & 0xffff) == 0 ? 1 : 0) << 6) | (((cbits >> 6) ^ (cbits >> 5)) & 4) | (cbits & 0x10) | 2 | ((cbits >> 8) & 1); } private final void ADC_HL(int x) { HL &= 0xffff; x &= 0xffff; int sum = HL + x + (AF & 1); int cbits = (HL ^ x ^ sum) >> 8; HL = sum & 0xffff; AF = (AF & 0xff00) | ((sum >> 8) & 0xa8) | (((sum & 0xffff) == 0 ? 1 : 0) << 6) | (((cbits >> 6) ^ (cbits >> 5)) & 4) | (cbits & 0x10) | ((cbits >> 8) & 1); } private final void cbFlag(int temp, int cbits) { AF = (AF & 0xff00) | (temp & 0xa8) | (((temp & 0xff) == 0 ? 1 : 0) << 6) | ((PF_Table[temp & 0xff] ^ 1) << 2) | (cbits == 0 ? 0 : 1); } private final int RR(int x) { /* int old_x=x&0xFF; int val=old_x; val=(((val>>1))|((AF&0x01)<<7))&0xFF; ZERO_FLAG(val); SIGN_FLAG(val,8); PARI_FLAG(val); if ((old_x&0x01)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); */ int temp = (x >> 1) | ((AF & 1) << 7); int cbits = x & 1; cbFlag(temp, cbits); return temp; } private final int RL(int x) { /* int old_x=x&0xFF; int val=old_x; val=((val<<1)|(AF&0x01))&0xFF; ZERO_FLAG(val); SIGN_FLAG(val,8); PARI_FLAG(val); if ((old_x&0x80)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); */ int temp = (x << 1) | (AF & 1); int cbits = x & 0x80; cbFlag(temp, cbits); return temp; } private final int RRC(int x) { /* int old_x=x&0xFF; int val=old_x; val=((val>>1)|(val<<7))&0xFF; ZERO_FLAG(val); SIGN_FLAG(val,8); PARI_FLAG(val); if ((old_x&0x01)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); return val&0xFF; */ int temp = (x >> 1) | (x << 7); int cbits = temp & 0x80; cbFlag(temp, cbits); return temp; } private final int RLC(int x) { /* int old_x=x&0xFF; int val=old_x; val=((val<<1)|(val>>7))&0xFF; ZERO_FLAG(val); SIGN_FLAG(val,8); PARI_FLAG(val); if ((old_x&0x80)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); return val; */ int temp = (x << 1) | (x >> 7); int cbits = temp & 1; cbFlag(temp, cbits); return temp; } private final void RRA() { int temp = (AF >> 8) & 0xFF; int sum = temp >> 1; AF = ((AF & 1) << 15) | (sum << 8) | (sum & 0x28) | (AF & 0xc4) | (temp & 1); } private final void RLA() { AF = ((AF << 8) & 0x0100) | ((AF >> 7) & 0x28) | ((AF << 1) & ((~0x1ff) & 0xFFFF)) | (AF & 0xc4) | ((AF >> 15) & 1); } private final void RRCA() { int temp = (AF >> 8) & 0xFF; int sum = temp >> 1; AF = ((temp & 1) << 15) | (sum << 8) | (sum & 0x28) | (AF & 0xc4) | (temp & 1); } private final void RLCA() { AF = ((AF >> 7) & 0x0128) | ((AF << 1) & ((~0x1ff) & 0xFFFF)) | (AF & 0xc4) | ((AF >> 15) & 1); } private final void RLD() { int temp = memReadByte(HL); int acu = (AF >> 8) & 0xFF; memWriteByte(HL, ((temp & 0xf) << 4) | (acu & 0xf)); acu = (acu & 0xf0) | ((temp >> 4) & 0xf); AF = (acu << 8) | (acu & 0xa8) | (((acu & 0xff) == 0 ? 1 : 0) << 6) | ((PF_Table[acu] ^ 1) << 2) | (AF & 1); } private final void RRD() { int temp = memReadByte(HL); int acu = (AF >> 8) & 0xFF; memWriteByte(HL, ((temp >> 4) & 0xf) | ((acu & 0xf) << 4)); acu = (acu & 0xf0) | (temp & 0xf); AF = (acu << 8) | (acu & 0xa8) | (((acu & 0xff) == 0 ? 1 : 0) << 6) | ((PF_Table[acu] ^ 1) << 2) | (AF & 1); } private final int IN() { int val = ioReadByte(BC); ClearHF(); ClearNF(); SIGN_FLAG(val, 8); ZERO_FLAG(val); PARI_FLAG(val); YF_XF_FLAGS(val); return val; } private final void INI() { int byte2 = ioReadByte(BC) & 0xFF; memWriteByte(HL, byte2); HL++; HL &= 0xFFFF; decB(); SIGN_FLAG(getB(), 8); ZERO_FLAG(getB()); /* if (((((getC()+1)&0xFF)+byte2)&0x100)!=0) { SetCF(); SetHF(); } else { ClearCF(); ClearHF(); }*/ if ((byte2 & 0x80) != 0) { SetNF(); } else { ClearNF(); } } private final void IND() { int byte2 = ioReadByte(BC) & 0xFF; memWriteByte(HL, byte2); HL--; HL &= 0xFFFF; decB(); SIGN_FLAG(getB(), 8); ZERO_FLAG(getB()); /* if (((((getC()+1)&0xFF)+byte2)&0x100)!=0) { SetCF(); SetHF(); } else { ClearCF(); ClearHF(); }*/ if ((byte2 & 0x80) != 0) { SetNF(); } else { ClearNF(); } } private final void INIR() { INI(); if (getB() != 0) { PC -= 2; } } private final void INDR() { IND(); if (getB() != 0) { PC -= 2; } } private final void OUTI() { int byte2 = memReadByte(HL); ioWriteByte(BC, byte2); HL++; HL &= 0xFFFF; decB(); SIGN_FLAG(getB(), 8); ZERO_FLAG(getB()); if ((byte2 & 0x80) != 0) { SetNF(); } else { ClearNF(); } /* if (((byte2+getL())&0x100)!=0) { SetCF(); SetHF(); } else { ClearCF(); ClearHF(); }*/ } private final void OUTD() { int byte2 = memReadByte(HL); ioWriteByte(BC, byte2); HL--; HL &= 0xFFFF; decB(); SIGN_FLAG(getB(), 8); ZERO_FLAG(getB()); if ((byte2 & 0x80) != 0) { SetNF(); } else { ClearNF(); } /* if (((byte2+getL())&0x100)!=0) { SetCF(); SetHF(); } else { ClearCF(); ClearHF(); }*/ } private final void OUTDR() { OUTD(); if (getB() != 0) { PC -= 2; } } private final void OUTIR() { OUTI(); if (getB() != 0) { PC -= 2; } } private final void LDI() { ClearHF(); ClearNF(); int byte2 = memReadByte(HL) & 0xFF; memWriteByte(DE, byte2); DE++; HL++; BC--; DE &= 0xFFFF; HL &= 0xFFFF; BC &= 0xFFFF; if ((BC) != 0) { SetVF(); } else { ClearVF(); } byte2 += getA(); byte2 &= 0xFF; if ((byte2 & 0x02) != 0) { AF |= 0x20; } else { AF &= 0xFFDF; } if ((byte2 & 0x08) != 0) { AF |= 0x08; } else { AF &= 0xFFF7; } UpdateR(); } private final void LDD() { ClearHF(); ClearNF(); int byte2 = memReadByte(HL) & 0xFF; memWriteByte(DE, byte2); DE--; HL--; BC--; DE &= 0xFFFF; HL &= 0xFFFF; BC &= 0xFFFF; if ((BC) != 0) { SetVF(); } else { ClearVF(); } byte2 += getA(); byte2 &= 0xFF; if ((byte2 & 0x02) != 0) { AF |= 0x20; } else { AF &= 0xFFDF; } if ((byte2 & 0x08) != 0) { AF |= 0x08; } else { AF &= 0xFFF7; } UpdateR(); } private final void LDIR() { LDI(); if (BC != 0) { PC -= 2; } } private final void LDDR() { LDD(); if (BC != 0) { PC -= 2; } } private final void CPI() { SetNF(); int byte2 = memReadByte(HL); HL++; HL &= 0xFFFF; BC--; BC &= 0xFFFF; int val = byte2 & 0xFF; int res = getA() - val; res &= 0xFF; ZERO_FLAG(res); if (((getA() ^ res ^ val) & 0x10) != 0) { SetHF(); } else { ClearHF(); } SIGN_FLAG(res, 8); YF_XF_FLAGS((getA() - byte2 - ((AF & 0x10) >> 4))); if ((BC) != 0) { SetVF(); } else { ClearVF(); } } private final void CPD() { SetNF(); int byte2 = memReadByte(HL); HL--; HL &= 0xFFFF; BC--; BC &= 0xFFFF; int val = byte2 & 0xFF; int res = getA() - val; res &= 0xFF; ZERO_FLAG(res); if (((getA() ^ res ^ val) & 0x10) != 0) { SetHF(); } else { ClearHF(); } SIGN_FLAG(res, 8); YF_XF_FLAGS((getA() - byte2 - ((AF & 0x10) >> 4))); if ((BC) != 0) { SetVF(); } else { ClearVF(); } } private final void CPIR() { CPI(); if ((BC != 0) && ((AF & 0x40) == 0)) { PC -= 2; } } private final void CPDR() { CPD(); if ((BC != 0) && ((AF & 0x40) == 0)) { PC -= 2; } } private final void BIT(int y, int x) { if ((x & (1 << y)) != 0) { ClearZF(); ClearVF(); switch (y) { case 7: SetSF(); break; case 5: AF |= 0x20; break; case 3: AF |= 0x08; break; } } else { SetZF(); SetVF(); } ClearNF(); SetHF(); } private final int RES(int y, int x) { return (x & (~(1 << y))) & 0xFF; } private final int SET(int y, int x) { return (x | (1 << y)) & 0xFF; } private final int SRA(int x) { /* int old_x=x&0xFF; x=old_x; x=(x&0x80)|((x>>1)); x&=0xFF; ZERO_FLAG(x); SIGN_FLAG(x,8); PARI_FLAG(x); if ((old_x&0x01)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); return x; */ int temp = (x >> 1) | (x & 0x80); int cbits = x & 1; cbFlag(temp, cbits); return temp; } private final int SRL(int x) { /* int old_x=x&0xFF; x=old_x; x=(x>>1)&0xFF; ZERO_FLAG(x); SIGN_FLAG(x,8); PARI_FLAG(x); if ((old_x&0x01)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); return x; }*/ int temp = x >> 1; int cbits = x & 1; cbFlag(temp, cbits); return temp; } private final int SLA(int x) { /* int old_x=x&0xFF; x=old_x; x=(x<<1)&0xFF; ZERO_FLAG(x); SIGN_FLAG(x,8); PARI_FLAG(x); if ((old_x&0x80)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); return x; }*/ int temp = x << 1; int cbits = x & 0x80; cbFlag(temp, cbits); return temp; } private final int SLL(int x) { /* int old_x=x&0xFF; x=old_x; x=((x<<1)|0x01)&0xFF; ZERO_FLAG(x); SIGN_FLAG(x,8); PARI_FLAG(x); if ((old_x&0x80)!=0) SetCF(); else ClearCF(); ClearHF(); ClearNF(); return x; }*/ int temp = (x << 1) | 1; int cbits = x & 0x80; cbFlag(temp, cbits); return temp; } private final int LD_RES(int i, int y) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = RES(y, memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_SET(int i, int y) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = SET(y, memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_RLC(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = RLC(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_RRC(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = RRC(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_RL(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = RL(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_RR(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = RR(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_SRA(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = SRA(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_SLA(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = SLA(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_SRL(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = SRL(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final int LD_SLL(int i) { int tmp_addr = i + (byte) (memReadByte(PC++)); tmp_addr &= 0xFFFF; int byte2 = SLL(memReadByte(tmp_addr)); memWriteByte(tmp_addr, byte2); return byte2; } private final void exeOpcode(int opcode) { switch (opcode) { case 0xCB: exe_cb_opcode(memReadByte(PC++)); break; // Prefix case 0xED: exe_ed_opcode(memReadByte(PC++)); break; // Prefix case 0xDD: IX = exe_dd_opcode(IX, memReadByte(PC++)); break; // Prefix case 0xFD: IY = exe_dd_opcode(IY, memReadByte(PC++)); break; // Prefix case 0x00: break; // NOP case 0x01: BC = memReadWord(PC); PC += 2; break; // LD BC,NN case 0x02: memWriteByte(BC, getA()); break; // LD (BC),A case 0x03: BC++; BC &= 0xFFFF; break; // INC BC case 0x04: setB(INC(getB())); break; // INC B case 0x05: setB(DEC(getB())); break; // DEC B case 0x06: setB(memReadByte(PC++)); break; // LD B,N case 0x07: RLCA(); break; // RLCA case 0x08: word = AF; AF = AF2; AF2 = word; break; // EX AF,AF' case 0x09: HL = ADD16(HL, BC); break; // ADD HL,BC case 0x0A: setA(memReadByte(BC)); break; // LD A,(BC) case 0x0B: BC--; BC &= 0xFFFF; break; // DEC BC case 0x0C: setC(INC(getC())); break; // INC C case 0x0D: setC(DEC(getC())); break; // DEC C case 0x0E: setC(memReadByte(PC++)); break; // LD C,N case 0x0F: RRCA(); break; // RRCA case 0x10: decB(); if (getB() != 0) { cyclesToDo -= 3; PC += 1 + (byte) (memReadByte(PC)); } else { PC++; } break; // DJNZ (PC+dd) case 0x11: DE = memReadWord(PC); PC += 2; break; // LD DE,NN case 0x12: memWriteByte(DE, getA()); break; // LD (DE),A case 0x13: DE++; DE &= 0xFFFF; break; // INC DE case 0x14: setD(INC(getD())); break; // INC D case 0x15: setD(DEC(getD())); break; // DEC D case 0x16: setD(memReadByte(PC++)); break; // LD D,N case 0x17: RLA(); break; // RLA case 0x18: PC += 1 + (byte) (memReadByte(PC)); break; // JR e case 0x19: HL = ADD16(HL, DE); break; // ADD HL,DE case 0x1A: setA(memReadByte(DE)); break; // LD A,(DE) case 0x1B: DE--; DE &= 0xFFFF; break; // DEC DE case 0x1C: setE(INC(getE())); break; // INC E case 0x1D: setE(DEC(getE())); break; // DEC E case 0x1E: setE(memReadByte(PC++)); break; // LD E,N case 0x1F: RRA(); break; // RRA case 0x20: if ((AF & 0x40) == 0) { cyclesToDo -= 5; PC += 1 + (byte) (memReadByte(PC)); } else { PC++; } break; // JR NZ,n case 0x21: HL = memReadWord(PC); PC += 2; break; // LD HL,NN case 0x22: memWriteWord(memReadWord(PC), HL); PC += 2; break; // LD (NN),HL case 0x23: HL++; HL &= 0xFFFF; break; // INC HL case 0x24: setH(INC(getH())); break; // INC H case 0x25: setH(DEC(getH())); break; // DEC H case 0x26: setH(memReadByte(PC++)); break; // LD H,N case 0x27: DAA(); break; // DAA case 0x28: if ((AF & 0x40) != 0) { cyclesToDo -= 5; PC += 1 + (byte) (memReadByte(PC)); } else { PC++; } break; // JR Z,n case 0x29: HL = ADD16(HL, HL); break; // ADD HL,HL case 0x2A: HL = memReadWord(memReadWord(PC)); PC += 2; break; // LD HL,(NN) case 0x2B: HL--; HL &= 0xFFFF; break; // DEC HL case 0x2C: setL(INC(getL())); break; // INC L case 0x2D: setL(DEC(getL())); break; // DEC L case 0x2E: setL(memReadByte(PC++)); break; // LD L,N case 0x2F: CPL(); break; // CPL case 0x30: if ((AF & 0x01) == 0) { cyclesToDo -= 5; PC += 1 + (byte) (memReadByte(PC)); } else { PC++; } break; // JR NC,n case 0x31: SP = memReadWord(PC); PC += 2; break; // LD SP,NN case 0x32: memWriteByte(memReadWord(PC), getA()); PC += 2; break; // LD (NN),A case 0x33: SP++; SP &= 0xFFFF; break; // INC SP case 0x34: memWriteByte(HL, INC(memReadByte(HL))); break; // INC (HL) case 0x35: memWriteByte(HL, DEC(memReadByte(HL))); break; // DEC (HL) case 0x36: memWriteByte(HL, memReadByte(PC++)); break; // LD (HL),N case 0x37: SCF(); break; // SCF case 0x38: if ((AF & 0x01) != 0) { cyclesToDo -= 5; PC += 1 + (byte) (memReadByte(PC)); } else { PC++; } break; // JR C,n case 0x39: HL = ADD16(HL, SP); break; // ADD HL,SP case 0x3A: setA(memReadByte(memReadWord(PC))); PC += 2; break; // LD A,(NN) case 0x3B: SP--; SP &= 0xFFFF; break; // DEC SP case 0x3C: setA(INC(getA())); break; // INC A case 0x3D: setA(DEC(getA())); break; // DEC A case 0x3E: setA(memReadByte(PC++)); break; // LD A,N case 0x3F: CCF(); break; // CCF case 0x40: break; // LD B,B case 0x41: setB(getC()); break; // LD B,C case 0x42: setB(getD()); break; // LD B,D case 0x43: setB(getE()); break; // LD B,E case 0x44: setB(getH()); break; // LD B,H case 0x45: setB(getL()); break; // LD B,L case 0x46: setB(memReadByte(HL)); break; // LD B,(HL) case 0x47: setB(getA()); break; // LD B,A case 0x48: setC(getB()); break; // LD C,B case 0x49: break; // LD C,C case 0x4A: setC(getD()); break; // LD C,D case 0x4B: setC(getE()); break; // LD C,E case 0x4C: setC(getH()); break; // LD C,H case 0x4D: setC(getL()); break; // LD C,L case 0x4E: setC(memReadByte(HL)); break; // LD C,(HL) case 0x4F: setC(getA()); break; // LD C,A case 0x50: setD(getB()); break; // LD D,B case 0x51: setD(getC()); break; // LD D,C case 0x52: break; // LD D,D case 0x53: setD(getE()); break; // LD D,E case 0x54: setD(getH()); break; // LD D,H case 0x55: setD(getL()); break; // LD D,L case 0x56: setD(memReadByte(HL)); break; // LD D,(HL) case 0x57: setD(getA()); break; // LD D,A case 0x58: setE(getB()); break; // LD E,B case 0x59: setE(getC()); break; // LD E,C case 0x5A: setE(getD()); break; // LD E,D case 0x5B: break; // LD E,E case 0x5C: setE(getH()); break; // LD E,H case 0x5D: setE(getL()); break; // LD E,L case 0x5E: setE(memReadByte(HL)); break; // LD E,(HL) case 0x5F: setE(getA()); break; // LD E,A case 0x60: setH(getB()); break; // LD H,B case 0x61: setH(getC()); break; // LD H,C case 0x62: setH(getD()); break; // LD H,D case 0x63: setH(getE()); break; // LD H,E case 0x64: break; // LD H,H case 0x65: setH(getL()); break; // LD H,L case 0x66: setH(memReadByte(HL)); break; // LD H,(HL) case 0x67: setH(getA()); break; // LD H,A case 0x68: setL(getB()); break; // LD L,B case 0x69: setL(getC()); break; // LD L,C case 0x6A: setL(getD()); break; // LD L,D case 0x6B: setL(getE()); break; // LD L,E case 0x6C: setL(getH()); break; // LD L,H case 0x6D: break; // LD L,L case 0x6E: setL(memReadByte(HL)); break; // LD L,(HL) case 0x6F: setL(getA()); break; // LD L,A case 0x70: memWriteByte(HL, getB()); break; // LD (HL),B case 0x71: memWriteByte(HL, getC()); break; // LD (HL),C case 0x72: memWriteByte(HL, getD()); break; // LD (HL),D case 0x73: memWriteByte(HL, getE()); break; // LD (HL),E case 0x74: memWriteByte(HL, getH()); break; // LD (HL),H case 0x75: memWriteByte(HL, getL()); break; // LD (HL),L case 0x76: halted = true; break; // HALT case 0x77: memWriteByte(HL, getA()); break; // LD (HL),A case 0x78: setA(getB()); break; // LD A,B case 0x79: setA(getC()); break; // LD A,C case 0x7A: setA(getD()); break; // LD A,D case 0x7B: setA(getE()); break; // LD A,E case 0x7C: setA(getH()); break; // LD A,H case 0x7D: setA(getL()); break; // LD A,L case 0x7E: setA(memReadByte(HL)); break; // LD A,(HL) case 0x7F: break; // LD A,A case 0x80: ADD(getB()); break; // ADD A,B case 0x81: ADD(getC()); break; // ADD A,C case 0x82: ADD(getD()); break; // ADD A,D case 0x83: ADD(getE()); break; // ADD A,E case 0x84: ADD(getH()); break; // ADD A,H case 0x85: ADD(getL()); break; // ADD A,L case 0x86: ADD(memReadByte(HL)); break; // ADD (HL) case 0x87: ADD(getA()); break; // ADD A,A case 0x88: ADC(getB()); break; // ADC A,B case 0x89: ADC(getC()); break; // ADC A,C case 0x8A: ADC(getD()); break; // ADC A,D case 0x8B: ADC(getE()); break; // ADC A,E case 0x8C: ADC(getH()); break; // ADC A,H case 0x8D: ADC(getL()); break; // ADC A,L case 0x8E: ADC(memReadByte(HL)); break; // ADC (HL) case 0x8F: ADC(getA()); break; // ADC A,A case 0x90: SUB(getB()); break; // SUB B case 0x91: SUB(getC()); break; // SUB C case 0x92: SUB(getD()); break; // SUB D case 0x93: SUB(getE()); break; // SUB E case 0x94: SUB(getH()); break; // SUB H case 0x95: SUB(getL()); break; // SUB L case 0x96: SUB(memReadByte(HL)); break; // SUB (HL) case 0x97: SUB(getA()); break; // SUB A case 0x98: SBC(getB()); break; // SBC B case 0x99: SBC(getC()); break; // SBC C case 0x9A: SBC(getD()); break; // SBC D case 0x9B: SBC(getE()); break; // SBC E case 0x9C: SBC(getH()); break; // SBC H case 0x9D: SBC(getL()); break; // SBC L case 0x9E: SBC(memReadByte(HL)); break; // SBC (HL) case 0x9F: SBC(getA()); break; // SBC A case 0xA0: AND(getB()); break; // AND B case 0xA1: AND(getC()); break; // AND C case 0xA2: AND(getD()); break; // AND D case 0xA3: AND(getE()); break; // AND E case 0xA4: AND(getH()); break; // AND H case 0xA5: AND(getL()); break; // AND L case 0xA6: AND(memReadByte(HL)); break; // AND (HL) case 0xA7: AND(getA()); break; // AND A case 0xA8: XOR(getB()); break; // XOR B case 0xA9: XOR(getC()); break; // XOR C case 0xAA: XOR(getD()); break; // XOR D case 0xAB: XOR(getE()); break; // XOR E case 0xAC: XOR(getH()); break; // XOR H case 0xAD: XOR(getL()); break; // XOR L case 0xAE: XOR(memReadByte(HL)); break; // XOR (HL) case 0xAF: XOR(getA()); break; // XOR A case 0xB0: OR(getB()); break; // OR B case 0xB1: OR(getC()); break; // OR C case 0xB2: OR(getD()); break; // OR D case 0xB3: OR(getE()); break; // OR E case 0xB4: OR(getH()); break; // OR H case 0xB5: OR(getL()); break; // OR L case 0xB6: OR(memReadByte(HL)); break; // OR (HL) case 0xB7: OR(getA()); break; // OR A case 0xB8: CP(getB()); break; // CP B case 0xB9: CP(getC()); break; // CP C case 0xBA: CP(getD()); break; // CP D case 0xBB: CP(getE()); break; // CP E case 0xBC: CP(getH()); break; // CP H case 0xBD: CP(getL()); break; // CP L case 0xBE: CP(memReadByte(HL)); break; // CP (HL) case 0xBF: CP(getA()); break; // CP A case 0xC0: if ((AF & 0x40) == 0) { cyclesToDo -= 6; RET(); } break; // RET NZ case 0xC1: BC = POP(); break; // POP BC case 0xC2: if ((AF & 0x40) == 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP NZ,nn case 0xC3: PC = memReadWord(PC); break; // JP nn case 0xC4: if ((AF & 0x40) == 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL NZ,nn case 0xC5: PUSH(BC); break; // PUSH BC case 0xC6: ADD(memReadByte(PC++)); break; // ADD nn case 0xC7: RST(0x00); break; // RST 00h case 0xC8: if ((AF & 0x40) != 0) { cyclesToDo -= 6; RET(); } break; // RET Z case 0xC9: RET(); break; // RET case 0xCA: if ((AF & 0x40) != 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP Z,nn case 0xCC: if ((AF & 0x40) != 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL Z,nn case 0xCD: CALL(); break; // CALL case 0xCE: ADC(memReadByte(PC++)); break; // ADC nn case 0xCF: RST(0x08); break; // RST 08h case 0xD0: if ((AF & 0x01) == 0) { RET(); } break; // RET NC case 0xD1: DE = POP(); break; // POP DE case 0xD2: if ((AF & 0x01) == 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP NC,nn case 0xD3: ioWriteByte((getA() << 8) | memReadByte(PC++), getA()); break; // OUT (N),A case 0xD4: if ((AF & 0x01) == 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL NC,nn case 0xD5: PUSH(DE); break; // PUSH DE case 0xD6: SUB(memReadByte(PC++)); break; // SUB n case 0xD7: RST(0x10); break; // RST 10h case 0xD8: if ((AF & 0x01) != 0) { RET(); } break; // RET C case 0xD9: EXX(); break; // EXX case 0xDA: if ((AF & 0x01) != 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP C,nn case 0xDB: setA(ioReadByte((getA() << 8) | memReadByte(PC++))); break; // IN A,N case 0xDC: if ((AF & 0x01) != 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL C,nn case 0xDE: SBC(memReadByte(PC++)); break; // SBC n case 0xDF: RST(0x18); break; // RST 18h case 0xE0: if ((AF & 0x04) == 0) { cyclesToDo -= 6; RET(); } break; // RET PO case 0xE1: HL = POP(); break; // POP HL case 0xE2: if ((AF & 0x04) == 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP PO,nn case 0xE3: word = HL; HL = memReadWord(SP); memWriteWord(SP, word); break; // EX (SP),HL case 0xE4: if ((AF & 0x04) == 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL PO,nn case 0xE5: PUSH(HL); break; // PUSH HL case 0xE6: AND(memReadByte(PC++)); break; // AND n case 0xE7: RST(0x20); break; // RST 20h case 0xE8: if ((AF & 0x04) != 0) { cyclesToDo -= 6; RET(); } break; // RET PE case 0xE9: PC = HL; break; // JP HL case 0xEA: if ((AF & 0x04) != 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP PE,nn case 0xEB: word = DE; DE = HL; HL = word; break; // EX DE,HL case 0xEC: if ((AF & 0x04) != 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL PE,nn case 0xEE: XOR(memReadByte(PC++)); break; // XOR n case 0xEF: RST(0x28); break; // RST 28h case 0xF0: if ((AF & 0x80) == 0) { cyclesToDo -= 6; RET(); } break; // RET P case 0xF1: AF = POP(); break; // POP AF case 0xF2: if ((AF & 0x80) == 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP P,nn case 0xF3: IFF1 = IFF2 = 0; break; // DI case 0xF4: if ((AF & 0x80) == 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL P,nn case 0xF5: PUSH(AF); break; // PUSH AF case 0xF6: OR(memReadByte(PC++)); break; // OR n case 0xF7: RST(0x30); break; // RST 30h case 0xF8: if ((AF & 0x80) != 0) { cyclesToDo -= 6; RET(); } break; // RET M case 0xF9: SP = HL; break; // LD SP,HL case 0xFA: if ((AF & 0x80) != 0) { PC = memReadWord(PC); } else { PC += 2; } break; // JP M,nn case 0xFB: enable = 1; break; // EI case 0xFC: if ((AF & 0x80) != 0) { cyclesToDo -= 7; CALL(); } else { PC += 2; } break; // CALL M,nn case 0xFE: CP(memReadByte(PC++)); break; // CP nn case 0xFF: RST(0x38); break; // RST 38h } cyclesToDo -= cycles_main_opcode[opcode]; } private final void exe_ed_opcode(int opcode) { switch (opcode) { // CASE TABLE FOR ED OPCODES case 0x40: setB(IN()); break; // IN B,(C) case 0x41: ioWriteByte(BC, getB()); break; // OUT (C),B case 0x42: SBC_HL(BC); break; // * SBC HL,BC case 0x43: memWriteWord(memReadWord(PC), BC); PC += 2; break; // LD (NN),BC case 0x44: NEG(); break; // NEG case 0x45: IFF1 = IFF2; RET(); Interrupt(); break; // * RETN case 0x46: IM = 0; break; // * IM 0 case 0x47: I = getA(); break; // LD I,A (incomplete) case 0x48: setC(IN()); break; // IN C,(C) case 0x49: ioWriteByte(BC, getC()); break; // OUT (C),C case 0x4A: ADC_HL(BC); break; // * ADC HL,BC case 0x4B: BC = memReadWord(memReadWord(PC)); PC += 2; break; // LD BC,(NN) case 0x4C: NEG(); break; // NEG case 0x4D: IFF1 = 1; RET(); break; // * RETI case 0x4E: IM = 0; break; // IM 0 case 0x4F: R = getA(); break; // LD R,A case 0x50: setD(IN()); break; // IN D,(C) case 0x51: ioWriteByte(BC, getD()); break; // OUT (C),D case 0x52: SBC_HL(DE); break; // * SBC HL,DE case 0x53: memWriteWord(memReadWord(PC), DE); PC += 2; break; // LD (NN),DE case 0x54: NEG(); break; // NEG case 0x55: IFF1 = IFF2; RET(); Interrupt(); break; // * RETN case 0x56: IM = 1; break; // * IM 1 case 0x57: setA(I); if ((IFF2) != 0) { SetVF(); } else { ClearVF(); } SIGN_FLAG(getA(), 8); ZERO_FLAG(getA()); ClearHF(); YF_XF_FLAGS(getA()); break; // LD A,I case 0x58: setE(IN()); break; // IN E,(C) case 0x59: ioWriteByte(BC, getE()); break; // OUT (C),E case 0x5A: ADC_HL(DE); break; // ADC HL,DE case 0x5B: DE = memReadWord(memReadWord(PC)); PC += 2; break; // LD DE,(NN) case 0x5C: NEG(); break; // NEG case 0x5D: IFF1 = IFF2; RET(); Interrupt(); break; // RETN case 0x5E: IM = 2; break; // IM 2 case 0x5F: setA(R); if ((IFF2) != 0) { SetVF(); } else { ClearVF(); } SIGN_FLAG(getA(), 8); ZERO_FLAG(getA()); ClearHF(); YF_XF_FLAGS(getA()); ClearNF(); break; // LD A,R case 0x60: setH(IN()); break; // IN H,(C) case 0x61: ioWriteByte(BC, getH()); break; // OUT (C),H case 0x62: SBC_HL(HL); break; // SBC HL,HL case 0x63: memWriteWord(memReadWord(PC), HL); PC += 2; break; // LD (NN),HL case 0x64: NEG(); break; // NEG case 0x65: IFF1 = IFF2; RET(); Interrupt(); break; // RETN case 0x66: IM = 0; break; // IM 0 case 0x67: RRD(); break; // * RRD case 0x68: setL(IN()); break; // IN L,(C) case 0x69: ioWriteByte(BC, getL()); break; // OUT (C),L case 0x6A: ADC_HL(HL); break; // * ADC HL,HL case 0x6B: HL = memReadWord(memReadWord(PC)); PC += 2; break; // LD HL,(NN) case 0x6C: NEG(); break; // NEG case 0x6D: IFF1 = IFF2; RET(); Interrupt(); break; // * RETN case 0x6E: IM = 0; break; // * IM 0 case 0x6F: RLD(); break; // * RLD case 0x70: IN(); break; // IN (C) case 0x71: ioWriteByte(BC, 0); break; // OUT (C),0 case 0x72: SBC_HL(SP); break; // SBC HL,SP case 0x73: memWriteWord(memReadWord(PC), SP); PC += 2; break; // LD (NN),SP case 0x74: NEG(); break; // NEG case 0x75: IFF1 = IFF2; RET(); Interrupt(); break; // * RETN case 0x76: IM = 2; break; // * IM 2 case 0x78: setA(IN()); break; // IN A,(C) case 0x79: ioWriteByte(BC, getA()); break; // OUT (C),A case 0x7A: ADC_HL(SP); break; // * ADC HL,SP case 0x7B: SP = memReadWord(memReadWord(PC)); PC += 2; break; // LD SP,(NN) case 0x7C: NEG(); break; // NEG case 0x7D: IFF1 = IFF2; RET(); Interrupt(); break; // * RETN case 0x7E: IM = 2; break; // * IM 2 case 0xA0: LDI(); break; // LDI case 0xA1: CPI(); break; // CPI case 0xA2: INI(); break; // INI case 0xA3: OUTI(); break; // OUTI case 0xA8: LDD(); break; // LDD case 0xA9: CPD(); break; // CPD case 0xAA: IND(); break; // IND case 0xAB: OUTD(); break; // OUTD case 0xB0: LDIR(); break; // LDIR case 0xB1: CPIR(); break; // CPIR case 0xB2: INIR(); break; // INIR case 0xB3: OUTIR(); break; // OUTIR case 0xB8: LDDR(); break; // LDDR case 0xB9: CPDR(); break; // CPDR case 0xBA: INDR(); break; // INDR case 0xBB: OUTDR(); break; // OUTDR default: // Should not happen :) break; } cyclesToDo -= cycles_ed_opcode[opcode]; } private final void exe_cb_opcode(int opcode) { switch (opcode) { // CASE TABLE FOR CB OPCODES case 0x00: setB(RLC(getB())); break; case 0x01: setC(RLC(getC())); break; case 0x02: setD(RLC(getD())); break; case 0x03: setE(RLC(getE())); break; case 0x04: setH(RLC(getH())); break; case 0x05: setL(RLC(getL())); break; case 0x06: memWriteByte(HL, RLC(memReadByte(HL))); break; case 0x07: setA(RLC(getA())); break; case 0x08: setB(RRC(getB())); break; case 0x09: setC(RRC(getC())); break; case 0x0A: setD(RRC(getD())); break; case 0x0B: setE(RRC(getE())); break; case 0x0C: setH(RRC(getH())); break; case 0x0D: setL(RRC(getL())); break; case 0x0E: memWriteByte(HL, RRC(memReadByte(HL))); break; case 0x0F: setA(RRC(getA())); break; case 0x10: setB(RL(getB())); break; case 0x11: setC(RL(getC())); break; case 0x12: setD(RL(getD())); break; case 0x13: setE(RL(getE())); break; case 0x14: setH(RL(getH())); break; case 0x15: setL(RL(getL())); break; case 0x16: memWriteByte(HL, RL(memReadByte(HL))); break; case 0x17: setA(RL(getA())); break; case 0x18: setB(RR(getB())); break; case 0x19: setC(RR(getC())); break; case 0x1A: setD(RR(getD())); break; case 0x1B: setE(RR(getE())); break; case 0x1C: setH(RR(getH())); break; case 0x1D: setL(RR(getL())); break; case 0x1E: memWriteByte(HL, RR(memReadByte(HL))); break; case 0x1F: setA(RR(getA())); break; case 0x20: setB(SLA(getB())); break; case 0x21: setC(SLA(getC())); break; case 0x22: setD(SLA(getD())); break; case 0x23: setE(SLA(getE())); break; case 0x24: setH(SLA(getH())); break; case 0x25: setL(SLA(getL())); break; case 0x26: memWriteByte(HL, SLA(memReadByte(HL))); break; case 0x27: setA(SLA(getA())); break; case 0x28: setB(SRA(getB())); break; case 0x29: setC(SRA(getC())); break; case 0x2A: setD(SRA(getD())); break; case 0x2B: setE(SRA(getE())); break; case 0x2C: setH(SRA(getH())); break; case 0x2D: setL(SRA(getL())); break; case 0x2E: memWriteByte(HL, SRA(memReadByte(HL))); break; case 0x2F: setA(SRA(getA())); break; case 0x30: setB(SLL(getB())); break; case 0x31: setC(SLL(getC())); break; case 0x32: setD(SLL(getD())); break; case 0x33: setE(SLL(getE())); break; case 0x34: setH(SLL(getH())); break; case 0x35: setL(SLL(getL())); break; case 0x36: memWriteByte(HL, SLL(memReadByte(HL))); break; case 0x37: setA(SLL(getA())); break; case 0x38: setB(SRL(getB())); break; case 0x39: setC(SRL(getC())); break; case 0x3A: setD(SRL(getD())); break; case 0x3B: setE(SRL(getE())); break; case 0x3C: setH(SRL(getH())); break; case 0x3D: setL(SRL(getL())); break; case 0x3E: memWriteByte(HL, SRL(memReadByte(HL))); break; case 0x3F: setA(SRL(getA())); break; case 0x40: BIT(0, getB()); break; case 0x41: BIT(0, getC()); break; case 0x42: BIT(0, getD()); break; case 0x43: BIT(0, getE()); break; case 0x44: BIT(0, getH()); break; case 0x45: BIT(0, getL()); break; case 0x46: BIT(0, memReadByte(HL)); break; case 0x47: BIT(0, getA()); break; case 0x48: BIT(1, getB()); break; case 0x49: BIT(1, getC()); break; case 0x4A: BIT(1, getD()); break; case 0x4B: BIT(1, getE()); break; case 0x4C: BIT(1, getH()); break; case 0x4D: BIT(1, getL()); break; case 0x4E: BIT(1, memReadByte(HL)); break; case 0x4F: BIT(1, getA()); break; case 0x50: BIT(2, getB()); break; case 0x51: BIT(2, getC()); break; case 0x52: BIT(2, getD()); break; case 0x53: BIT(2, getE()); break; case 0x54: BIT(2, getH()); break; case 0x55: BIT(2, getL()); break; case 0x56: BIT(2, memReadByte(HL)); break; case 0x57: BIT(2, getA()); break; case 0x58: BIT(3, getB()); break; case 0x59: BIT(3, getC()); break; case 0x5A: BIT(3, getD()); break; case 0x5B: BIT(3, getE()); break; case 0x5C: BIT(3, getH()); break; case 0x5D: BIT(3, getL()); break; case 0x5E: BIT(3, memReadByte(HL)); break; case 0x5F: BIT(3, getA()); break; case 0x60: BIT(4, getB()); break; case 0x61: BIT(4, getC()); break; case 0x62: BIT(4, getD()); break; case 0x63: BIT(4, getE()); break; case 0x64: BIT(4, getH()); break; case 0x65: BIT(4, getL()); break; case 0x66: BIT(4, memReadByte(HL)); break; case 0x67: BIT(4, getA()); break; case 0x68: BIT(5, getB()); break; case 0x69: BIT(5, getC()); break; case 0x6A: BIT(5, getD()); break; case 0x6B: BIT(5, getE()); break; case 0x6C: BIT(5, getH()); break; case 0x6D: BIT(5, getL()); break; case 0x6E: BIT(5, memReadByte(HL)); break; case 0x6F: BIT(5, getA()); break; case 0x70: BIT(6, getB()); break; case 0x71: BIT(6, getC()); break; case 0x72: BIT(6, getD()); break; case 0x73: BIT(6, getE()); break; case 0x74: BIT(6, getH()); break; case 0x75: BIT(6, getL()); break; case 0x76: BIT(6, memReadByte(HL)); break; case 0x77: BIT(6, getA()); break; case 0x78: BIT(7, getB()); break; case 0x79: BIT(7, getC()); break; case 0x7A: BIT(7, getD()); break; case 0x7B: BIT(7, getE()); break; case 0x7C: BIT(7, getH()); break; case 0x7D: BIT(7, getL()); break; case 0x7E: BIT(7, memReadByte(HL)); break; case 0x7F: BIT(7, getA()); break; case 0x80: setB(RES(0, getB())); break; case 0x81: setC(RES(0, getC())); break; case 0x82: setD(RES(0, getD())); break; case 0x83: setE(RES(0, getE())); break; case 0x84: setH(RES(0, getH())); break; case 0x85: setL(RES(0, getL())); break; case 0x86: memWriteByte(HL, RES(0, memReadByte(HL))); break; case 0x87: setA(RES(0, getA())); break; case 0x88: setB(RES(1, getB())); break; case 0x89: setC(RES(1, getC())); break; case 0x8A: setD(RES(1, getD())); break; case 0x8B: setE(RES(1, getE())); break; case 0x8C: setH(RES(1, getH())); break; case 0x8D: setL(RES(1, getL())); break; case 0x8E: memWriteByte(HL, RES(1, memReadByte(HL))); break; case 0x8F: setA(RES(1, getA())); break; case 0x90: setB(RES(2, getB())); break; case 0x91: setC(RES(2, getC())); break; case 0x92: setD(RES(2, getD())); break; case 0x93: setE(RES(2, getE())); break; case 0x94: setH(RES(2, getH())); break; case 0x95: setL(RES(2, getL())); break; case 0x96: memWriteByte(HL, RES(2, memReadByte(HL))); break; case 0x97: setA(RES(2, getA())); break; case 0x98: setB(RES(3, getB())); break; case 0x99: setC(RES(3, getC())); break; case 0x9A: setD(RES(3, getD())); break; case 0x9B: setE(RES(3, getE())); break; case 0x9C: setH(RES(3, getH())); break; case 0x9D: setL(RES(3, getL())); break; case 0x9E: memWriteByte(HL, RES(3, memReadByte(HL))); break; case 0x9F: setA(RES(3, getA())); break; case 0xA0: setB(RES(4, getB())); break; case 0xA1: setC(RES(4, getC())); break; case 0xA2: setD(RES(4, getD())); break; case 0xA3: setE(RES(4, getE())); break; case 0xA4: setH(RES(4, getH())); break; case 0xA5: setL(RES(4, getL())); break; case 0xA6: memWriteByte(HL, RES(4, memReadByte(HL))); break; case 0xA7: setA(RES(4, getA())); break; case 0xA8: setB(RES(5, getB())); break; case 0xA9: setC(RES(5, getC())); break; case 0xAA: setD(RES(5, getD())); break; case 0xAB: setE(RES(5, getE())); break; case 0xAC: setH(RES(5, getH())); break; case 0xAD: setL(RES(5, getL())); break; case 0xAE: memWriteByte(HL, RES(5, memReadByte(HL))); break; case 0xAF: setA(RES(5, getA())); break; case 0xB0: setB(RES(6, getB())); break; case 0xB1: setC(RES(6, getC())); break; case 0xB2: setD(RES(6, getD())); break; case 0xB3: setE(RES(6, getE())); break; case 0xB4: setH(RES(6, getH())); break; case 0xB5: setL(RES(6, getL())); break; case 0xB6: memWriteByte(HL, RES(6, memReadByte(HL))); break; case 0xB7: setA(RES(6, getA())); break; case 0xB8: setB(RES(7, getB())); break; case 0xB9: setC(RES(7, getC())); break; case 0xBA: setD(RES(7, getD())); break; case 0xBB: setE(RES(7, getE())); break; case 0xBC: setH(RES(7, getH())); break; case 0xBD: setL(RES(7, getL())); break; case 0xBE: memWriteByte(HL, RES(7, memReadByte(HL))); break; case 0xBF: setA(RES(7, getA())); break; case 0xC0: setB(SET(0, getB())); break; case 0xC1: setC(SET(0, getC())); break; case 0xC2: setD(SET(0, getD())); break; case 0xC3: setE(SET(0, getE())); break; case 0xC4: setH(SET(0, getH())); break; case 0xC5: setL(SET(0, getL())); break; case 0xC6: memWriteByte(HL, SET(0, memReadByte(HL))); break; case 0xC7: setA(SET(0, getA())); break; case 0xC8: setB(SET(1, getB())); break; case 0xC9: setC(SET(1, getC())); break; case 0xCA: setD(SET(1, getD())); break; case 0xCB: setE(SET(1, getE())); break; case 0xCC: setH(SET(1, getH())); break; case 0xCD: setL(SET(1, getL())); break; case 0xCE: memWriteByte(HL, SET(1, memReadByte(HL))); break; case 0xCF: setA(SET(1, getA())); break; case 0xD0: setB(SET(2, getB())); break; case 0xD1: setC(SET(2, getC())); break; case 0xD2: setD(SET(2, getD())); break; case 0xD3: setE(SET(2, getE())); break; case 0xD4: setH(SET(2, getH())); break; case 0xD5: setL(SET(2, getL())); break; case 0xD6: memWriteByte(HL, SET(2, memReadByte(HL))); break; case 0xD7: setA(SET(2, getA())); break; case 0xD8: setB(SET(3, getB())); break; case 0xD9: setC(SET(3, getC())); break; case 0xDA: setD(SET(3, getD())); break; case 0xDB: setE(SET(3, getE())); break; case 0xDC: setH(SET(3, getH())); break; case 0xDD: setL(SET(3, getL())); break; case 0xDE: memWriteByte(HL, SET(3, memReadByte(HL))); break; case 0xDF: setA(SET(3, getA())); break; case 0xE0: setB(SET(4, getB())); break; case 0xE1: setC(SET(4, getC())); break; case 0xE2: setD(SET(4, getD())); break; case 0xE3: setE(SET(4, getE())); break; case 0xE4: setH(SET(4, getH())); break; case 0xE5: setL(SET(4, getL())); break; case 0xE6: memWriteByte(HL, SET(4, memReadByte(HL))); break; case 0xE7: setA(SET(4, getA())); break; case 0xE8: setB(SET(5, getB())); break; case 0xE9: setC(SET(5, getC())); break; case 0xEA: setD(SET(5, getD())); break; case 0xEB: setE(SET(5, getE())); break; case 0xEC: setH(SET(5, getH())); break; case 0xED: setL(SET(5, getL())); break; case 0xEE: memWriteByte(HL, SET(5, memReadByte(HL))); break; case 0xEF: setA(SET(5, getA())); break; case 0xF0: setB(SET(6, getB())); break; case 0xF1: setC(SET(6, getC())); break; case 0xF2: setD(SET(6, getD())); break; case 0xF3: setE(SET(6, getE())); break; case 0xF4: setH(SET(6, getH())); break; case 0xF5: setL(SET(6, getL())); break; case 0xF6: memWriteByte(HL, SET(6, memReadByte(HL))); break; case 0xF7: setA(SET(6, getA())); break; case 0xF8: setB(SET(7, getB())); break; case 0xF9: setC(SET(7, getC())); break; case 0xFA: setD(SET(7, getD())); break; case 0xFB: setE(SET(7, getE())); break; case 0xFC: setH(SET(7, getH())); break; case 0xFD: setL(SET(7, getL())); break; case 0xFE: memWriteByte(HL, SET(7, memReadByte(HL))); break; case 0xFF: setA(SET(7, getA())); break; } cyclesToDo -= cycles_cb_opcode[opcode]; } private final int exe_dd_opcode(int index, int opcode) { XY = index; switch (opcode) { // CASE TABLE FOR DD OPCODES case 0xCB: exe_dd_cb_opcode(memReadByte(++PC)); break; // Prefix case 0xED: exe_ed_opcode(memReadByte(PC++)); break; // Redirecting case 0xDD: IX = exe_dd_opcode(IX, memReadByte(PC++)); break; // Redirecting case 0xFD: IY = exe_dd_opcode(IY, memReadByte(PC++)); break; // Redirecting case 0x09: XY = ADD16(XY, BC); break; // ADD XY,BC case 0x19: XY = ADD16(XY, DE); break; // ADD XY,DE case 0x21: XY = memReadWord(PC); PC += 2; break; // LD XY,NN case 0x22: memWriteWord(memReadWord(PC), XY); PC += 2; break; // LD (NN),XY case 0x23: XY++; XY &= 0xFFFF; break; // INC XY case 0x24: setXYH(INC(getXYH())); break; // INC XYH case 0x25: setXYH(DEC(getXYH())); break; // DEC XYH case 0x26: setXYH(memReadByte(PC++)); break; // LD XYH,N case 0x29: XY = ADD16(XY, XY); break; // ADD XY,XY case 0x2A: XY = memReadWord(memReadWord(PC)); PC += 2; break; // LD XY,(NN) case 0x2B: XY--; XY &= 0xFFFF; break; // DEC XY case 0x2C: setXYL(INC(getXYL())); break; // INC XYL case 0x2D: setXYL(DEC(getXYL())); break; // DEC XYL case 0x2E: setXYL(memReadByte(PC++)); break; // LD XYL,N case 0x34: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, INC(memReadByte(word))); break; // INC (XY+dd) case 0x35: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, DEC(memReadByte(word))); break; // DEC (XY+dd) case 0x36: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, memReadByte(PC++)); break; // LD (XY+d),N case 0x39: XY = ADD16(XY, SP); break; // ADD XY,SP case 0x44: setB(getXYH()); break; // LD B,XYH case 0x45: setB(getXYL()); break; // LD B,XYL case 0x46: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; setB(memReadByte(word)); break; // LD B,(XY+N) case 0x4C: setC(getXYH()); break; // LD C,XYH case 0x4D: setC(getXYL()); break; // LD C,XYL case 0x4E: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; setC(memReadByte(word)); break; // LD C,(XY+N) case 0x54: setD(getXYH()); break; // LD D,XYH case 0x55: setD(getXYL()); break; // LD D,XYL case 0x56: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; setD(memReadByte(word)); break; // LD D,(XY+N) case 0x5C: setE(getXYH()); break; // LD E,XYH case 0x5D: setE(getXYL()); break; // LD E,XYL case 0x5E: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; setE(memReadByte(word)); break; // LD E,(XY+N) case 0x60: setXYH(getB()); break; // LD XYH,B case 0x61: setXYH(getC()); break; // LD XYH,C case 0x62: setXYH(getD()); break; // LD XYH,D case 0x63: setXYH(getE()); break; // LD XYH,E case 0x64: break; // LD XYH,XYH case 0x65: setXYH(getXYL()); break; // LD XYH,XYL case 0x66: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; setH(memReadByte(word)); break; // LD H,(XY+d) case 0x67: setXYH(getA()); break; // LD XYH,A case 0x68: setXYL(getB()); break; // LD XYL,B case 0x69: setXYL(getC()); break; // LD XYL,C case 0x6A: setXYL(getD()); break; // LD XYL,D case 0x6B: setXYL(getE()); break; // LD XYL,E case 0x6C: setXYL(getXYH()); break; // LD XYL,XYH case 0x6D: break; // LD XYL,XYL case 0x6E: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; setL(memReadByte(word)); break; // LD L,(XY+d) case 0x6F: setXYL(getA()); break; // LD XYL,A case 0x70: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, getB()); break; // LD (XY+d),B case 0x71: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, getC()); break; // LD (XY+d),C case 0x72: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, getD()); break; // LD (XY+d),D case 0x73: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, getE()); break; // LD (XY+d,E case 0x74: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, getH()); break; // LD (XY+d),H case 0x75: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, getL()); break; // LD (XY+d),L case 0x77: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; memWriteByte(word, getA()); break; // LD (XY+d),A case 0x7C: setA(getXYH()); break; case 0x7D: setA(getXYL()); break; case 0x7E: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; setA(memReadByte(word)); break; // LD A,(XY+d) case 0x84: ADD(getXYH()); break; // ADD A,XYH case 0x85: ADD(getXYL()); break; // ADD A,XYL case 0x86: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; ADD(memReadByte(word)); break; // ADD A,(XY+d) case 0x8C: ADC(getXYH()); break; // ADC A,XYH case 0x8D: ADC(getXYL()); break; // ADC A,XYL case 0x8E: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; ADC(memReadByte(word)); break; // ADC A,(XY+d) case 0x94: SUB(getXYH()); break; // SUB A,XYH case 0x95: SUB(getXYL()); break; // SUB A,XYL case 0x96: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; SUB(memReadByte(word)); break; // SUB A,(XY+d) case 0x9C: SBC(getXYH()); break; // SBC A,XYH case 0x9D: SBC(getXYL()); break; // SBC A,XYL case 0x9E: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; SBC(memReadByte(word)); break; // SBC A,(XY+d) case 0xA4: AND(getXYH()); break; // AND XYH case 0xA5: AND(getXYL()); break; // AND XYL case 0xA6: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; AND(memReadByte(word)); break; // AND (XY+d) case 0xAC: XOR(getXYH()); break; // XOR XYH case 0xAD: XOR(getXYL()); break; // XOR XYL case 0xAE: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; XOR(memReadByte(word)); break; // XOR (XY+d) case 0xB4: OR(getXYH()); break; // OR XYH case 0xB5: OR(getXYL()); break; // OR XYL case 0xB6: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; OR(memReadByte(word)); break; // OR (XY+d) case 0xBC: CP(getXYH()); break; // CP XYH case 0xBD: CP(getXYL()); break; // CP XYL case 0xBE: word = XY + (byte) (memReadByte(PC++)); word &= 0xFFFF; CP(memReadByte(word)); break; // CP (XY+d) case 0xE1: XY = POP(); break; // POP XY case 0xE3: word = memReadWord(SP); memWriteWord(SP, XY); XY = word; break; // EX (SP),XY case 0xE5: PUSH(XY); break; // PUSH XY case 0xE9: PC = XY; break; // JP XY case 0xF9: SP = XY; break; // LD SP,XY } cyclesToDo -= cycles_dd_opcode[opcode]; return XY; } private final void exe_dd_cb_opcode(int opcode) { PC--; switch (opcode) { // CASE TABLE FOR DD-CB OPCODES case 0x00: setB(LD_RLC(XY)); break; case 0x01: setC(LD_RLC(XY)); break; case 0x02: setD(LD_RLC(XY)); break; case 0x03: setE(LD_RLC(XY)); break; case 0x04: setH(LD_RLC(XY)); break; case 0x05: setL(LD_RLC(XY)); break; case 0x06: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RLC(memReadByte(addr))); break; case 0x07: setA(LD_RLC(XY)); break; case 0x08: setB(LD_RRC(XY)); break; case 0x09: setC(LD_RRC(XY)); break; case 0x0A: setD(LD_RRC(XY)); break; case 0x0B: setE(LD_RRC(XY)); break; case 0x0C: setH(LD_RRC(XY)); break; case 0x0D: setL(LD_RRC(XY)); break; case 0x0E: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RRC(memReadByte(addr))); break; case 0x0F: setA(LD_RRC(XY)); break; case 0x10: setB(LD_RL(XY)); break; case 0x11: setC(LD_RL(XY)); break; case 0x12: setD(LD_RL(XY)); break; case 0x13: setE(LD_RL(XY)); break; case 0x14: setH(LD_RL(XY)); break; case 0x15: setL(LD_RL(XY)); break; case 0x16: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RL(memReadByte(addr))); break; case 0x17: setA(LD_RL(XY)); break; case 0x18: setB(LD_RR(XY)); break; case 0x19: setC(LD_RR(XY)); break; case 0x1A: setD(LD_RR(XY)); break; case 0x1B: setE(LD_RR(XY)); break; case 0x1C: setH(LD_RR(XY)); break; case 0x1D: setL(LD_RR(XY)); break; case 0x1E: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RR(memReadByte(addr))); break; case 0x1F: setA(LD_RR(XY)); break; case 0x20: setB(LD_SLA(XY)); break; case 0x21: setC(LD_SLA(XY)); break; case 0x22: setD(LD_SLA(XY)); break; case 0x23: setE(LD_SLA(XY)); break; case 0x24: setH(LD_SLA(XY)); break; case 0x25: setL(LD_SLA(XY)); break; case 0x26: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SLA(memReadByte(addr))); break; case 0x27: setA(LD_SLA(XY)); break; case 0x28: setB(LD_SRA(XY)); break; case 0x29: setC(LD_SRA(XY)); break; case 0x2A: setD(LD_SRA(XY)); break; case 0x2B: setE(LD_SRA(XY)); break; case 0x2C: setH(LD_SRA(XY)); break; case 0x2D: setL(LD_SRA(XY)); break; case 0x2E: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SRA(memReadByte(addr))); break; case 0x2F: setA(LD_SRA(XY)); break; case 0x30: setB(LD_SLL(XY)); break; case 0x31: setC(LD_SLL(XY)); break; case 0x32: setD(LD_SLL(XY)); break; case 0x33: setE(LD_SLL(XY)); break; case 0x34: setH(LD_SLL(XY)); break; case 0x35: setL(LD_SLL(XY)); break; case 0x36: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SLL(memReadByte(addr))); break; case 0x37: setA(LD_SLL(XY)); break; case 0x38: setB(LD_SRL(XY)); break; case 0x39: setC(LD_SRL(XY)); break; case 0x3A: setD(LD_SRL(XY)); break; case 0x3B: setE(LD_SRL(XY)); break; case 0x3C: setH(LD_SRL(XY)); break; case 0x3D: setL(LD_SRL(XY)); break; case 0x3E: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SRL(memReadByte(addr))); break; case 0x3F: setA(LD_SRL(XY)); break; case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: BIT(0, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: BIT(1, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: BIT(2, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x58: case 0x59: case 0x5A: case 0x5B: case 0x5C: case 0x5D: case 0x5E: case 0x5F: BIT(3, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: BIT(4, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: BIT(5, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: BIT(6, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x78: case 0x79: case 0x7A: case 0x7B: case 0x7C: case 0x7D: case 0x7E: case 0x7F: BIT(7, memReadByte(XY + (byte) (memReadByte(PC++)))); break; case 0x80: setB(LD_RES(XY, 0)); break; case 0x81: setC(LD_RES(XY, 0)); break; case 0x82: setD(LD_RES(XY, 0)); break; case 0x83: setE(LD_RES(XY, 0)); break; case 0x84: setH(LD_RES(XY, 0)); break; case 0x85: setL(LD_RES(XY, 0)); break; case 0x86: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(0, memReadByte(addr))); break; case 0x87: setA(LD_RES(XY, 0)); break; case 0x88: setB(LD_RES(XY, 1)); break; case 0x89: setC(LD_RES(XY, 1)); break; case 0x8A: setD(LD_RES(XY, 1)); break; case 0x8B: setE(LD_RES(XY, 1)); break; case 0x8C: setH(LD_RES(XY, 1)); break; case 0x8D: setL(LD_RES(XY, 1)); break; case 0x8E: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(1, memReadByte(addr))); break; case 0x8F: setA(LD_RES(XY, 1)); break; case 0x90: setB(LD_RES(XY, 2)); break; case 0x91: setC(LD_RES(XY, 2)); break; case 0x92: setD(LD_RES(XY, 2)); break; case 0x93: setE(LD_RES(XY, 2)); break; case 0x94: setH(LD_RES(XY, 2)); break; case 0x95: setL(LD_RES(XY, 2)); break; case 0x96: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(2, memReadByte(addr))); break; case 0x97: setA(LD_RES(XY, 2)); break; case 0x98: setB(LD_RES(XY, 3)); break; case 0x99: setC(LD_RES(XY, 3)); break; case 0x9A: setD(LD_RES(XY, 3)); break; case 0x9B: setE(LD_RES(XY, 3)); break; case 0x9C: setH(LD_RES(XY, 3)); break; case 0x9D: setL(LD_RES(XY, 3)); break; case 0x9E: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(3, memReadByte(addr))); break; case 0x9F: setA(LD_RES(XY, 3)); break; case 0xA0: setB(LD_RES(XY, 4)); break; case 0xA1: setC(LD_RES(XY, 4)); break; case 0xA2: setD(LD_RES(XY, 4)); break; case 0xA3: setE(LD_RES(XY, 4)); break; case 0xA4: setH(LD_RES(XY, 4)); break; case 0xA5: setL(LD_RES(XY, 4)); break; case 0xA6: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(4, memReadByte(addr))); break; case 0xA7: setA(LD_RES(XY, 4)); break; case 0xA8: setB(LD_RES(XY, 5)); break; case 0xA9: setC(LD_RES(XY, 5)); break; case 0xAA: setD(LD_RES(XY, 5)); break; case 0xAB: setE(LD_RES(XY, 5)); break; case 0xAC: setH(LD_RES(XY, 5)); break; case 0xAD: setL(LD_RES(XY, 5)); break; case 0xAE: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(5, memReadByte(addr))); break; case 0xAF: setA(LD_RES(XY, 5)); break; case 0xB0: setB(LD_RES(XY, 6)); break; case 0xB1: setC(LD_RES(XY, 6)); break; case 0xB2: setD(LD_RES(XY, 6)); break; case 0xB3: setE(LD_RES(XY, 6)); break; case 0xB4: setH(LD_RES(XY, 6)); break; case 0xB5: setL(LD_RES(XY, 6)); break; case 0xB6: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(6, memReadByte(addr))); break; case 0xB7: setA(LD_RES(XY, 6)); break; case 0xB8: setB(LD_RES(XY, 7)); break; case 0xB9: setC(LD_RES(XY, 7)); break; case 0xBA: setD(LD_RES(XY, 7)); break; case 0xBB: setE(LD_RES(XY, 7)); break; case 0xBC: setH(LD_RES(XY, 7)); break; case 0xBD: setL(LD_RES(XY, 7)); break; case 0xBE: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, RES(7, memReadByte(addr))); break; case 0xBF: setA(LD_RES(XY, 7)); break; case 0xC0: setB(LD_SET(XY, 0)); break; case 0xC1: setC(LD_SET(XY, 0)); break; case 0xC2: setD(LD_SET(XY, 0)); break; case 0xC3: setE(LD_SET(XY, 0)); break; case 0xC4: setH(LD_SET(XY, 0)); break; case 0xC5: setL(LD_SET(XY, 0)); break; case 0xC6: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(0, memReadByte(addr))); break; case 0xC7: setA(LD_SET(XY, 0)); break; case 0xC8: setB(LD_SET(XY, 1)); break; case 0xC9: setC(LD_SET(XY, 1)); break; case 0xCA: setD(LD_SET(XY, 1)); break; case 0xCB: setE(LD_SET(XY, 1)); break; case 0xCC: setH(LD_SET(XY, 1)); break; case 0xCD: setL(LD_SET(XY, 1)); break; case 0xCE: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(1, memReadByte(addr))); break; case 0xCF: setA(LD_SET(XY, 1)); break; case 0xD0: setB(LD_SET(XY, 2)); break; case 0xD1: setC(LD_SET(XY, 2)); break; case 0xD2: setD(LD_SET(XY, 2)); break; case 0xD3: setE(LD_SET(XY, 2)); break; case 0xD4: setH(LD_SET(XY, 2)); break; case 0xD5: setL(LD_SET(XY, 2)); break; case 0xD6: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(2, memReadByte(addr))); break; case 0xD7: setA(LD_SET(XY, 2)); break; case 0xD8: setB(LD_SET(XY, 3)); break; case 0xD9: setC(LD_SET(XY, 3)); break; case 0xDA: setD(LD_SET(XY, 3)); break; case 0xDB: setE(LD_SET(XY, 3)); break; case 0xDC: setH(LD_SET(XY, 3)); break; case 0xDD: setL(LD_SET(XY, 3)); break; case 0xDE: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(3, memReadByte(addr))); break; case 0xDF: setA(LD_SET(XY, 3)); break; case 0xE0: setB(LD_SET(XY, 4)); break; case 0xE1: setC(LD_SET(XY, 4)); break; case 0xE2: setD(LD_SET(XY, 4)); break; case 0xE3: setE(LD_SET(XY, 4)); break; case 0xE4: setH(LD_SET(XY, 4)); break; case 0xE5: setL(LD_SET(XY, 4)); break; case 0xE6: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(4, memReadByte(addr))); break; case 0xE7: setA(LD_SET(XY, 4)); break; case 0xE8: setB(LD_SET(XY, 5)); break; case 0xE9: setC(LD_SET(XY, 5)); break; case 0xEA: setD(LD_SET(XY, 5)); break; case 0xEB: setE(LD_SET(XY, 5)); break; case 0xEC: setH(LD_SET(XY, 5)); break; case 0xED: setL(LD_SET(XY, 5)); break; case 0xEE: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(5, memReadByte(addr))); break; case 0xEF: setA(LD_SET(XY, 5)); break; case 0xF0: setB(LD_SET(XY, 6)); break; case 0xF1: setC(LD_SET(XY, 6)); break; case 0xF2: setD(LD_SET(XY, 6)); break; case 0xF3: setE(LD_SET(XY, 6)); break; case 0xF4: setH(LD_SET(XY, 6)); break; case 0xF5: setL(LD_SET(XY, 6)); break; case 0xF6: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(6, memReadByte(addr))); break; case 0xF7: setA(LD_SET(XY, 6)); break; case 0xF8: setB(LD_SET(XY, 7)); break; case 0xF9: setC(LD_SET(XY, 7)); break; case 0xFA: setD(LD_SET(XY, 7)); break; case 0xFB: setE(LD_SET(XY, 7)); break; case 0xFC: setH(LD_SET(XY, 7)); break; case 0xFD: setL(LD_SET(XY, 7)); break; case 0xFE: addr = XY + (byte) (memReadByte(PC++)); addr &= 0xFFFF; memWriteByte(addr, SET(7, memReadByte(addr))); break; case 0xFF: setA(LD_SET(XY, 7)); break; } PC++; cyclesToDo -= cycles_xx_cb_opcode[opcode]; } public final void run(int nbCycles) { totalClocks=totalClocks.add(BigInteger.valueOf(sliceClocks-cyclesToDo)); sliceClocks=nbCycles; cyclesToDo += nbCycles; Interrupt(); while (cyclesToDo > 0) { UpdateR(); // Accepts interrupts the intruction AFTER EI switch (enable) { case 2: IFF1 = IFF2 = 1; Interrupt(); enable = 0; break; case 1: enable = 2; break; } if (halted == false) { exeOpcode(memReadByte(PC++)); PC &= 0xFFFF; } else { cyclesToDo -= 4; Interrupt(); } } } public final void PendingIRQ(int value) { vector = value; IRQ = 1; if (IFF1 != 0) { CheckIRQ(); } } public final void PendingNMI() { NMIInt = 1; } public final void CheckIRQ() { if ((IFF1 == 0) || (IRQ == 0)) { return; } IRQ = IFF1 = IFF2 = 0; halted = false; UpdateR(); switch (IM) { // 8080 compatible mode case 0: exeOpcode(vector); break; // RST 38h case 1: SP -= 2; SP &= 0xFFFF; memWriteWord(SP, PC); PC = 0x0038; cyclesToDo -= 13; break; // CALL (address I*256+(value read on the bus)) case 2: SP -= 2; SP &= 0xFFFF; memWriteWord(SP, PC); PC = memReadWord(((I) << 8) + vector); cyclesToDo -= 19; break; } } private final void PF_Table_init() { int c; byte d; int m; for (c = 0; c <= 255; c++) { d = 0; for (m = 0; m <= 7; m++) { if ((c & (1 << m)) != 0) { d ^= 1; } } PF_Table[c] = d; } } public final void NMI() { NMIInt = IFF1 = 0; // Disable interrupts and ack the interrupt halted = false; // Unhalt the CPU SP -= 2; SP &= 0xFFFF; memWriteWord(SP, PC); PC = NMI_PC; // NMI ! } public final void Interrupt() { if (NMIInt != 0) { NMI(); cyclesToDo -= 11; return; } if ((IFF1 != 0) && (IRQ != 0)) { CheckIRQ(); cyclesToDo += 19; return; } } private static final int cycles_main_opcode[] = { 4, 10, 7, 6, 4, 4, 7, 4, 4, 11, 7, 6, 4, 4, 7, 4, 10, 10, 7, 6, 4, 4, 7, 4, 12, 11, 7, 6, 4, 4, 7, 4, 7, 10, 16, 6, 4, 4, 7, 4, 7, 11, 16, 6, 4, 4, 7, 4, 7, 10, 13, 6, 11, 11, 10, 4, 7, 11, 13, 6, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 7, 7, 7, 7, 7, 7, 4, 7, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 5, 10, 10, 10, 10, 11, 7, 11, 5, 10, 10, 0, 10, 17, 7, 11, 5, 10, 10, 11, 10, 11, 7, 11, 5, 4, 10, 11, 10, 0, 7, 11, 5, 10, 10, 19, 10, 11, 7, 11, 5, 4, 10, 4, 10, 0, 7, 11, 5, 10, 10, 4, 10, 11, 7, 11, 5, 6, 10, 4, 10, 0, 7, 11 }; private static final int cycles_ed_opcode[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 12, 15, 20, 8, 8, 8, 9, 12, 12, 15, 20, 8, 8, 8, 9, 12, 12, 15, 20, 8, 8, 8, 9, 12, 12, 15, 20, 8, 8, 8, 9, 12, 12, 15, 20, 8, 8, 8, 18, 12, 12, 15, 20, 8, 8, 8, 18, 12, 12, 15, 20, 8, 8, 8, 8, 12, 12, 15, 20, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 8, 8, 8, 8, 16, 16, 16, 16, 8, 8, 8, 8, 16, 16, 16, 16, 8, 8, 8, 8, 16, 16, 16, 16, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; private static final int cycles_dd_opcode[] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 15, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 15, 4, 4, 4, 4, 4, 4, 4, 14, 20, 10, 8, 8, 11, 4, 4, 15, 20, 10, 8, 8, 11, 4, 4, 4, 4, 4, 23, 23, 19, 4, 4, 15, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8, 8, 8, 8, 8, 19, 8, 19, 19, 19, 19, 19, 19, 4, 19, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, }; private static final int cycles_cb_opcode[] = { 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, }; private static final int cycles_xx_cb_opcode[] = { 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, }; private static final int DAATable2[] = { 0x0044, 0x0100, 0x0200, 0x0304, 0x0400, 0x0504, 0x0604, 0x0700, 0x0808, 0x090C, 0x1010, 0x1114, 0x1214, 0x1310, 0x1414, 0x1510, 0x1000, 0x1104, 0x1204, 0x1300, 0x1404, 0x1500, 0x1600, 0x1704, 0x180C, 0x1908, 0x2030, 0x2134, 0x2234, 0x2330, 0x2434, 0x2530, 0x2020, 0x2124, 0x2224, 0x2320, 0x2424, 0x2520, 0x2620, 0x2724, 0x282C, 0x2928, 0x3034, 0x3130, 0x3230, 0x3334, 0x3430, 0x3534, 0x3024, 0x3120, 0x3220, 0x3324, 0x3420, 0x3524, 0x3624, 0x3720, 0x3828, 0x392C, 0x4010, 0x4114, 0x4214, 0x4310, 0x4414, 0x4510, 0x4000, 0x4104, 0x4204, 0x4300, 0x4404, 0x4500, 0x4600, 0x4704, 0x480C, 0x4908, 0x5014, 0x5110, 0x5210, 0x5314, 0x5410, 0x5514, 0x5004, 0x5100, 0x5200, 0x5304, 0x5400, 0x5504, 0x5604, 0x5700, 0x5808, 0x590C, 0x6034, 0x6130, 0x6230, 0x6334, 0x6430, 0x6534, 0x6024, 0x6120, 0x6220, 0x6324, 0x6420, 0x6524, 0x6624, 0x6720, 0x6828, 0x692C, 0x7030, 0x7134, 0x7234, 0x7330, 0x7434, 0x7530, 0x7020, 0x7124, 0x7224, 0x7320, 0x7424, 0x7520, 0x7620, 0x7724, 0x782C, 0x7928, 0x8090, 0x8194, 0x8294, 0x8390, 0x8494, 0x8590, 0x8080, 0x8184, 0x8284, 0x8380, 0x8484, 0x8580, 0x8680, 0x8784, 0x888C, 0x8988, 0x9094, 0x9190, 0x9290, 0x9394, 0x9490, 0x9594, 0x9084, 0x9180, 0x9280, 0x9384, 0x9480, 0x9584, 0x9684, 0x9780, 0x9888, 0x998C, 0x0055, 0x0111, 0x0211, 0x0315, 0x0411, 0x0515, 0x0045, 0x0101, 0x0201, 0x0305, 0x0401, 0x0505, 0x0605, 0x0701, 0x0809, 0x090D, 0x1011, 0x1115, 0x1215, 0x1311, 0x1415, 0x1511, 0x1001, 0x1105, 0x1205, 0x1301, 0x1405, 0x1501, 0x1601, 0x1705, 0x180D, 0x1909, 0x2031, 0x2135, 0x2235, 0x2331, 0x2435, 0x2531, 0x2021, 0x2125, 0x2225, 0x2321, 0x2425, 0x2521, 0x2621, 0x2725, 0x282D, 0x2929, 0x3035, 0x3131, 0x3231, 0x3335, 0x3431, 0x3535, 0x3025, 0x3121, 0x3221, 0x3325, 0x3421, 0x3525, 0x3625, 0x3721, 0x3829, 0x392D, 0x4011, 0x4115, 0x4215, 0x4311, 0x4415, 0x4511, 0x4001, 0x4105, 0x4205, 0x4301, 0x4405, 0x4501, 0x4601, 0x4705, 0x480D, 0x4909, 0x5015, 0x5111, 0x5211, 0x5315, 0x5411, 0x5515, 0x5005, 0x5101, 0x5201, 0x5305, 0x5401, 0x5505, 0x5605, 0x5701, 0x5809, 0x590D, 0x6035, 0x6131, 0x6231, 0x6335, 0x6431, 0x6535, 0x6025, 0x6121, 0x6221, 0x6325, 0x6421, 0x6525, 0x6625, 0x6721, 0x6829, 0x692D, 0x7031, 0x7135, 0x7235, 0x7331, 0x7435, 0x7531, 0x7021, 0x7125, 0x7225, 0x7321, 0x7425, 0x7521, 0x7621, 0x7725, 0x782D, 0x7929, 0x8091, 0x8195, 0x8295, 0x8391, 0x8495, 0x8591, 0x8081, 0x8185, 0x8285, 0x8381, 0x8485, 0x8581, 0x8681, 0x8785, 0x888D, 0x8989, 0x9095, 0x9191, 0x9291, 0x9395, 0x9491, 0x9595, 0x9085, 0x9181, 0x9281, 0x9385, 0x9481, 0x9585, 0x9685, 0x9781, 0x9889, 0x998D, 0xA0B5, 0xA1B1, 0xA2B1, 0xA3B5, 0xA4B1, 0xA5B5, 0xA0A5, 0xA1A1, 0xA2A1, 0xA3A5, 0xA4A1, 0xA5A5, 0xA6A5, 0xA7A1, 0xA8A9, 0xA9AD, 0xB0B1, 0xB1B5, 0xB2B5, 0xB3B1, 0xB4B5, 0xB5B1, 0xB0A1, 0xB1A5, 0xB2A5, 0xB3A1, 0xB4A5, 0xB5A1, 0xB6A1, 0xB7A5, 0xB8AD, 0xB9A9, 0xC095, 0xC191, 0xC291, 0xC395, 0xC491, 0xC595, 0xC085, 0xC181, 0xC281, 0xC385, 0xC481, 0xC585, 0xC685, 0xC781, 0xC889, 0xC98D, 0xD091, 0xD195, 0xD295, 0xD391, 0xD495, 0xD591, 0xD081, 0xD185, 0xD285, 0xD381, 0xD485, 0xD581, 0xD681, 0xD785, 0xD88D, 0xD989, 0xE0B1, 0xE1B5, 0xE2B5, 0xE3B1, 0xE4B5, 0xE5B1, 0xE0A1, 0xE1A5, 0xE2A5, 0xE3A1, 0xE4A5, 0xE5A1, 0xE6A1, 0xE7A5, 0xE8AD, 0xE9A9, 0xF0B5, 0xF1B1, 0xF2B1, 0xF3B5, 0xF4B1, 0xF5B5, 0xF0A5, 0xF1A1, 0xF2A1, 0xF3A5, 0xF4A1, 0xF5A5, 0xF6A5, 0xF7A1, 0xF8A9, 0xF9AD, 0x0055, 0x0111, 0x0211, 0x0315, 0x0411, 0x0515, 0x0045, 0x0101, 0x0201, 0x0305, 0x0401, 0x0505, 0x0605, 0x0701, 0x0809, 0x090D, 0x1011, 0x1115, 0x1215, 0x1311, 0x1415, 0x1511, 0x1001, 0x1105, 0x1205, 0x1301, 0x1405, 0x1501, 0x1601, 0x1705, 0x180D, 0x1909, 0x2031, 0x2135, 0x2235, 0x2331, 0x2435, 0x2531, 0x2021, 0x2125, 0x2225, 0x2321, 0x2425, 0x2521, 0x2621, 0x2725, 0x282D, 0x2929, 0x3035, 0x3131, 0x3231, 0x3335, 0x3431, 0x3535, 0x3025, 0x3121, 0x3221, 0x3325, 0x3421, 0x3525, 0x3625, 0x3721, 0x3829, 0x392D, 0x4011, 0x4115, 0x4215, 0x4311, 0x4415, 0x4511, 0x4001, 0x4105, 0x4205, 0x4301, 0x4405, 0x4501, 0x4601, 0x4705, 0x480D, 0x4909, 0x5015, 0x5111, 0x5211, 0x5315, 0x5411, 0x5515, 0x5005, 0x5101, 0x5201, 0x5305, 0x5401, 0x5505, 0x5605, 0x5701, 0x5809, 0x590D, 0x6035, 0x6131, 0x6231, 0x6335, 0x6431, 0x6535, 0x0604, 0x0700, 0x0808, 0x090C, 0x0A0C, 0x0B08, 0x0C0C, 0x0D08, 0x0E08, 0x0F0C, 0x1010, 0x1114, 0x1214, 0x1310, 0x1414, 0x1510, 0x1600, 0x1704, 0x180C, 0x1908, 0x1A08, 0x1B0C, 0x1C08, 0x1D0C, 0x1E0C, 0x1F08, 0x2030, 0x2134, 0x2234, 0x2330, 0x2434, 0x2530, 0x2620, 0x2724, 0x282C, 0x2928, 0x2A28, 0x2B2C, 0x2C28, 0x2D2C, 0x2E2C, 0x2F28, 0x3034, 0x3130, 0x3230, 0x3334, 0x3430, 0x3534, 0x3624, 0x3720, 0x3828, 0x392C, 0x3A2C, 0x3B28, 0x3C2C, 0x3D28, 0x3E28, 0x3F2C, 0x4010, 0x4114, 0x4214, 0x4310, 0x4414, 0x4510, 0x4600, 0x4704, 0x480C, 0x4908, 0x4A08, 0x4B0C, 0x4C08, 0x4D0C, 0x4E0C, 0x4F08, 0x5014, 0x5110, 0x5210, 0x5314, 0x5410, 0x5514, 0x5604, 0x5700, 0x5808, 0x590C, 0x5A0C, 0x5B08, 0x5C0C, 0x5D08, 0x5E08, 0x5F0C, 0x6034, 0x6130, 0x6230, 0x6334, 0x6430, 0x6534, 0x6624, 0x6720, 0x6828, 0x692C, 0x6A2C, 0x6B28, 0x6C2C, 0x6D28, 0x6E28, 0x6F2C, 0x7030, 0x7134, 0x7234, 0x7330, 0x7434, 0x7530, 0x7620, 0x7724, 0x782C, 0x7928, 0x7A28, 0x7B2C, 0x7C28, 0x7D2C, 0x7E2C, 0x7F28, 0x8090, 0x8194, 0x8294, 0x8390, 0x8494, 0x8590, 0x8680, 0x8784, 0x888C, 0x8988, 0x8A88, 0x8B8C, 0x8C88, 0x8D8C, 0x8E8C, 0x8F88, 0x9094, 0x9190, 0x9290, 0x9394, 0x9490, 0x9594, 0x9684, 0x9780, 0x9888, 0x998C, 0x9A8C, 0x9B88, 0x9C8C, 0x9D88, 0x9E88, 0x9F8C, 0x0055, 0x0111, 0x0211, 0x0315, 0x0411, 0x0515, 0x0605, 0x0701, 0x0809, 0x090D, 0x0A0D, 0x0B09, 0x0C0D, 0x0D09, 0x0E09, 0x0F0D, 0x1011, 0x1115, 0x1215, 0x1311, 0x1415, 0x1511, 0x1601, 0x1705, 0x180D, 0x1909, 0x1A09, 0x1B0D, 0x1C09, 0x1D0D, 0x1E0D, 0x1F09, 0x2031, 0x2135, 0x2235, 0x2331, 0x2435, 0x2531, 0x2621, 0x2725, 0x282D, 0x2929, 0x2A29, 0x2B2D, 0x2C29, 0x2D2D, 0x2E2D, 0x2F29, 0x3035, 0x3131, 0x3231, 0x3335, 0x3431, 0x3535, 0x3625, 0x3721, 0x3829, 0x392D, 0x3A2D, 0x3B29, 0x3C2D, 0x3D29, 0x3E29, 0x3F2D, 0x4011, 0x4115, 0x4215, 0x4311, 0x4415, 0x4511, 0x4601, 0x4705, 0x480D, 0x4909, 0x4A09, 0x4B0D, 0x4C09, 0x4D0D, 0x4E0D, 0x4F09, 0x5015, 0x5111, 0x5211, 0x5315, 0x5411, 0x5515, 0x5605, 0x5701, 0x5809, 0x590D, 0x5A0D, 0x5B09, 0x5C0D, 0x5D09, 0x5E09, 0x5F0D, 0x6035, 0x6131, 0x6231, 0x6335, 0x6431, 0x6535, 0x6625, 0x6721, 0x6829, 0x692D, 0x6A2D, 0x6B29, 0x6C2D, 0x6D29, 0x6E29, 0x6F2D, 0x7031, 0x7135, 0x7235, 0x7331, 0x7435, 0x7531, 0x7621, 0x7725, 0x782D, 0x7929, 0x7A29, 0x7B2D, 0x7C29, 0x7D2D, 0x7E2D, 0x7F29, 0x8091, 0x8195, 0x8295, 0x8391, 0x8495, 0x8591, 0x8681, 0x8785, 0x888D, 0x8989, 0x8A89, 0x8B8D, 0x8C89, 0x8D8D, 0x8E8D, 0x8F89, 0x9095, 0x9191, 0x9291, 0x9395, 0x9491, 0x9595, 0x9685, 0x9781, 0x9889, 0x998D, 0x9A8D, 0x9B89, 0x9C8D, 0x9D89, 0x9E89, 0x9F8D, 0xA0B5, 0xA1B1, 0xA2B1, 0xA3B5, 0xA4B1, 0xA5B5, 0xA6A5, 0xA7A1, 0xA8A9, 0xA9AD, 0xAAAD, 0xABA9, 0xACAD, 0xADA9, 0xAEA9, 0xAFAD, 0xB0B1, 0xB1B5, 0xB2B5, 0xB3B1, 0xB4B5, 0xB5B1, 0xB6A1, 0xB7A5, 0xB8AD, 0xB9A9, 0xBAA9, 0xBBAD, 0xBCA9, 0xBDAD, 0xBEAD, 0xBFA9, 0xC095, 0xC191, 0xC291, 0xC395, 0xC491, 0xC595, 0xC685, 0xC781, 0xC889, 0xC98D, 0xCA8D, 0xCB89, 0xCC8D, 0xCD89, 0xCE89, 0xCF8D, 0xD091, 0xD195, 0xD295, 0xD391, 0xD495, 0xD591, 0xD681, 0xD785, 0xD88D, 0xD989, 0xDA89, 0xDB8D, 0xDC89, 0xDD8D, 0xDE8D, 0xDF89, 0xE0B1, 0xE1B5, 0xE2B5, 0xE3B1, 0xE4B5, 0xE5B1, 0xE6A1, 0xE7A5, 0xE8AD, 0xE9A9, 0xEAA9, 0xEBAD, 0xECA9, 0xEDAD, 0xEEAD, 0xEFA9, 0xF0B5, 0xF1B1, 0xF2B1, 0xF3B5, 0xF4B1, 0xF5B5, 0xF6A5, 0xF7A1, 0xF8A9, 0xF9AD, 0xFAAD, 0xFBA9, 0xFCAD, 0xFDA9, 0xFEA9, 0xFFAD, 0x0055, 0x0111, 0x0211, 0x0315, 0x0411, 0x0515, 0x0605, 0x0701, 0x0809, 0x090D, 0x0A0D, 0x0B09, 0x0C0D, 0x0D09, 0x0E09, 0x0F0D, 0x1011, 0x1115, 0x1215, 0x1311, 0x1415, 0x1511, 0x1601, 0x1705, 0x180D, 0x1909, 0x1A09, 0x1B0D, 0x1C09, 0x1D0D, 0x1E0D, 0x1F09, 0x2031, 0x2135, 0x2235, 0x2331, 0x2435, 0x2531, 0x2621, 0x2725, 0x282D, 0x2929, 0x2A29, 0x2B2D, 0x2C29, 0x2D2D, 0x2E2D, 0x2F29, 0x3035, 0x3131, 0x3231, 0x3335, 0x3431, 0x3535, 0x3625, 0x3721, 0x3829, 0x392D, 0x3A2D, 0x3B29, 0x3C2D, 0x3D29, 0x3E29, 0x3F2D, 0x4011, 0x4115, 0x4215, 0x4311, 0x4415, 0x4511, 0x4601, 0x4705, 0x480D, 0x4909, 0x4A09, 0x4B0D, 0x4C09, 0x4D0D, 0x4E0D, 0x4F09, 0x5015, 0x5111, 0x5211, 0x5315, 0x5411, 0x5515, 0x5605, 0x5701, 0x5809, 0x590D, 0x5A0D, 0x5B09, 0x5C0D, 0x5D09, 0x5E09, 0x5F0D, 0x6035, 0x6131, 0x6231, 0x6335, 0x6431, 0x6535, 0x0046, 0x0102, 0x0202, 0x0306, 0x0402, 0x0506, 0x0606, 0x0702, 0x080A, 0x090E, 0x0402, 0x0506, 0x0606, 0x0702, 0x080A, 0x090E, 0x1002, 0x1106, 0x1206, 0x1302, 0x1406, 0x1502, 0x1602, 0x1706, 0x180E, 0x190A, 0x1406, 0x1502, 0x1602, 0x1706, 0x180E, 0x190A, 0x2022, 0x2126, 0x2226, 0x2322, 0x2426, 0x2522, 0x2622, 0x2726, 0x282E, 0x292A, 0x2426, 0x2522, 0x2622, 0x2726, 0x282E, 0x292A, 0x3026, 0x3122, 0x3222, 0x3326, 0x3422, 0x3526, 0x3626, 0x3722, 0x382A, 0x392E, 0x3422, 0x3526, 0x3626, 0x3722, 0x382A, 0x392E, 0x4002, 0x4106, 0x4206, 0x4302, 0x4406, 0x4502, 0x4602, 0x4706, 0x480E, 0x490A, 0x4406, 0x4502, 0x4602, 0x4706, 0x480E, 0x490A, 0x5006, 0x5102, 0x5202, 0x5306, 0x5402, 0x5506, 0x5606, 0x5702, 0x580A, 0x590E, 0x5402, 0x5506, 0x5606, 0x5702, 0x580A, 0x590E, 0x6026, 0x6122, 0x6222, 0x6326, 0x6422, 0x6526, 0x6626, 0x6722, 0x682A, 0x692E, 0x6422, 0x6526, 0x6626, 0x6722, 0x682A, 0x692E, 0x7022, 0x7126, 0x7226, 0x7322, 0x7426, 0x7522, 0x7622, 0x7726, 0x782E, 0x792A, 0x7426, 0x7522, 0x7622, 0x7726, 0x782E, 0x792A, 0x8082, 0x8186, 0x8286, 0x8382, 0x8486, 0x8582, 0x8682, 0x8786, 0x888E, 0x898A, 0x8486, 0x8582, 0x8682, 0x8786, 0x888E, 0x898A, 0x9086, 0x9182, 0x9282, 0x9386, 0x9482, 0x9586, 0x9686, 0x9782, 0x988A, 0x998E, 0x3423, 0x3527, 0x3627, 0x3723, 0x382B, 0x392F, 0x4003, 0x4107, 0x4207, 0x4303, 0x4407, 0x4503, 0x4603, 0x4707, 0x480F, 0x490B, 0x4407, 0x4503, 0x4603, 0x4707, 0x480F, 0x490B, 0x5007, 0x5103, 0x5203, 0x5307, 0x5403, 0x5507, 0x5607, 0x5703, 0x580B, 0x590F, 0x5403, 0x5507, 0x5607, 0x5703, 0x580B, 0x590F, 0x6027, 0x6123, 0x6223, 0x6327, 0x6423, 0x6527, 0x6627, 0x6723, 0x682B, 0x692F, 0x6423, 0x6527, 0x6627, 0x6723, 0x682B, 0x692F, 0x7023, 0x7127, 0x7227, 0x7323, 0x7427, 0x7523, 0x7623, 0x7727, 0x782F, 0x792B, 0x7427, 0x7523, 0x7623, 0x7727, 0x782F, 0x792B, 0x8083, 0x8187, 0x8287, 0x8383, 0x8487, 0x8583, 0x8683, 0x8787, 0x888F, 0x898B, 0x8487, 0x8583, 0x8683, 0x8787, 0x888F, 0x898B, 0x9087, 0x9183, 0x9283, 0x9387, 0x9483, 0x9587, 0x9687, 0x9783, 0x988B, 0x998F, 0x9483, 0x9587, 0x9687, 0x9783, 0x988B, 0x998F, 0xA0A7, 0xA1A3, 0xA2A3, 0xA3A7, 0xA4A3, 0xA5A7, 0xA6A7, 0xA7A3, 0xA8AB, 0xA9AF, 0xA4A3, 0xA5A7, 0xA6A7, 0xA7A3, 0xA8AB, 0xA9AF, 0xB0A3, 0xB1A7, 0xB2A7, 0xB3A3, 0xB4A7, 0xB5A3, 0xB6A3, 0xB7A7, 0xB8AF, 0xB9AB, 0xB4A7, 0xB5A3, 0xB6A3, 0xB7A7, 0xB8AF, 0xB9AB, 0xC087, 0xC183, 0xC283, 0xC387, 0xC483, 0xC587, 0xC687, 0xC783, 0xC88B, 0xC98F, 0xC483, 0xC587, 0xC687, 0xC783, 0xC88B, 0xC98F, 0xD083, 0xD187, 0xD287, 0xD383, 0xD487, 0xD583, 0xD683, 0xD787, 0xD88F, 0xD98B, 0xD487, 0xD583, 0xD683, 0xD787, 0xD88F, 0xD98B, 0xE0A3, 0xE1A7, 0xE2A7, 0xE3A3, 0xE4A7, 0xE5A3, 0xE6A3, 0xE7A7, 0xE8AF, 0xE9AB, 0xE4A7, 0xE5A3, 0xE6A3, 0xE7A7, 0xE8AF, 0xE9AB, 0xF0A7, 0xF1A3, 0xF2A3, 0xF3A7, 0xF4A3, 0xF5A7, 0xF6A7, 0xF7A3, 0xF8AB, 0xF9AF, 0xF4A3, 0xF5A7, 0xF6A7, 0xF7A3, 0xF8AB, 0xF9AF, 0x0047, 0x0103, 0x0203, 0x0307, 0x0403, 0x0507, 0x0607, 0x0703, 0x080B, 0x090F, 0x0403, 0x0507, 0x0607, 0x0703, 0x080B, 0x090F, 0x1003, 0x1107, 0x1207, 0x1303, 0x1407, 0x1503, 0x1603, 0x1707, 0x180F, 0x190B, 0x1407, 0x1503, 0x1603, 0x1707, 0x180F, 0x190B, 0x2023, 0x2127, 0x2227, 0x2323, 0x2427, 0x2523, 0x2623, 0x2727, 0x282F, 0x292B, 0x2427, 0x2523, 0x2623, 0x2727, 0x282F, 0x292B, 0x3027, 0x3123, 0x3223, 0x3327, 0x3423, 0x3527, 0x3627, 0x3723, 0x382B, 0x392F, 0x3423, 0x3527, 0x3627, 0x3723, 0x382B, 0x392F, 0x4003, 0x4107, 0x4207, 0x4303, 0x4407, 0x4503, 0x4603, 0x4707, 0x480F, 0x490B, 0x4407, 0x4503, 0x4603, 0x4707, 0x480F, 0x490B, 0x5007, 0x5103, 0x5203, 0x5307, 0x5403, 0x5507, 0x5607, 0x5703, 0x580B, 0x590F, 0x5403, 0x5507, 0x5607, 0x5703, 0x580B, 0x590F, 0x6027, 0x6123, 0x6223, 0x6327, 0x6423, 0x6527, 0x6627, 0x6723, 0x682B, 0x692F, 0x6423, 0x6527, 0x6627, 0x6723, 0x682B, 0x692F, 0x7023, 0x7127, 0x7227, 0x7323, 0x7427, 0x7523, 0x7623, 0x7727, 0x782F, 0x792B, 0x7427, 0x7523, 0x7623, 0x7727, 0x782F, 0x792B, 0x8083, 0x8187, 0x8287, 0x8383, 0x8487, 0x8583, 0x8683, 0x8787, 0x888F, 0x898B, 0x8487, 0x8583, 0x8683, 0x8787, 0x888F, 0x898B, 0x9087, 0x9183, 0x9283, 0x9387, 0x9483, 0x9587, 0x9687, 0x9783, 0x988B, 0x998F, 0x9483, 0x9587, 0x9687, 0x9783, 0x988B, 0x998F, 0xFABE, 0xFBBA, 0xFCBE, 0xFDBA, 0xFEBA, 0xFFBE, 0x0046, 0x0102, 0x0202, 0x0306, 0x0402, 0x0506, 0x0606, 0x0702, 0x080A, 0x090E, 0x0A1E, 0x0B1A, 0x0C1E, 0x0D1A, 0x0E1A, 0x0F1E, 0x1002, 0x1106, 0x1206, 0x1302, 0x1406, 0x1502, 0x1602, 0x1706, 0x180E, 0x190A, 0x1A1A, 0x1B1E, 0x1C1A, 0x1D1E, 0x1E1E, 0x1F1A, 0x2022, 0x2126, 0x2226, 0x2322, 0x2426, 0x2522, 0x2622, 0x2726, 0x282E, 0x292A, 0x2A3A, 0x2B3E, 0x2C3A, 0x2D3E, 0x2E3E, 0x2F3A, 0x3026, 0x3122, 0x3222, 0x3326, 0x3422, 0x3526, 0x3626, 0x3722, 0x382A, 0x392E, 0x3A3E, 0x3B3A, 0x3C3E, 0x3D3A, 0x3E3A, 0x3F3E, 0x4002, 0x4106, 0x4206, 0x4302, 0x4406, 0x4502, 0x4602, 0x4706, 0x480E, 0x490A, 0x4A1A, 0x4B1E, 0x4C1A, 0x4D1E, 0x4E1E, 0x4F1A, 0x5006, 0x5102, 0x5202, 0x5306, 0x5402, 0x5506, 0x5606, 0x5702, 0x580A, 0x590E, 0x5A1E, 0x5B1A, 0x5C1E, 0x5D1A, 0x5E1A, 0x5F1E, 0x6026, 0x6122, 0x6222, 0x6326, 0x6422, 0x6526, 0x6626, 0x6722, 0x682A, 0x692E, 0x6A3E, 0x6B3A, 0x6C3E, 0x6D3A, 0x6E3A, 0x6F3E, 0x7022, 0x7126, 0x7226, 0x7322, 0x7426, 0x7522, 0x7622, 0x7726, 0x782E, 0x792A, 0x7A3A, 0x7B3E, 0x7C3A, 0x7D3E, 0x7E3E, 0x7F3A, 0x8082, 0x8186, 0x8286, 0x8382, 0x8486, 0x8582, 0x8682, 0x8786, 0x888E, 0x898A, 0x8A9A, 0x8B9E, 0x8C9A, 0x8D9E, 0x8E9E, 0x8F9A, 0x9086, 0x9182, 0x9282, 0x9386, 0x3423, 0x3527, 0x3627, 0x3723, 0x382B, 0x392F, 0x3A3F, 0x3B3B, 0x3C3F, 0x3D3B, 0x3E3B, 0x3F3F, 0x4003, 0x4107, 0x4207, 0x4303, 0x4407, 0x4503, 0x4603, 0x4707, 0x480F, 0x490B, 0x4A1B, 0x4B1F, 0x4C1B, 0x4D1F, 0x4E1F, 0x4F1B, 0x5007, 0x5103, 0x5203, 0x5307, 0x5403, 0x5507, 0x5607, 0x5703, 0x580B, 0x590F, 0x5A1F, 0x5B1B, 0x5C1F, 0x5D1B, 0x5E1B, 0x5F1F, 0x6027, 0x6123, 0x6223, 0x6327, 0x6423, 0x6527, 0x6627, 0x6723, 0x682B, 0x692F, 0x6A3F, 0x6B3B, 0x6C3F, 0x6D3B, 0x6E3B, 0x6F3F, 0x7023, 0x7127, 0x7227, 0x7323, 0x7427, 0x7523, 0x7623, 0x7727, 0x782F, 0x792B, 0x7A3B, 0x7B3F, 0x7C3B, 0x7D3F, 0x7E3F, 0x7F3B, 0x8083, 0x8187, 0x8287, 0x8383, 0x8487, 0x8583, 0x8683, 0x8787, 0x888F, 0x898B, 0x8A9B, 0x8B9F, 0x8C9B, 0x8D9F, 0x8E9F, 0x8F9B, 0x9087, 0x9183, 0x9283, 0x9387, 0x9483, 0x9587, 0x9687, 0x9783, 0x988B, 0x998F, 0x9A9F, 0x9B9B, 0x9C9F, 0x9D9B, 0x9E9B, 0x9F9F, 0xA0A7, 0xA1A3, 0xA2A3, 0xA3A7, 0xA4A3, 0xA5A7, 0xA6A7, 0xA7A3, 0xA8AB, 0xA9AF, 0xAABF, 0xABBB, 0xACBF, 0xADBB, 0xAEBB, 0xAFBF, 0xB0A3, 0xB1A7, 0xB2A7, 0xB3A3, 0xB4A7, 0xB5A3, 0xB6A3, 0xB7A7, 0xB8AF, 0xB9AB, 0xBABB, 0xBBBF, 0xBCBB, 0xBDBF, 0xBEBF, 0xBFBB, 0xC087, 0xC183, 0xC283, 0xC387, 0xC483, 0xC587, 0xC687, 0xC783, 0xC88B, 0xC98F, 0xCA9F, 0xCB9B, 0xCC9F, 0xCD9B, 0xCE9B, 0xCF9F, 0xD083, 0xD187, 0xD287, 0xD383, 0xD487, 0xD583, 0xD683, 0xD787, 0xD88F, 0xD98B, 0xDA9B, 0xDB9F, 0xDC9B, 0xDD9F, 0xDE9F, 0xDF9B, 0xE0A3, 0xE1A7, 0xE2A7, 0xE3A3, 0xE4A7, 0xE5A3, 0xE6A3, 0xE7A7, 0xE8AF, 0xE9AB, 0xEABB, 0xEBBF, 0xECBB, 0xEDBF, 0xEEBF, 0xEFBB, 0xF0A7, 0xF1A3, 0xF2A3, 0xF3A7, 0xF4A3, 0xF5A7, 0xF6A7, 0xF7A3, 0xF8AB, 0xF9AF, 0xFABF, 0xFBBB, 0xFCBF, 0xFDBB, 0xFEBB, 0xFFBF, 0x0047, 0x0103, 0x0203, 0x0307, 0x0403, 0x0507, 0x0607, 0x0703, 0x080B, 0x090F, 0x0A1F, 0x0B1B, 0x0C1F, 0x0D1B, 0x0E1B, 0x0F1F, 0x1003, 0x1107, 0x1207, 0x1303, 0x1407, 0x1503, 0x1603, 0x1707, 0x180F, 0x190B, 0x1A1B, 0x1B1F, 0x1C1B, 0x1D1F, 0x1E1F, 0x1F1B, 0x2023, 0x2127, 0x2227, 0x2323, 0x2427, 0x2523, 0x2623, 0x2727, 0x282F, 0x292B, 0x2A3B, 0x2B3F, 0x2C3B, 0x2D3F, 0x2E3F, 0x2F3B, 0x3027, 0x3123, 0x3223, 0x3327, 0x3423, 0x3527, 0x3627, 0x3723, 0x382B, 0x392F, 0x3A3F, 0x3B3B, 0x3C3F, 0x3D3B, 0x3E3B, 0x3F3F, 0x4003, 0x4107, 0x4207, 0x4303, 0x4407, 0x4503, 0x4603, 0x4707, 0x480F, 0x490B, 0x4A1B, 0x4B1F, 0x4C1B, 0x4D1F, 0x4E1F, 0x4F1B, 0x5007, 0x5103, 0x5203, 0x5307, 0x5403, 0x5507, 0x5607, 0x5703, 0x580B, 0x590F, 0x5A1F, 0x5B1B, 0x5C1F, 0x5D1B, 0x5E1B, 0x5F1F, 0x6027, 0x6123, 0x6223, 0x6327, 0x6423, 0x6527, 0x6627, 0x6723, 0x682B, 0x692F, 0x6A3F, 0x6B3B, 0x6C3F, 0x6D3B, 0x6E3B, 0x6F3F, 0x7023, 0x7127, 0x7227, 0x7323, 0x7427, 0x7523, 0x7623, 0x7727, 0x782F, 0x792B, 0x7A3B, 0x7B3F, 0x7C3B, 0x7D3F, 0x7E3F, 0x7F3B, 0x8083, 0x8187, 0x8287, 0x8383, 0x8487, 0x8583, 0x8683, 0x8787, 0x888F, 0x898B, 0x8A9B, 0x8B9F, 0x8C9B, 0x8D9F, 0x8E9F, 0x8F9B, 0x9087, 0x9183, 0x9283, 0x9387, 0x9483, 0x9587, 0x9687, 0x9783, 0x988B, 0x998F }; }
109,913
0.495852
0.366259
5,471
19.094133
18.475267
127
false
false
0
0
0
0
0
0
1.251873
false
false
11
757abe347fac5a6bf8263156d62bb081b1d4a274
19,318,762,952,005
c816ff9dc4960fc5f2ac9fc747823f11b5e815c6
/DiffJ/resources/diffj/packages/d0/Removed.java
577ecc174fb2675f6ac11726a9a02c9f1fb60b63
[]
no_license
danielcalencar/raszzprime
https://github.com/danielcalencar/raszzprime
11ee9f2cd00e3478a522c50199533018e15dd1a0
10d624008a8f1f446bcbcbc4bf1e052e3f4c00c1
refs/heads/master
2022-10-25T23:20:20.180000
2022-10-04T01:15:24
2022-10-04T01:15:24
207,686,552
9
11
null
false
2023-09-14T03:44:07
2019-09-11T00:15:56
2023-05-29T12:25:08
2023-09-14T03:44:06
129,614
8
11
0
Java
false
false
package org.incava.removed; class Removed { }
UTF-8
Java
47
java
Removed.java
Java
[]
null
[]
package org.incava.removed; class Removed { }
47
0.744681
0.744681
4
10.75
11.098987
27
false
false
0
0
0
0
0
0
0.25
false
false
11
b4f8277595cce10fb2893492e4768d4fe113964a
9,148,280,358,968
dfbe68de409b8f34e71ebf60b41a0b8c433e53a2
/src/src/bonbombe/exceptions/JoueurInexistantException.java
9a241ade1ea42cb7d4e7d2b69fb46925a998a082
[]
no_license
ericJz/Projet_IR
https://github.com/ericJz/Projet_IR
0618f5d1ace057cc268a4dc2a61cc6e939e4ca5d
c5a8ce6c086bcd7e0a1e76221b671f778f446294
refs/heads/master
2020-05-31T05:10:13.025000
2015-09-21T20:59:51
2015-09-21T20:59:51
42,892,147
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bonbombe.exceptions; import java.lang.Exception; /** * Exception de login existant */ public class JoueurInexistantException extends Exception { public JoueurInexistantException(String _message){ super(_message); } }
UTF-8
Java
231
java
JoueurInexistantException.java
Java
[]
null
[]
package bonbombe.exceptions; import java.lang.Exception; /** * Exception de login existant */ public class JoueurInexistantException extends Exception { public JoueurInexistantException(String _message){ super(_message); } }
231
0.779221
0.779221
11
20.09091
19.736696
58
false
false
0
0
0
0
0
0
0.636364
false
false
11
c54502ac7408efdd457276c4a12175fe90da0630
29,987,461,678,457
4501f2e990b87bf278183dfc1ba188e011ea763e
/service_sellergoods/src/main/java/cn/itcast/core/service/OrdersServiceImpl.java
ab3f9b5c6ad68cd03911d73c67e38f28e6614b8b
[]
no_license
beijingheima/xiangmushizhan
https://github.com/beijingheima/xiangmushizhan
2ea7900e4ad5b1a6b96e69b7fab5d167c800659b
2a94c0dfe02b1bfba71149f28e0d4fe0d3d361cc
refs/heads/master
2020-04-15T15:25:05.551000
2019-01-11T09:36:08
2019-01-11T09:36:08
164,792,754
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.itcast.core.service; import cn.itcast.core.dao.order.OrderDao; import cn.itcast.core.pojo.entity.OrderEntity; import cn.itcast.core.pojo.entity.PageResult; import cn.itcast.core.pojo.good.Brand; import cn.itcast.core.pojo.good.BrandQuery; import cn.itcast.core.pojo.order.Order; import cn.itcast.core.pojo.order.OrderItemQuery; import cn.itcast.core.pojo.order.OrderQuery; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import org.aspectj.weaver.ast.Or; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import javax.management.Query; import java.util.List; import java.util.Map; @Service public class OrdersServiceImpl implements OrdersService { @Autowired private OrderDao orderDao; @Override public List<OrderEntity> findAll() { List<OrderEntity> entityList = orderDao.findAllOrder(null); return entityList; } @Override public PageResult findPage(OrderEntity order, Integer page, Integer rows) { //使用分页助手, 传入当前页和每页查询多少条数据 PageHelper.startPage(page, rows); OrderQuery orderQuery = new OrderQuery(); OrderQuery.Criteria criteria1 = orderQuery.createCriteria(); if (order!=null){ if (order.getCreateTime()!=null && !"".equals(order.getCreateTime())){ criteria1.andCreateTimeEqualTo(order.getCreateTime()); } } //使用分页助手的page对象接收查询到的数据, page对象继承了ArrayList所以可以接收查询到的结果集数据. Page<OrderEntity> orders = (Page<OrderEntity>)orderDao.findAllOrder(orderQuery); return new PageResult(orders.getTotal(), orders.getResult()); } @Override public Brand findOne(Long id) { return null; } @Override public List<Map> selectOptionList() { return null; } }
UTF-8
Java
2,038
java
OrdersServiceImpl.java
Java
[]
null
[]
package cn.itcast.core.service; import cn.itcast.core.dao.order.OrderDao; import cn.itcast.core.pojo.entity.OrderEntity; import cn.itcast.core.pojo.entity.PageResult; import cn.itcast.core.pojo.good.Brand; import cn.itcast.core.pojo.good.BrandQuery; import cn.itcast.core.pojo.order.Order; import cn.itcast.core.pojo.order.OrderItemQuery; import cn.itcast.core.pojo.order.OrderQuery; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import org.aspectj.weaver.ast.Or; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import javax.management.Query; import java.util.List; import java.util.Map; @Service public class OrdersServiceImpl implements OrdersService { @Autowired private OrderDao orderDao; @Override public List<OrderEntity> findAll() { List<OrderEntity> entityList = orderDao.findAllOrder(null); return entityList; } @Override public PageResult findPage(OrderEntity order, Integer page, Integer rows) { //使用分页助手, 传入当前页和每页查询多少条数据 PageHelper.startPage(page, rows); OrderQuery orderQuery = new OrderQuery(); OrderQuery.Criteria criteria1 = orderQuery.createCriteria(); if (order!=null){ if (order.getCreateTime()!=null && !"".equals(order.getCreateTime())){ criteria1.andCreateTimeEqualTo(order.getCreateTime()); } } //使用分页助手的page对象接收查询到的数据, page对象继承了ArrayList所以可以接收查询到的结果集数据. Page<OrderEntity> orders = (Page<OrderEntity>)orderDao.findAllOrder(orderQuery); return new PageResult(orders.getTotal(), orders.getResult()); } @Override public Brand findOne(Long id) { return null; } @Override public List<Map> selectOptionList() { return null; } }
2,038
0.715921
0.71488
68
27.264706
24.980356
88
false
false
0
0
0
0
0
0
0.514706
false
false
11
e9838bed1f84c029f7a808eff8ec49aeef6bdda8
10,316,511,468,240
9c96c0b6f33f64e568b9b6cc6dbca4738114bcef
/app/src/main/java/com/bruce/gank/net/retrofit/api/GankApi.java
746d49238c6f1c705125a7062b6975ca801d3102
[]
no_license
xhdlmy/VMGank
https://github.com/xhdlmy/VMGank
439e95e03757ca4dea4589582bde376766289a3e
d4294d86317376c3847ca00c5ede89e950a36fb2
refs/heads/master
2022-04-23T14:38:53.777000
2020-04-26T12:33:17
2020-04-26T12:33:17
259,025,813
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bruce.gank.net.retrofit.api; import io.reactivex.Observable; import okhttp3.ResponseBody; import retrofit2.http.GET; import retrofit2.http.Path; /** * Created time:2020/4/21 * Author:Bruce * Function Description: */ public interface GankApi { // Banner @GET("banners") Observable<ResponseBody> getBanner(); // 分类 @GET("categories/{categories_type}") Observable<ResponseBody> getCategory(@Path("categories_type") String categoryType); // 分类数据 @GET("category/{category}/type/{type}/page/{page}/count/{count}") Observable<ResponseBody> getClassifyData(@Path("category") String category, @Path("type") String type, @Path("page") int pager, @Path("count") int count); // 数据详情 @GET("post/{post_id}") Observable<ResponseBody> getDataDetail(@Path("post_id") String post_id); }
UTF-8
Java
866
java
GankApi.java
Java
[ { "context": "tp.Path;\n\n/**\n * Created time:2020/4/21\n * Author:Bruce\n * Function Description:\n */\npublic interface Gan", "end": 204, "score": 0.9975194334983826, "start": 199, "tag": "USERNAME", "value": "Bruce" } ]
null
[]
package com.bruce.gank.net.retrofit.api; import io.reactivex.Observable; import okhttp3.ResponseBody; import retrofit2.http.GET; import retrofit2.http.Path; /** * Created time:2020/4/21 * Author:Bruce * Function Description: */ public interface GankApi { // Banner @GET("banners") Observable<ResponseBody> getBanner(); // 分类 @GET("categories/{categories_type}") Observable<ResponseBody> getCategory(@Path("categories_type") String categoryType); // 分类数据 @GET("category/{category}/type/{type}/page/{page}/count/{count}") Observable<ResponseBody> getClassifyData(@Path("category") String category, @Path("type") String type, @Path("page") int pager, @Path("count") int count); // 数据详情 @GET("post/{post_id}") Observable<ResponseBody> getDataDetail(@Path("post_id") String post_id); }
866
0.692857
0.680952
31
26.096775
32.941154
158
false
false
0
0
0
0
0
0
0.387097
false
false
11
f0ad9a4e3e11ef0cb4bf7663bd9d7dea3f488f50
16,020,228,037,251
e2923829ce208c663803ce849c0a018d4cdfa486
/src/JDBC/Upload.java
f07ca855f765b6c7777a78651defcb45e49dd538
[]
no_license
yanyun6/QFFThird
https://github.com/yanyun6/QFFThird
007c20d3ea2572ea8f6312a28bcfe26b64afd7c5
d6406734a9a81aaf4a9936c2515d648c605547dc
refs/heads/master
2023-02-05T22:15:56.979000
2020-12-27T04:27:52
2020-12-27T04:27:52
324,382,870
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package JDBC; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * 该类用于存储文件上传的用户名、类型、时间到数据库 */ public class Upload { public void insert(String username,String type,String time){ Connection connection = null; PreparedStatement ps = null; ResultSet resultSet = null; try { connection = JdbcUtils.getConnection(); String sql = "insert into PublicStorage(username,type,time) values (?,?,?)"; ps = connection.prepareStatement(sql); ps.setString(1, username); ps.setString(2, type); ps.setString(3, time); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JdbcUtils.close(ps, connection, resultSet); } } }
UTF-8
Java
928
java
Upload.java
Java
[]
null
[]
package JDBC; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * 该类用于存储文件上传的用户名、类型、时间到数据库 */ public class Upload { public void insert(String username,String type,String time){ Connection connection = null; PreparedStatement ps = null; ResultSet resultSet = null; try { connection = JdbcUtils.getConnection(); String sql = "insert into PublicStorage(username,type,time) values (?,?,?)"; ps = connection.prepareStatement(sql); ps.setString(1, username); ps.setString(2, type); ps.setString(3, time); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JdbcUtils.close(ps, connection, resultSet); } } }
928
0.604545
0.601136
31
27.387096
20.39715
88
false
false
0
0
0
0
0
0
0.903226
false
false
11
53ac566fe0a2e633d45df8b776dcfb893ae5f8a5
6,640,019,464,777
43c53bfd9f461cb99e124e6ac4820d7cb662e1f2
/app/src/main/java/com/androidy/azsecuer/activity/adapter/QuickAdapter.java
8b978545b8692b216180ea2611b016a586425be8
[]
no_license
lifuyuan123/azsecuers
https://github.com/lifuyuan123/azsecuers
b96c341796fd441101eb46b9a851c3cd080d8a2e
a51fd47b6caf6f24b2eac94eaaf73697d92c43fa
refs/heads/master
2021-01-22T19:59:54.732000
2017-03-17T04:34:05
2017-03-17T04:34:05
85,271,118
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.androidy.azsecuer.activity.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TextView; import com.androidy.azsecuer.R; import com.androidy.azsecuer.activity.adapter.basedataAdapter.BaseDataAdapter; import com.androidy.azsecuer.activity.entity.quick.Quicker; import com.androidy.azsecuer.activity.util.PublicUtils; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2016/8/20. */ public class QuickAdapter extends BaseDataAdapter<Quicker> { private List<Quicker> quickers=new ArrayList<>(); public QuickAdapter(Context context) { super(context); } public int getItemViewType(int position){ Quicker quicker=(Quicker) getItem(position); if(quicker.isSystemApp){ return 0;//系统的 } return 1;//用户的 } @Override public View getView(int position, View convertView, ViewGroup parent) { int type=getItemViewType(position); ViewHolder viewHolder; if(convertView==null){ switch (type){ case 0: convertView=this.layoutInflater.inflate(R.layout.phone_quick_list_style_system,null); break; case 1: convertView=this.layoutInflater.inflate(R.layout.phone_quick_list_style,null); break; } viewHolder=new ViewHolder(); viewHolder.tv_phonequick_liststyle_top=(TextView) convertView.findViewById(R.id.tv_phonequick_liststyle_top); viewHolder.tv_phonequick_liststyle_buttom=(TextView)convertView.findViewById(R.id.tv_phonequick_liststyle_buttom); viewHolder.im_phone_quick_liststyle=(ImageView)convertView.findViewById(R.id.im_phone_quick_liststyle); viewHolder.phone_qiuck_liststyle_check=(CheckBox)convertView.findViewById(R.id.phone_qiuck_liststyle_check); convertView.setTag(viewHolder); }else { viewHolder=(ViewHolder)convertView.getTag(); } Quicker quicker=(Quicker) this.getItem(position); viewHolder.tv_phonequick_liststyle_top.setText(quicker.name); viewHolder.tv_phonequick_liststyle_buttom.setText(PublicUtils.formatSize(quicker.nameSize)); viewHolder.im_phone_quick_liststyle.setImageDrawable(quicker.drawable); viewHolder.phone_qiuck_liststyle_check.setChecked(quicker.ischeck); //check设置标签 viewHolder.phone_qiuck_liststyle_check.setTag(quicker); viewHolder.phone_qiuck_liststyle_check.setOnCheckedChangeListener(onCheckedChangeListener); return convertView; } private CompoundButton.OnCheckedChangeListener onCheckedChangeListener=new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ((Quicker)buttonView.getTag()).ischeck=isChecked; } }; class ViewHolder{ TextView tv_phonequick_liststyle_top,tv_phonequick_liststyle_buttom; ImageView im_phone_quick_liststyle; CheckBox phone_qiuck_liststyle_check; } }
UTF-8
Java
3,337
java
QuickAdapter.java
Java
[]
null
[]
package com.androidy.azsecuer.activity.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TextView; import com.androidy.azsecuer.R; import com.androidy.azsecuer.activity.adapter.basedataAdapter.BaseDataAdapter; import com.androidy.azsecuer.activity.entity.quick.Quicker; import com.androidy.azsecuer.activity.util.PublicUtils; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2016/8/20. */ public class QuickAdapter extends BaseDataAdapter<Quicker> { private List<Quicker> quickers=new ArrayList<>(); public QuickAdapter(Context context) { super(context); } public int getItemViewType(int position){ Quicker quicker=(Quicker) getItem(position); if(quicker.isSystemApp){ return 0;//系统的 } return 1;//用户的 } @Override public View getView(int position, View convertView, ViewGroup parent) { int type=getItemViewType(position); ViewHolder viewHolder; if(convertView==null){ switch (type){ case 0: convertView=this.layoutInflater.inflate(R.layout.phone_quick_list_style_system,null); break; case 1: convertView=this.layoutInflater.inflate(R.layout.phone_quick_list_style,null); break; } viewHolder=new ViewHolder(); viewHolder.tv_phonequick_liststyle_top=(TextView) convertView.findViewById(R.id.tv_phonequick_liststyle_top); viewHolder.tv_phonequick_liststyle_buttom=(TextView)convertView.findViewById(R.id.tv_phonequick_liststyle_buttom); viewHolder.im_phone_quick_liststyle=(ImageView)convertView.findViewById(R.id.im_phone_quick_liststyle); viewHolder.phone_qiuck_liststyle_check=(CheckBox)convertView.findViewById(R.id.phone_qiuck_liststyle_check); convertView.setTag(viewHolder); }else { viewHolder=(ViewHolder)convertView.getTag(); } Quicker quicker=(Quicker) this.getItem(position); viewHolder.tv_phonequick_liststyle_top.setText(quicker.name); viewHolder.tv_phonequick_liststyle_buttom.setText(PublicUtils.formatSize(quicker.nameSize)); viewHolder.im_phone_quick_liststyle.setImageDrawable(quicker.drawable); viewHolder.phone_qiuck_liststyle_check.setChecked(quicker.ischeck); //check设置标签 viewHolder.phone_qiuck_liststyle_check.setTag(quicker); viewHolder.phone_qiuck_liststyle_check.setOnCheckedChangeListener(onCheckedChangeListener); return convertView; } private CompoundButton.OnCheckedChangeListener onCheckedChangeListener=new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ((Quicker)buttonView.getTag()).ischeck=isChecked; } }; class ViewHolder{ TextView tv_phonequick_liststyle_top,tv_phonequick_liststyle_buttom; ImageView im_phone_quick_liststyle; CheckBox phone_qiuck_liststyle_check; } }
3,337
0.704854
0.701538
79
40.987343
33.38858
126
false
false
0
0
0
0
0
0
0.658228
false
false
11
d97e338dc4b248765dcb0906916ff151ff984946
16,973,710,781,606
f5376bac2af32b509f087e3cb532de5e24892a19
/eclipse/javaFoundation/src/com/java/method/printStar.java
f08c2c464603cb30041ba8d20c1208b5bd244b1d
[]
no_license
wz71014q/AndroidWorkSpace
https://github.com/wz71014q/AndroidWorkSpace
3d99eb857c20203b614abb27284453cc4eb71c86
771d58ec9c3066e81056cb199f0803041fa71ae8
refs/heads/master
2019-03-17T18:06:57.283000
2018-02-28T08:27:25
2018-02-28T08:27:25
123,252,996
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.java.method; public class printStar { /** * @param args */ public void printfStar() { System.out.print("************************"); }//方法只能在类中定义,一般放在主方法前面 public int pr() { return 0; }//无参有返回值 public String st(){ String name="Tom"; String myName="我叫:"+name; return myName; }//无参有返回值 public static void main(String[] args) { // TODO Auto-generated method stub printStar myDemo=new printStar(); //方法的调用:创建一个printStar类的对象myDemo,使用对象名.方法名()来调用。 //类 对象=new 类(); myDemo.printfStar(); System.out.print("\nyes!\n"); myDemo.printfStar(); myDemo.pr(); System.out.print("\n"+myDemo.st()); } }
GB18030
Java
764
java
printStar.java
Java
[ { "context": "0;\n\t}//无参有返回值\n\tpublic String st(){\n\t\tString name=\"Tom\";\n\t\tString myName=\"我叫:\"+name;\n\t\treturn myName;\n\t}", "end": 259, "score": 0.9929971098899841, "start": 256, "tag": "NAME", "value": "Tom" } ]
null
[]
package com.java.method; public class printStar { /** * @param args */ public void printfStar() { System.out.print("************************"); }//方法只能在类中定义,一般放在主方法前面 public int pr() { return 0; }//无参有返回值 public String st(){ String name="Tom"; String myName="我叫:"+name; return myName; }//无参有返回值 public static void main(String[] args) { // TODO Auto-generated method stub printStar myDemo=new printStar(); //方法的调用:创建一个printStar类的对象myDemo,使用对象名.方法名()来调用。 //类 对象=new 类(); myDemo.printfStar(); System.out.print("\nyes!\n"); myDemo.printfStar(); myDemo.pr(); System.out.print("\n"+myDemo.st()); } }
764
0.626959
0.625392
31
19.580645
13.691943
49
false
false
0
0
0
0
0
0
1.741935
false
false
11
93f45d4c4444676b6912e047102a4257bc185f47
5,660,766,922,312
449f52674e7a1203950f9155b03ce06e6eacb09e
/src/main/java/wo/app/woserver/handler/WoStaticRequestHandler.java
cc53bc3fae60f9029af95202ab3739d1ad5b595f
[]
no_license
wooder-whj/wo-web-app-server
https://github.com/wooder-whj/wo-web-app-server
ae4b2a0a6b1ecf34a1768749692c90fca21f69d6
5c77195a214152c9cb1af183f77f58ccff87ff2c
refs/heads/master
2020-05-03T13:53:10.588000
2019-04-02T12:00:46
2019-04-02T12:00:46
178,663,412
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package wo.app.woserver.handler; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.ApplicationArguments; import org.springframework.context.ApplicationContext; import org.springframework.util.ResourceUtils; import wo.app.woserver.WoServer; import wo.app.woserver.util.UriUtils; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.List; public class WoStaticRequestHandler implements RequestHandler { private final Logger logger= LoggerFactory.getLogger(WoStaticRequestHandler.class); private final FullHttpRequest request; private final ApplicationContext applicationContext; public WoStaticRequestHandler(FullHttpRequest request, ApplicationContext applicationContext) { this.request = request; this.applicationContext = applicationContext; } @Override public HttpResponse handleRequest() throws Exception { byte[] bytes = readStaticResource(); HttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(bytes)); httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"*/*;charset=UTF-8") .set(HttpHeaderNames.CONTENT_LENGTH, bytes.length); return httpResponse; } private byte[] readStaticResource() throws IOException { RandomAccessFile accessFile=null; FileChannel channel=null; byte[] bytes=null; List<Byte> contentBytes=new ArrayList(); try{ ApplicationArguments arguments = applicationContext.getBean(ApplicationArguments.class); String contextPath=UriUtils.getContextPath(request.uri()); if(arguments.containsOption(WoServer.CONTEXT_PATH)){ accessFile=new RandomAccessFile( arguments.getOptionValues(WoServer.CONTEXT_PATH).get(0) + contextPath, "r"); }else { accessFile=new RandomAccessFile( UriUtils.getDefaultContextPath(ResourceUtils.FILE_URL_PREFIX,WoServer.DEFAULT_CONTEXT_DIR) + contextPath.substring(1), "r"); } // String urlPath=ResourceUtils.URL_PROTOCOL_JAR.equals(UriUtils.getURLProtocol(WoStaticRequestHandler.class)) // ?UriUtils.getClassPath().replace(ResourceUtils.FILE_URL_PREFIX,ResourceUtils.JAR_URL_PREFIX ) // :UriUtils.getClassPath(); channel = accessFile.getChannel(); ByteBuffer buffer=ByteBuffer.allocate(2048); while((channel.read(buffer))>0){ buffer.flip(); bytes=new byte[buffer.limit()]; buffer.get(bytes); for(byte b:bytes){ contentBytes.add(b); } buffer.clear(); } bytes=new byte[contentBytes.size()]; for(int i=0;i<contentBytes.size();i++){ bytes[i]=(contentBytes.get(i)).byteValue(); } }finally { try{ if(channel!=null){ channel.close(); } if(accessFile!=null){ accessFile.close(); } }catch (Exception e){ logger.error(e.getMessage(),e ); } } return bytes; } }
UTF-8
Java
3,498
java
WoStaticRequestHandler.java
Java
[]
null
[]
package wo.app.woserver.handler; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.ApplicationArguments; import org.springframework.context.ApplicationContext; import org.springframework.util.ResourceUtils; import wo.app.woserver.WoServer; import wo.app.woserver.util.UriUtils; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.List; public class WoStaticRequestHandler implements RequestHandler { private final Logger logger= LoggerFactory.getLogger(WoStaticRequestHandler.class); private final FullHttpRequest request; private final ApplicationContext applicationContext; public WoStaticRequestHandler(FullHttpRequest request, ApplicationContext applicationContext) { this.request = request; this.applicationContext = applicationContext; } @Override public HttpResponse handleRequest() throws Exception { byte[] bytes = readStaticResource(); HttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(bytes)); httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"*/*;charset=UTF-8") .set(HttpHeaderNames.CONTENT_LENGTH, bytes.length); return httpResponse; } private byte[] readStaticResource() throws IOException { RandomAccessFile accessFile=null; FileChannel channel=null; byte[] bytes=null; List<Byte> contentBytes=new ArrayList(); try{ ApplicationArguments arguments = applicationContext.getBean(ApplicationArguments.class); String contextPath=UriUtils.getContextPath(request.uri()); if(arguments.containsOption(WoServer.CONTEXT_PATH)){ accessFile=new RandomAccessFile( arguments.getOptionValues(WoServer.CONTEXT_PATH).get(0) + contextPath, "r"); }else { accessFile=new RandomAccessFile( UriUtils.getDefaultContextPath(ResourceUtils.FILE_URL_PREFIX,WoServer.DEFAULT_CONTEXT_DIR) + contextPath.substring(1), "r"); } // String urlPath=ResourceUtils.URL_PROTOCOL_JAR.equals(UriUtils.getURLProtocol(WoStaticRequestHandler.class)) // ?UriUtils.getClassPath().replace(ResourceUtils.FILE_URL_PREFIX,ResourceUtils.JAR_URL_PREFIX ) // :UriUtils.getClassPath(); channel = accessFile.getChannel(); ByteBuffer buffer=ByteBuffer.allocate(2048); while((channel.read(buffer))>0){ buffer.flip(); bytes=new byte[buffer.limit()]; buffer.get(bytes); for(byte b:bytes){ contentBytes.add(b); } buffer.clear(); } bytes=new byte[contentBytes.size()]; for(int i=0;i<contentBytes.size();i++){ bytes[i]=(contentBytes.get(i)).byteValue(); } }finally { try{ if(channel!=null){ channel.close(); } if(accessFile!=null){ accessFile.close(); } }catch (Exception e){ logger.error(e.getMessage(),e ); } } return bytes; } }
3,498
0.643225
0.639508
84
40.642857
32.88459
173
false
false
0
0
0
0
0
0
0.714286
false
false
11
361356b584e9d859017765559433faf3c443c3fb
14,130,442,428,382
ef97bfd7a01786a9b5dba732db99d497a9b96c3f
/src/test/java/tk/graalogosh/ppos/dao/specifications/StudentSpecificationTest.java
210d797098099b6488a751fee94b24912f0bf09a
[]
no_license
graalogosh/ppos
https://github.com/graalogosh/ppos
582838044c945b8723671799b61318ac3d677189
313c3760a3a4207aacc2854f11a4799e23cd1e63
refs/heads/master
2021-05-01T12:48:45.267000
2016-05-02T23:16:06
2016-05-02T23:16:06
40,253,561
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tk.graalogosh.ppos.dao.specifications; import junit.framework.TestCase; import org.junit.Test; /** * Created by graal on 15.08.2015. */ public class StudentSpecificationTest extends TestCase { public void setUp() throws Exception { super.setUp(); } @Test public void testGetByStudentID(){ } }
UTF-8
Java
336
java
StudentSpecificationTest.java
Java
[ { "context": "estCase;\nimport org.junit.Test;\n\n/**\n * Created by graal on 15.08.2015.\n */\npublic class StudentSpecificat", "end": 128, "score": 0.9962320923805237, "start": 123, "tag": "USERNAME", "value": "graal" } ]
null
[]
package tk.graalogosh.ppos.dao.specifications; import junit.framework.TestCase; import org.junit.Test; /** * Created by graal on 15.08.2015. */ public class StudentSpecificationTest extends TestCase { public void setUp() throws Exception { super.setUp(); } @Test public void testGetByStudentID(){ } }
336
0.690476
0.666667
20
15.85
18.246302
56
false
false
0
0
0
0
0
0
0.2
false
false
11
5f9e5a396e1c85ab6cb4f909a879b613fe34dcc8
14,130,442,429,110
ab98c81375665d7bc32411a6a4e8e8a829af35f6
/app/src/main/java/topayevtimur/hw3final/MainActivity.java
4d1489703a98e784b9c91be35fba62546c399f8a
[]
no_license
topaevtimur/homework3
https://github.com/topaevtimur/homework3
80c5a1223eefab76c7a106f411a8c25435372291
8ae0d1afc58e80ec7c0f7096c33c3067c7affa61
refs/heads/master
2020-06-17T19:37:47.965000
2016-11-30T20:38:30
2016-11-30T20:38:30
74,975,814
0
0
null
true
2016-11-28T13:30:59
2016-11-28T13:30:59
2016-10-28T08:26:48
2016-11-28T07:31:48
2
0
0
0
null
null
null
package topayevtimur.hw3final; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.BitmapFactory; import android.provider.ContactsContract; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import java.io.File; /** * Created by AdminPC on 29.11.2016. */ public class MainActivity extends AppCompatActivity { TextView errorText; ImageView image; Button delete; BroadcastReceiver imReceiver; BroadcastReceiver brReceiver; public static final String BROADCAST_ACTION = "ACTION"; public static final String IM_NAME = "pic.jpg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); errorText = (TextView) findViewById(R.id.text_error); image = (ImageView) findViewById(R.id.image); delete = (Button) findViewById(R.id.delete); delete.setOnClickListener(onButton); display(); brReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { display(); } }; imReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { context.startService(new Intent(context, MyService.class)); } }; registerReceiver(imReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); registerReceiver(brReceiver, new IntentFilter(BROADCAST_ACTION)); } public void display() { File file = new File(getFilesDir(), IM_NAME); if (file.exists()) { errorText.setVisibility(View.GONE); image.setVisibility(View.VISIBLE); image.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath())); } else{ errorText.setVisibility(View.VISIBLE); image.setVisibility(View.GONE); } } View.OnClickListener onButton = new View.OnClickListener() { @Override public void onClick(View view) { File file = new File(getFilesDir(), IM_NAME); if(file.exists()) { file.delete(); display(); } } }; @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(imReceiver); unregisterReceiver(brReceiver); } }
UTF-8
Java
2,792
java
MainActivity.java
Java
[ { "context": "iew;\r\n\r\nimport java.io.File;\r\n\r\n/**\r\n * Created by AdminPC on 29.11.2016.\r\n */\r\n\r\npublic class MainActivity ", "end": 517, "score": 0.9995864629745483, "start": 510, "tag": "USERNAME", "value": "AdminPC" } ]
null
[]
package topayevtimur.hw3final; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.BitmapFactory; import android.provider.ContactsContract; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import java.io.File; /** * Created by AdminPC on 29.11.2016. */ public class MainActivity extends AppCompatActivity { TextView errorText; ImageView image; Button delete; BroadcastReceiver imReceiver; BroadcastReceiver brReceiver; public static final String BROADCAST_ACTION = "ACTION"; public static final String IM_NAME = "pic.jpg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); errorText = (TextView) findViewById(R.id.text_error); image = (ImageView) findViewById(R.id.image); delete = (Button) findViewById(R.id.delete); delete.setOnClickListener(onButton); display(); brReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { display(); } }; imReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { context.startService(new Intent(context, MyService.class)); } }; registerReceiver(imReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); registerReceiver(brReceiver, new IntentFilter(BROADCAST_ACTION)); } public void display() { File file = new File(getFilesDir(), IM_NAME); if (file.exists()) { errorText.setVisibility(View.GONE); image.setVisibility(View.VISIBLE); image.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath())); } else{ errorText.setVisibility(View.VISIBLE); image.setVisibility(View.GONE); } } View.OnClickListener onButton = new View.OnClickListener() { @Override public void onClick(View view) { File file = new File(getFilesDir(), IM_NAME); if(file.exists()) { file.delete(); display(); } } }; @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(imReceiver); unregisterReceiver(brReceiver); } }
2,792
0.623209
0.619628
94
27.702127
22.134901
83
false
false
0
0
0
0
0
0
0.574468
false
false
11
67ec7f7d5ba3e5a27d51824ed73f4ff3b86627a3
601,295,451,649
0f00d9730750ba7e0018784d8fea7a928c01a593
/src/main/java/com/mecby/base/base/BaseApplication.java
b6f3f23d580c1e7d12d81a43662f89427d83f66e
[]
no_license
yangqqq537/MVP_BaseLibrary
https://github.com/yangqqq537/MVP_BaseLibrary
3caeb4d9cc416d7a0ac19c26400f83bb7a4d0cb2
3c34dc1d9524fab6298af0052f30bd1b11237fc4
refs/heads/master
2021-04-26T23:28:47.655000
2018-03-06T02:00:05
2018-03-06T02:00:05
124,002,433
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mecby.base.base; import android.app.Activity; import android.app.Application; import com.alibaba.android.arouter.launcher.ARouter; import com.mecby.base.net.CustomSignInterceptor; import com.mecby.base.net.img.LoaderManager; import com.mecby.base.net.img.PicassoLoader; import com.mecby.base.utils.Logger; import com.zhouyou.http.EasyHttp; import com.zhouyou.http.cache.converter.SerializableDiskConverter; /** * Created by jerry on 2017/8/8 0008. * */ public abstract class BaseApplication extends Application { private static BaseApplication sInstance; public static BaseApplication getInstance() { return sInstance; } private Activity app_activity = null; @Override public void onCreate() { super.onCreate(); sInstance = this; //外部定制图片框架,可定制,默认glide LoaderManager.setLoader(new PicassoLoader()); //LoaderManager.getLoader().init(this); //读取缓存用户信息,配置信息 CacheManager.getInstance().loadContext(this).loadUserInfo().loadConfigInfo(); initArouter(); initHttp(); /* registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { app_activity=activity; } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { } @Override public void onActivityPaused(Activity activity) { } @Override public void onActivityStopped(Activity activity) { } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { app_activity=null; } });*/ } /** * 公开方法,外部可通过 MyApplication.getInstance().getCurrentActivity() 获取到当前最上层的activity */ public Activity getCurrentActivity() { return app_activity; } private void initHttp() { EasyHttp.init(this); EasyHttp.getInstance() .debug("base", Logger.DEBUG ? true : false) .setReadTimeOut(30 * 1000) .setWriteTimeOut(30 * 1000) .setConnectTimeout(30 * 1000) .setRetryCount(0)//默认网络不好自动重试1次 .setRetryDelay(500)//每次延时500ms重试 .setRetryIncreaseDelay(500)//每次延时叠加500ms .setBaseUrl(getBaseUrl()) .setCacheDiskConverter(new SerializableDiskConverter())//默认缓存使用序列化转化 .setCertificates()//信任所有证书 .addInterceptor(new CustomSignInterceptor());//添加参数签名拦截器 //.addCommonHeaders(AppUtils.getHeaderMap())//设置全局公共头 //.addCommonParams(params)//设置全局公共参数 //.addInterceptor(new HeTInterceptor());//处理自己业务的拦截器 } public abstract String getBaseUrl(); private void initArouter() { if(Logger.DEBUG){ ARouter.openLog(); ARouter.openDebug(); } ARouter.init(this); } }
UTF-8
Java
3,542
java
BaseApplication.java
Java
[ { "context": "rter.SerializableDiskConverter;\n\n/**\n * Created by jerry on 2017/8/8 0008.\n *\n */\n\npublic abstract class B", "end": 445, "score": 0.9990065097808838, "start": 440, "tag": "USERNAME", "value": "jerry" } ]
null
[]
package com.mecby.base.base; import android.app.Activity; import android.app.Application; import com.alibaba.android.arouter.launcher.ARouter; import com.mecby.base.net.CustomSignInterceptor; import com.mecby.base.net.img.LoaderManager; import com.mecby.base.net.img.PicassoLoader; import com.mecby.base.utils.Logger; import com.zhouyou.http.EasyHttp; import com.zhouyou.http.cache.converter.SerializableDiskConverter; /** * Created by jerry on 2017/8/8 0008. * */ public abstract class BaseApplication extends Application { private static BaseApplication sInstance; public static BaseApplication getInstance() { return sInstance; } private Activity app_activity = null; @Override public void onCreate() { super.onCreate(); sInstance = this; //外部定制图片框架,可定制,默认glide LoaderManager.setLoader(new PicassoLoader()); //LoaderManager.getLoader().init(this); //读取缓存用户信息,配置信息 CacheManager.getInstance().loadContext(this).loadUserInfo().loadConfigInfo(); initArouter(); initHttp(); /* registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { app_activity=activity; } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { } @Override public void onActivityPaused(Activity activity) { } @Override public void onActivityStopped(Activity activity) { } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { app_activity=null; } });*/ } /** * 公开方法,外部可通过 MyApplication.getInstance().getCurrentActivity() 获取到当前最上层的activity */ public Activity getCurrentActivity() { return app_activity; } private void initHttp() { EasyHttp.init(this); EasyHttp.getInstance() .debug("base", Logger.DEBUG ? true : false) .setReadTimeOut(30 * 1000) .setWriteTimeOut(30 * 1000) .setConnectTimeout(30 * 1000) .setRetryCount(0)//默认网络不好自动重试1次 .setRetryDelay(500)//每次延时500ms重试 .setRetryIncreaseDelay(500)//每次延时叠加500ms .setBaseUrl(getBaseUrl()) .setCacheDiskConverter(new SerializableDiskConverter())//默认缓存使用序列化转化 .setCertificates()//信任所有证书 .addInterceptor(new CustomSignInterceptor());//添加参数签名拦截器 //.addCommonHeaders(AppUtils.getHeaderMap())//设置全局公共头 //.addCommonParams(params)//设置全局公共参数 //.addInterceptor(new HeTInterceptor());//处理自己业务的拦截器 } public abstract String getBaseUrl(); private void initArouter() { if(Logger.DEBUG){ ARouter.openLog(); ARouter.openDebug(); } ARouter.init(this); } }
3,542
0.607381
0.594676
116
27.5
24.562902
89
false
false
0
0
0
0
0
0
0.318966
false
false
11
2bc98bca8c0ca8274c25c359a81207fee35823a0
35,304,631,226,697
2c04d1d23d498e68a35f8793716a1ccd6d79e07c
/lib-jvm/src/main/java/com/riseofcat/lib/UnitTest.java
51c07d442b832fe6e5f93c99290e5491e2537f09
[]
no_license
riseofcat/mass-power-server
https://github.com/riseofcat/mass-power-server
6f4f1ebede48df01582518a8dd01c1ef03051759
cb5c5accf6afd80191a9145d3a637e167a2f4ed0
refs/heads/master
2021-04-27T12:49:07.296000
2018-05-28T18:22:06
2018-05-28T18:22:06
122,427,206
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.riseofcat.lib; public class UnitTest { public static void main(String[] args) { try { String ls = LibAll.nativeCmd("ls").execute().resultStr; breakpoint(); } catch(Exception e) { e.printStackTrace(); } breakpoint(); boolean ip = com.riseofcat.lib_gwt.LibAllGwt.isIp("127.0.0.1"); boolean ip2 = com.riseofcat.lib_gwt.LibAllGwt.isIp("a127.0.0.1"); breakpoint(); String s = com.riseofcat.lib_gwt.LibAllGwt.putStrArgs("my name is {name}", new com.riseofcat.lib_gwt.LibAllGwt.StrArgs().put("name", "Bobr")); LibAll.HttpRequest.Response response = LibAll.request("http://127.0.0.1:54322/jre?action=start").body("{\"redundant\":0}").post(); breakpoint(); } public static void breakpoint() { int a = 1 + 1; } }
UTF-8
Java
735
java
UnitTest.java
Java
[ { "context": "oolean ip = com.riseofcat.lib_gwt.LibAllGwt.isIp(\"127.0.0.1\");\n\tboolean ip2 = com.riseofcat.lib_gwt.LibAllGwt", "end": 300, "score": 0.9996219277381897, "start": 291, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "lean ip2 = com.riseofcat.lib_gwt.LibAllG...
null
[]
package com.riseofcat.lib; public class UnitTest { public static void main(String[] args) { try { String ls = LibAll.nativeCmd("ls").execute().resultStr; breakpoint(); } catch(Exception e) { e.printStackTrace(); } breakpoint(); boolean ip = com.riseofcat.lib_gwt.LibAllGwt.isIp("127.0.0.1"); boolean ip2 = com.riseofcat.lib_gwt.LibAllGwt.isIp("a127.0.0.1"); breakpoint(); String s = com.riseofcat.lib_gwt.LibAllGwt.putStrArgs("my name is {name}", new com.riseofcat.lib_gwt.LibAllGwt.StrArgs().put("name", "Bobr")); LibAll.HttpRequest.Response response = LibAll.request("http://127.0.0.1:54322/jre?action=start").body("{\"redundant\":0}").post(); breakpoint(); } public static void breakpoint() { int a = 1 + 1; } }
735
0.692517
0.655782
24
29.625
37.768829
143
false
false
0
0
0
0
0
0
1.291667
false
false
11
5d1b9d106c2b9cc3cb8c2314bf228d8b301eaccf
38,981,123,216,641
dadb78a28eba6d831fff3749016ef3747a941355
/SupMarket/build/generated-sources/ap-source-output/com/supinfo/supmarket/entity/Users_.java
b5a9e4edd8162fca5149f5c421e7cad133372f92
[]
no_license
schatteleyn/SupMarket
https://github.com/schatteleyn/SupMarket
836f811de2b87cfd6134cf563793045892efaad6
3d77afc9b2b6e1c717e6f1a48561b43bcb6ee9f2
refs/heads/master
2020-04-20T13:04:55.281000
2013-05-30T09:11:55
2013-05-30T09:11:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.supinfo.supmarket.entity; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.3.2.v20111125-r10461", date="2013-03-23T18:52:45") @StaticMetamodel(Users.class) public class Users_ { public static volatile SingularAttribute<Users, Long> id; public static volatile SingularAttribute<Users, String> email; public static volatile SingularAttribute<Users, String> password; }
UTF-8
Java
519
java
Users_.java
Java
[]
null
[]
package com.supinfo.supmarket.entity; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.3.2.v20111125-r10461", date="2013-03-23T18:52:45") @StaticMetamodel(Users.class) public class Users_ { public static volatile SingularAttribute<Users, Long> id; public static volatile SingularAttribute<Users, String> email; public static volatile SingularAttribute<Users, String> password; }
519
0.801541
0.743738
15
33.666668
28.072922
82
false
false
0
0
0
0
0
0
0.733333
false
false
11
850ffc427da0b19810d5518d5711536399fed2de
38,981,123,217,429
fbd14bb19e81908f4bbbe5ac571912813edf7a23
/IssueResolver/src/main/java/com/shonowo/resolver/model/Issue.java
aba8c46cac113e8559f774d358cf5f75a873ce71
[]
no_license
ishonowo/issueresolver
https://github.com/ishonowo/issueresolver
5512a7ad5feb5de224da7431dd571416554ba9ed
8e2e93d67c27edf11d0881c305bf0ee367aa7908
refs/heads/master
2020-04-14T09:35:05.396000
2019-01-01T20:38:51
2019-01-01T20:38:51
163,763,395
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shonowo.resolver.model; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Issue { @GeneratedValue(strategy=GenerationType.IDENTITY) @Id private Long issueId; private String terminalId; private String issueDesc; private String logger; private String loggerEmail; private String loggerPhoneNo; private Date logDate; private String supportEmail; private String contact; private String branchEmail; private String branchName; private String atmName; private String physical_address; private String vendor; @Override public String toString() { return "Issue [issueId=" + issueId + ", terminalId=" + terminalId + ", issueDesc=" + issueDesc + ", logger=" + logger + ", loggerEmail=" + loggerEmail + ", loggerPhoneNo=" + loggerPhoneNo + ", logDate=" + logDate + ", supportEmail=" + supportEmail + ", contact=" + contact + ", branchEmail=" + branchEmail + ", branchName=" + branchName + ", atmName=" + atmName + ", physical_address=" + physical_address + ", vendor=" + vendor + "]"; } public Issue() { } public Issue(String terminalId, String issueDesc, String logger, String loggerEmail, String loggerPhoneNo, Date logDate, String supportEmail, String contact, String branchEmail, String branchName, String atmName, String physical_address, String vendor) { this.terminalId = terminalId; this.issueDesc = issueDesc; this.logger = logger; this.loggerEmail = loggerEmail; this.loggerPhoneNo = loggerPhoneNo; this.logDate = logDate; this.supportEmail = supportEmail; this.contact = contact; this.branchEmail = branchEmail; this.branchName = branchName; this.atmName = atmName; this.physical_address = physical_address; this.vendor = vendor; } public Long getIssueId() { return issueId; } public void setIssueId(Long issueId) { this.issueId = issueId; } public String getTerminalId() { return terminalId; } public void setTerminalId(String terminalId) { this.terminalId = terminalId; } public String getIssueDesc() { return issueDesc; } public void setIssueDesc(String issueDesc) { this.issueDesc = issueDesc; } public String getLogger() { return logger; } public void setLogger(String logger) { this.logger = logger; } public String getLoggerEmail() { return loggerEmail; } public void setLoggerEmail(String loggerEmail) { this.loggerEmail = loggerEmail; } public String getLoggerPhoneNo() { return loggerPhoneNo; } public void setLoggerPhoneNo(String loggerPhoneNo) { this.loggerPhoneNo = loggerPhoneNo; } public Date getLogDate() { return logDate; } public void setLogDate(Date logDate) { this.logDate = logDate; } public String getSupportEmail() { return supportEmail; } public void setSupportEmail(String supportEmail) { this.supportEmail = supportEmail; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getBranchEmail() { return branchEmail; } public void setBranchEmail(String branchEmail) { this.branchEmail = branchEmail; } public String getBranchName() { return branchName; } public void setBranchName(String branchName) { this.branchName = branchName; } public String getAtmName() { return atmName; } public void setAtmName(String atmName) { this.atmName = atmName; } public String getPhysical_address() { return physical_address; } public void setPhysical_address(String physical_address) { this.physical_address = physical_address; } public String getVendor() { return vendor; } public void setVendor(String vendor) { this.vendor = vendor; } }
UTF-8
Java
3,982
java
Issue.java
Java
[]
null
[]
package com.shonowo.resolver.model; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Issue { @GeneratedValue(strategy=GenerationType.IDENTITY) @Id private Long issueId; private String terminalId; private String issueDesc; private String logger; private String loggerEmail; private String loggerPhoneNo; private Date logDate; private String supportEmail; private String contact; private String branchEmail; private String branchName; private String atmName; private String physical_address; private String vendor; @Override public String toString() { return "Issue [issueId=" + issueId + ", terminalId=" + terminalId + ", issueDesc=" + issueDesc + ", logger=" + logger + ", loggerEmail=" + loggerEmail + ", loggerPhoneNo=" + loggerPhoneNo + ", logDate=" + logDate + ", supportEmail=" + supportEmail + ", contact=" + contact + ", branchEmail=" + branchEmail + ", branchName=" + branchName + ", atmName=" + atmName + ", physical_address=" + physical_address + ", vendor=" + vendor + "]"; } public Issue() { } public Issue(String terminalId, String issueDesc, String logger, String loggerEmail, String loggerPhoneNo, Date logDate, String supportEmail, String contact, String branchEmail, String branchName, String atmName, String physical_address, String vendor) { this.terminalId = terminalId; this.issueDesc = issueDesc; this.logger = logger; this.loggerEmail = loggerEmail; this.loggerPhoneNo = loggerPhoneNo; this.logDate = logDate; this.supportEmail = supportEmail; this.contact = contact; this.branchEmail = branchEmail; this.branchName = branchName; this.atmName = atmName; this.physical_address = physical_address; this.vendor = vendor; } public Long getIssueId() { return issueId; } public void setIssueId(Long issueId) { this.issueId = issueId; } public String getTerminalId() { return terminalId; } public void setTerminalId(String terminalId) { this.terminalId = terminalId; } public String getIssueDesc() { return issueDesc; } public void setIssueDesc(String issueDesc) { this.issueDesc = issueDesc; } public String getLogger() { return logger; } public void setLogger(String logger) { this.logger = logger; } public String getLoggerEmail() { return loggerEmail; } public void setLoggerEmail(String loggerEmail) { this.loggerEmail = loggerEmail; } public String getLoggerPhoneNo() { return loggerPhoneNo; } public void setLoggerPhoneNo(String loggerPhoneNo) { this.loggerPhoneNo = loggerPhoneNo; } public Date getLogDate() { return logDate; } public void setLogDate(Date logDate) { this.logDate = logDate; } public String getSupportEmail() { return supportEmail; } public void setSupportEmail(String supportEmail) { this.supportEmail = supportEmail; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getBranchEmail() { return branchEmail; } public void setBranchEmail(String branchEmail) { this.branchEmail = branchEmail; } public String getBranchName() { return branchName; } public void setBranchName(String branchName) { this.branchName = branchName; } public String getAtmName() { return atmName; } public void setAtmName(String atmName) { this.atmName = atmName; } public String getPhysical_address() { return physical_address; } public void setPhysical_address(String physical_address) { this.physical_address = physical_address; } public String getVendor() { return vendor; } public void setVendor(String vendor) { this.vendor = vendor; } }
3,982
0.694626
0.694626
176
20.625
22.538509
121
false
false
0
0
0
0
0
0
1.573864
false
false
11
f0b602b7c9849a35e3d12688aab4a78e6878f25a
15,101,105,078,249
26d7f969f754b0027cfa2763fb80cedb247684f9
/kafka/src/main/java/kafka/etl/KafkaETLMapper.java
9d9e00141079666f20f8d44f3315495ed247903f
[ "Apache-2.0" ]
permissive
ymasory/scala-corpus
https://github.com/ymasory/scala-corpus
19ae8f4a5eb6231f01dbde0e5b5cfe36c3845505
e79fc959cd918959d8d8b5d9fdf4a3dc183f1121
refs/heads/master
2020-05-18T03:48:53.359000
2011-04-27T04:32:29
2011-04-27T04:32:29
1,190,930
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2010 LinkedIn * * 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 kafka.etl; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import kafka.api.FetchRequest; import kafka.api.MultiFetchResponse; import kafka.api.OffsetRequest; import kafka.common.ErrorMapping; import kafka.consumer.SimpleConsumer; import kafka.message.ByteBufferMessageSet; import kafka.message.Message; import kafka.message.MessageSet; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.lib.MultipleOutputs; import static kafka.api.OffsetRequest.*; /** * KafkaETL mapper * * input -- text in the following format node:topic:partition:offset * * output -- there are two types of outputs * 1. intermediate output to reducers: * key: KafkaETLKey (timestamp, partition) value: BytesWritable * 2. final output: offsets in the following format node:topic:partition:offset * */ @SuppressWarnings("deprecation") public abstract class KafkaETLMapper implements Mapper<LongWritable, Text, KafkaETLKey, BytesWritable> { static protected int MAX_RETRY_TIME = 1; protected Props _props; protected int _bufferSize; protected int _soTimeout; protected Map<Integer, URI> _nodes; protected int _partition; protected int _nodeId; protected String _topic; protected SimpleConsumer _consumer; protected MultipleOutputs _mos; protected OutputCollector<Text, Text> _offsetOut = null; protected long[] _offsetRange; protected long _startOffset; protected long _offset; protected boolean _toContinue = true; protected int _retry; protected long _timestamp; protected long _count; protected boolean _ignoreErrors = false; protected DateUtils.TimeGranularity _granularity; public static enum Status { OUTPUT_AND_CONTINUE, OUTPUT_AND_BREAK, CONTINUE, BREAK }; /** * Called by the default implementation of {@link #map} to reset members * based on input. */ protected void reset(String input) throws IOException { // read topic and current offset from input String[] pieces = input.trim().split( KafkaETLCommons.getOffsetFieldDelim()); if (pieces.length != 4) throw new IOException( input + " : input must be in the form 'node:topic:partition:offset'"); String topic = pieces[1]; if (!topic.equalsIgnoreCase(_topic)) { System.out.println("This job only accepts topic " + _topic + ". Ignore topic:" + topic); return; } _partition = Integer.valueOf(pieces[2]); _nodeId = Integer.valueOf(pieces[0]); if (!_nodes.containsKey(_nodeId)) throw new IOException( input + " : invalid node id in offset file--no host information found"); URI node = _nodes.get(_nodeId); // read data from queue _consumer = new SimpleConsumer(node.getHost(), node.getPort(), _soTimeout, _bufferSize); // get available offset range _offsetRange = getOffsetRange(_consumer, topic, _partition, input); String offsetStr = pieces[3]; _startOffset = getStartOffset(input, offsetStr, _offsetRange); System.out.println("Connected to node " + _nodeId + " at " + node + " beginning reading at offset " + _startOffset + " latest offset=" + _offsetRange[1]); _offset = _startOffset; _retry = 0; _toContinue = true; _timestamp = 0; _count = 0; } /** * Called by the default implementation of {@link #map} to determine * stopping condition. The default implementation is to stop when reaching * the maximum offset. May be overridden with alternative logic. */ protected boolean toContinue() { return _toContinue && _offset < _offsetRange[1] && _retry < MAX_RETRY_TIME; } /** * Called by the default implementation of {@link #map} to get timestamp * from message. Need to be implemented by sub-class. */ abstract protected long getTimestamp(Message message) throws IOException; /** * Called by the default implementation of {@link #map} to get percentage of * completeness (to be shown in job tracker). Need to be implemented by * sub-class. */ abstract protected float getProgress(); /** * Called by the default implementation of {@link #map} to determine whether * to output message and continue. Accepts following status: * OUTPUT_AND_CONTINUE, OUTPUT_AND_BREAK, CONTINUE, BREAK Need to be * implemented by sub-class. */ abstract protected Status getStatus(Message message, Reporter reporter); @Override @SuppressWarnings("unchecked") public void map(LongWritable key, Text val, OutputCollector<KafkaETLKey, BytesWritable> collector, Reporter reporter) throws IOException { String input = val.toString(); System.out.println("input=" + input); reset(input); long startTime = System.currentTimeMillis(); long requestTime = 0, tempTime = 0; long decodeTime = 0; // , tempDecodeTime = 0; long outputTime = 0; // , tempOutputTime = 0; while (toContinue()) { // fetch data using multi-fetch interfaces // TODO: change to high-level interface once it supports "reset" FetchRequest fetchRequest = new FetchRequest(_topic, _partition, _offset, _bufferSize); List<FetchRequest> array = new ArrayList<FetchRequest>(); array.add(fetchRequest); tempTime = System.currentTimeMillis(); MultiFetchResponse response = _consumer.multifetch(array); requestTime += (System.currentTimeMillis() - tempTime); while (response.hasNext()) { ByteBufferMessageSet messages = response.next(); // check error codes _toContinue = checkErrorCode(messages, input); if (!_toContinue) break; Iterator<Message> iter = (Iterator<Message>) messages .iterator(); long messageOffset = 0; while (iter.hasNext()) { Message message = iter.next(); messageOffset += MessageSet.entrySize(message); reporter.incrCounter("topic-counters", _topic, 1); _count++; try { tempTime = System.currentTimeMillis(); _timestamp = getTimestamp(message); decodeTime += (System.currentTimeMillis() - tempTime); } catch (IOException e) { System.err.println("SetOffset=" + _offset + "messageOffset=" + messageOffset + ": ignore message with exception: "); if (_ignoreErrors) { reporter.incrCounter(_topic, _topic + "_PARSING_ERROR", 1); continue; } else { e.printStackTrace(System.err); throw e; } } // determine whether to stop Status status = getStatus(message, reporter); // generate output switch (status) { case OUTPUT_AND_CONTINUE: case OUTPUT_AND_BREAK: tempTime = System.currentTimeMillis(); ByteBuffer buffer = message.payload(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes, buffer.position(), bytes.length); collector.collect(new KafkaETLKey(_timestamp, _granularity), new BytesWritable(bytes)); outputTime += (System.currentTimeMillis() - tempTime); } // report progress float percentage = getProgress(); reporter.setStatus("collected " + percentage + "%"); switch (status) { case OUTPUT_AND_BREAK: case BREAK: break; } } _offset += messages.validBytes(); } } _consumer.close(); long endTime = System.currentTimeMillis(); // output offsets // Note: name can only contain chars and numbers String offsetName = _nodeId + _topic + _partition; Text offsetText = new Text(KafkaETLCommons.getOffset( Integer.toString(_nodeId), _topic, _partition, _offset)); if (_offsetOut == null) _offsetOut = _mos.getCollector("offset", offsetName, reporter); _offsetOut.collect(null, offsetText); // now record some stats double secondsEllapsed = (endTime - startTime) / 1000.0; reporter.incrCounter(_topic, "total-time(ms)", (endTime - startTime) ); reporter.incrCounter(_topic, "request-time(ms)", requestTime); reporter.incrCounter(_topic, "decode-time(ms)", decodeTime); reporter.incrCounter(_topic, "output-time(ms)", outputTime); long bytesRead = _offset - _startOffset; reporter.incrCounter(_topic, "bytes-read", (long) bytesRead); double bytesPerSec = bytesRead / secondsEllapsed; NumberFormat format = NumberFormat.getInstance(); format.setMaximumFractionDigits(2); System.out.println("Completed reading at offset " + _offset + " for node " + _nodeId + " on " + _nodes.get(_nodeId).toString()); double megabytes = bytesPerSec / (1024.0 * 1024.0); System.out.println("Read " + bytesRead + " bytes in " + ((int) secondsEllapsed) + " seconds (" + format.format(megabytes) + " MB/sec)"); System.out .println("count\tbytesRead\ttotalTime(ms)\trequestTime(ms)\tdecodeTime(ms)\toutputTime(ms)"); System.out.println(_count + "\t" + bytesRead + "\t" + (endTime - startTime) + "\t" + requestTime + "\t" + decodeTime + "\t" + outputTime); } /** * Called by the default implementation of {@link #map} to check error code * to determine whether to continue. */ protected boolean checkErrorCode(ByteBufferMessageSet messages, String input) throws IOException { int errorCode = messages.errorCOde(); if (errorCode == ErrorMapping.OFFSET_OUT_OF_RANGE_CODE()) { // offset cannot cross the maximum offset (guaranteed by Kafka // protocol) // Kafka server may delete old files from time to time System.err.println("WARNING: current offset=" + _offset + ". It is out of range."); if (_retry >= MAX_RETRY_TIME) return false; _retry++; // get the current offset range _offsetRange = getOffsetRange(_consumer, _topic, _partition, input); _offset = _startOffset = _offsetRange[0]; return true; } else if (errorCode == ErrorMapping.INVALID_MESSAGE_CODE()) { throw new IOException(input + " current offset=" + _offset + " : invalid offset."); } else if (errorCode == ErrorMapping.WRONG_PARTITION_CODE()) { throw new IOException(input + " : wrong partition"); } else if (errorCode != ErrorMapping.NO_ERROR()) { throw new IOException(input + " current offset=" + _offset + " error:" + errorCode); } else return true; } /** * Get offset ranges * */ protected long[] getOffsetRange(SimpleConsumer consumer, String topic, int partition, String input) throws IOException { long[] range = new long[2]; long[] offsets = consumer.getOffsetsBefore(topic, partition, OffsetRequest.EARLIEST_TIME(), 1); if (offsets.length != 1) throw new IOException("input:" + input + " Expect one smallest offset"); range[0] = offsets[0]; offsets = consumer.getOffsetsBefore(topic, partition, OffsetRequest.LATEST_TIME(), 1); if (offsets.length != 1) throw new IOException("input:" + input + " Expect one latest offset"); range[1] = offsets[0]; return range; } /** * Get start offset */ protected long getStartOffset(String input, String offsetStr, long[] range) throws IOException { if (offsetStr.equalsIgnoreCase("smallest")) { return range[0]; } else { Long start = Long.parseLong(offsetStr); if (start > range[1]) { throw new IOException("input:" + input + " start offset is larger than latest one:" + range[1]); } else if (start < range[0]) { System.err.println("WARNING: input:" + input + " start_offset is smaller than smallest_offset:" + range[0] + ". Will use the samllest instead."); return range[0]; } else { return start; } } } @Override public void close() throws IOException { _mos.close(); } @Override public void configure(JobConf conf) { try { _props = KafkaETLUtils.getPropsFromJob(conf); String nodePath = KafkaETLCommons.getNodesPath(_props); Props nodesProps = KafkaETLUtils.readProps(nodePath); System.out.println(nodesProps); _nodes = new HashMap<Integer, URI>(); for (String key : nodesProps.stringPropertyNames()) { _nodes.put(Integer.parseInt(key),nodesProps.getUri(key)); } _bufferSize = KafkaETLCommons.getClientBufferSize(_props); _soTimeout = KafkaETLCommons.getClientTimeout(_props); System.out.println("bufferSize=" + _bufferSize); System.out.println("timeout=" + _soTimeout); _granularity = KafkaETLCommons.getGranularity(_props); _topic = KafkaETLCommons.getTopic(_props); System.out.println("topic=" + _topic); _mos = new MultipleOutputs(conf); _ignoreErrors = _props.getBoolean(KafkaETLCommons.IGNORE_ERRORS, false); } catch (Exception e) { throw new RuntimeException(e); } } }
UTF-8
Java
13,415
java
KafkaETLMapper.java
Java
[]
null
[]
/* * Copyright 2010 LinkedIn * * 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 kafka.etl; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import kafka.api.FetchRequest; import kafka.api.MultiFetchResponse; import kafka.api.OffsetRequest; import kafka.common.ErrorMapping; import kafka.consumer.SimpleConsumer; import kafka.message.ByteBufferMessageSet; import kafka.message.Message; import kafka.message.MessageSet; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.lib.MultipleOutputs; import static kafka.api.OffsetRequest.*; /** * KafkaETL mapper * * input -- text in the following format node:topic:partition:offset * * output -- there are two types of outputs * 1. intermediate output to reducers: * key: KafkaETLKey (timestamp, partition) value: BytesWritable * 2. final output: offsets in the following format node:topic:partition:offset * */ @SuppressWarnings("deprecation") public abstract class KafkaETLMapper implements Mapper<LongWritable, Text, KafkaETLKey, BytesWritable> { static protected int MAX_RETRY_TIME = 1; protected Props _props; protected int _bufferSize; protected int _soTimeout; protected Map<Integer, URI> _nodes; protected int _partition; protected int _nodeId; protected String _topic; protected SimpleConsumer _consumer; protected MultipleOutputs _mos; protected OutputCollector<Text, Text> _offsetOut = null; protected long[] _offsetRange; protected long _startOffset; protected long _offset; protected boolean _toContinue = true; protected int _retry; protected long _timestamp; protected long _count; protected boolean _ignoreErrors = false; protected DateUtils.TimeGranularity _granularity; public static enum Status { OUTPUT_AND_CONTINUE, OUTPUT_AND_BREAK, CONTINUE, BREAK }; /** * Called by the default implementation of {@link #map} to reset members * based on input. */ protected void reset(String input) throws IOException { // read topic and current offset from input String[] pieces = input.trim().split( KafkaETLCommons.getOffsetFieldDelim()); if (pieces.length != 4) throw new IOException( input + " : input must be in the form 'node:topic:partition:offset'"); String topic = pieces[1]; if (!topic.equalsIgnoreCase(_topic)) { System.out.println("This job only accepts topic " + _topic + ". Ignore topic:" + topic); return; } _partition = Integer.valueOf(pieces[2]); _nodeId = Integer.valueOf(pieces[0]); if (!_nodes.containsKey(_nodeId)) throw new IOException( input + " : invalid node id in offset file--no host information found"); URI node = _nodes.get(_nodeId); // read data from queue _consumer = new SimpleConsumer(node.getHost(), node.getPort(), _soTimeout, _bufferSize); // get available offset range _offsetRange = getOffsetRange(_consumer, topic, _partition, input); String offsetStr = pieces[3]; _startOffset = getStartOffset(input, offsetStr, _offsetRange); System.out.println("Connected to node " + _nodeId + " at " + node + " beginning reading at offset " + _startOffset + " latest offset=" + _offsetRange[1]); _offset = _startOffset; _retry = 0; _toContinue = true; _timestamp = 0; _count = 0; } /** * Called by the default implementation of {@link #map} to determine * stopping condition. The default implementation is to stop when reaching * the maximum offset. May be overridden with alternative logic. */ protected boolean toContinue() { return _toContinue && _offset < _offsetRange[1] && _retry < MAX_RETRY_TIME; } /** * Called by the default implementation of {@link #map} to get timestamp * from message. Need to be implemented by sub-class. */ abstract protected long getTimestamp(Message message) throws IOException; /** * Called by the default implementation of {@link #map} to get percentage of * completeness (to be shown in job tracker). Need to be implemented by * sub-class. */ abstract protected float getProgress(); /** * Called by the default implementation of {@link #map} to determine whether * to output message and continue. Accepts following status: * OUTPUT_AND_CONTINUE, OUTPUT_AND_BREAK, CONTINUE, BREAK Need to be * implemented by sub-class. */ abstract protected Status getStatus(Message message, Reporter reporter); @Override @SuppressWarnings("unchecked") public void map(LongWritable key, Text val, OutputCollector<KafkaETLKey, BytesWritable> collector, Reporter reporter) throws IOException { String input = val.toString(); System.out.println("input=" + input); reset(input); long startTime = System.currentTimeMillis(); long requestTime = 0, tempTime = 0; long decodeTime = 0; // , tempDecodeTime = 0; long outputTime = 0; // , tempOutputTime = 0; while (toContinue()) { // fetch data using multi-fetch interfaces // TODO: change to high-level interface once it supports "reset" FetchRequest fetchRequest = new FetchRequest(_topic, _partition, _offset, _bufferSize); List<FetchRequest> array = new ArrayList<FetchRequest>(); array.add(fetchRequest); tempTime = System.currentTimeMillis(); MultiFetchResponse response = _consumer.multifetch(array); requestTime += (System.currentTimeMillis() - tempTime); while (response.hasNext()) { ByteBufferMessageSet messages = response.next(); // check error codes _toContinue = checkErrorCode(messages, input); if (!_toContinue) break; Iterator<Message> iter = (Iterator<Message>) messages .iterator(); long messageOffset = 0; while (iter.hasNext()) { Message message = iter.next(); messageOffset += MessageSet.entrySize(message); reporter.incrCounter("topic-counters", _topic, 1); _count++; try { tempTime = System.currentTimeMillis(); _timestamp = getTimestamp(message); decodeTime += (System.currentTimeMillis() - tempTime); } catch (IOException e) { System.err.println("SetOffset=" + _offset + "messageOffset=" + messageOffset + ": ignore message with exception: "); if (_ignoreErrors) { reporter.incrCounter(_topic, _topic + "_PARSING_ERROR", 1); continue; } else { e.printStackTrace(System.err); throw e; } } // determine whether to stop Status status = getStatus(message, reporter); // generate output switch (status) { case OUTPUT_AND_CONTINUE: case OUTPUT_AND_BREAK: tempTime = System.currentTimeMillis(); ByteBuffer buffer = message.payload(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes, buffer.position(), bytes.length); collector.collect(new KafkaETLKey(_timestamp, _granularity), new BytesWritable(bytes)); outputTime += (System.currentTimeMillis() - tempTime); } // report progress float percentage = getProgress(); reporter.setStatus("collected " + percentage + "%"); switch (status) { case OUTPUT_AND_BREAK: case BREAK: break; } } _offset += messages.validBytes(); } } _consumer.close(); long endTime = System.currentTimeMillis(); // output offsets // Note: name can only contain chars and numbers String offsetName = _nodeId + _topic + _partition; Text offsetText = new Text(KafkaETLCommons.getOffset( Integer.toString(_nodeId), _topic, _partition, _offset)); if (_offsetOut == null) _offsetOut = _mos.getCollector("offset", offsetName, reporter); _offsetOut.collect(null, offsetText); // now record some stats double secondsEllapsed = (endTime - startTime) / 1000.0; reporter.incrCounter(_topic, "total-time(ms)", (endTime - startTime) ); reporter.incrCounter(_topic, "request-time(ms)", requestTime); reporter.incrCounter(_topic, "decode-time(ms)", decodeTime); reporter.incrCounter(_topic, "output-time(ms)", outputTime); long bytesRead = _offset - _startOffset; reporter.incrCounter(_topic, "bytes-read", (long) bytesRead); double bytesPerSec = bytesRead / secondsEllapsed; NumberFormat format = NumberFormat.getInstance(); format.setMaximumFractionDigits(2); System.out.println("Completed reading at offset " + _offset + " for node " + _nodeId + " on " + _nodes.get(_nodeId).toString()); double megabytes = bytesPerSec / (1024.0 * 1024.0); System.out.println("Read " + bytesRead + " bytes in " + ((int) secondsEllapsed) + " seconds (" + format.format(megabytes) + " MB/sec)"); System.out .println("count\tbytesRead\ttotalTime(ms)\trequestTime(ms)\tdecodeTime(ms)\toutputTime(ms)"); System.out.println(_count + "\t" + bytesRead + "\t" + (endTime - startTime) + "\t" + requestTime + "\t" + decodeTime + "\t" + outputTime); } /** * Called by the default implementation of {@link #map} to check error code * to determine whether to continue. */ protected boolean checkErrorCode(ByteBufferMessageSet messages, String input) throws IOException { int errorCode = messages.errorCOde(); if (errorCode == ErrorMapping.OFFSET_OUT_OF_RANGE_CODE()) { // offset cannot cross the maximum offset (guaranteed by Kafka // protocol) // Kafka server may delete old files from time to time System.err.println("WARNING: current offset=" + _offset + ". It is out of range."); if (_retry >= MAX_RETRY_TIME) return false; _retry++; // get the current offset range _offsetRange = getOffsetRange(_consumer, _topic, _partition, input); _offset = _startOffset = _offsetRange[0]; return true; } else if (errorCode == ErrorMapping.INVALID_MESSAGE_CODE()) { throw new IOException(input + " current offset=" + _offset + " : invalid offset."); } else if (errorCode == ErrorMapping.WRONG_PARTITION_CODE()) { throw new IOException(input + " : wrong partition"); } else if (errorCode != ErrorMapping.NO_ERROR()) { throw new IOException(input + " current offset=" + _offset + " error:" + errorCode); } else return true; } /** * Get offset ranges * */ protected long[] getOffsetRange(SimpleConsumer consumer, String topic, int partition, String input) throws IOException { long[] range = new long[2]; long[] offsets = consumer.getOffsetsBefore(topic, partition, OffsetRequest.EARLIEST_TIME(), 1); if (offsets.length != 1) throw new IOException("input:" + input + " Expect one smallest offset"); range[0] = offsets[0]; offsets = consumer.getOffsetsBefore(topic, partition, OffsetRequest.LATEST_TIME(), 1); if (offsets.length != 1) throw new IOException("input:" + input + " Expect one latest offset"); range[1] = offsets[0]; return range; } /** * Get start offset */ protected long getStartOffset(String input, String offsetStr, long[] range) throws IOException { if (offsetStr.equalsIgnoreCase("smallest")) { return range[0]; } else { Long start = Long.parseLong(offsetStr); if (start > range[1]) { throw new IOException("input:" + input + " start offset is larger than latest one:" + range[1]); } else if (start < range[0]) { System.err.println("WARNING: input:" + input + " start_offset is smaller than smallest_offset:" + range[0] + ". Will use the samllest instead."); return range[0]; } else { return start; } } } @Override public void close() throws IOException { _mos.close(); } @Override public void configure(JobConf conf) { try { _props = KafkaETLUtils.getPropsFromJob(conf); String nodePath = KafkaETLCommons.getNodesPath(_props); Props nodesProps = KafkaETLUtils.readProps(nodePath); System.out.println(nodesProps); _nodes = new HashMap<Integer, URI>(); for (String key : nodesProps.stringPropertyNames()) { _nodes.put(Integer.parseInt(key),nodesProps.getUri(key)); } _bufferSize = KafkaETLCommons.getClientBufferSize(_props); _soTimeout = KafkaETLCommons.getClientTimeout(_props); System.out.println("bufferSize=" + _bufferSize); System.out.println("timeout=" + _soTimeout); _granularity = KafkaETLCommons.getGranularity(_props); _topic = KafkaETLCommons.getTopic(_props); System.out.println("topic=" + _topic); _mos = new MultipleOutputs(conf); _ignoreErrors = _props.getBoolean(KafkaETLCommons.IGNORE_ERRORS, false); } catch (Exception e) { throw new RuntimeException(e); } } }
13,415
0.689899
0.685278
448
28.944197
23.523905
97
false
false
0
0
0
0
0
0
2.533482
false
false
11
1e0782530d224ec1c31894ac21e5f00047582d19
39,608,188,434,479
25e99a0af5751865bce1702ee85cc5c080b0715c
/java/src/图解Java多线程设计模式代码Maven版/src/main/java/ch01SingleThreadedExecution/jucSemaphore/Main.java
9dadea10fac067d88402b29857d159d4b289fb31
[ "Zlib" ]
permissive
jasonblog/note
https://github.com/jasonblog/note
215837f6a08d07abe3e3d2be2e1f183e14aa4a30
4471f95736c60969a718d854cab929f06726280a
refs/heads/master
2023-05-31T13:02:27.451000
2022-04-04T11:28:06
2022-04-04T11:28:06
35,311,001
130
67
null
false
2023-02-10T21:26:36
2015-05-09T02:04:40
2023-01-30T15:37:23
2023-02-10T21:26:30
7,567,053
107
65
43
C
false
false
package ch01SingleThreadedExecution.jucSemaphore; import java.util.Random; import java.util.concurrent.Semaphore; class Log { public static void println(String s) { System.out.println(Thread.currentThread().getName() + ": " + s); } } // 资源个数有限 class BoundedResource { private final static Random random = new Random(314159); private final Semaphore semaphore; private final int permits; // 构造函数(permits为资源个数) public BoundedResource(int permits) { this.semaphore = new Semaphore(permits); this.permits = permits; } // 使用资源 public void use() throws InterruptedException { semaphore.acquire(); try { doUse(); } finally { semaphore.release(); } } // 实际使用资源(此处仅使用Thread.sleep) protected void doUse() throws InterruptedException { Log.println("BEGIN: used = " + (permits - semaphore.availablePermits())); Thread.sleep(random.nextInt(500)); Log.println("END: used = " + (permits - semaphore.availablePermits())); } } // 使用资源的线程 class UserThread extends Thread { private final static Random random = new Random(26535); private final BoundedResource resource; public UserThread(BoundedResource resource) { this.resource = resource; } public void run() { try { while (true) { resource.use(); Thread.sleep(random.nextInt(3000)); } } catch (InterruptedException e) { } } } public class Main { public static void main(String[] args) { // 设置3个资源 BoundedResource resource = new BoundedResource(3); // 10个线程使用资源 for (int i = 0; i < 10; i++) { new UserThread(resource).start(); } } } /* Thread-0: BEGIN: used = 1 Thread-1: BEGIN: used = 2 Thread-2: BEGIN: used = 3 Thread-1: END: used = 3 Thread-5: BEGIN: used = 3 Thread-5: END: used = 3 Thread-4: BEGIN: used = 3 Thread-2: END: used = 3 Thread-8: BEGIN: used = 3 Thread-4: END: used = 3 Thread-6: BEGIN: used = 3 Thread-6: END: used = 3 Thread-9: BEGIN: used = 3 Thread-0: END: used = 3 Thread-3: BEGIN: used = 3 Thread-8: END: used = 3 Thread-7: BEGIN: used = 3 Thread-3: END: used = 3 Thread-7: END: used = 2 Thread-9: END: used = 2 Thread-1: BEGIN: used = 2 Thread-3: BEGIN: used = 2 Thread-5: BEGIN: used = 3 Thread-1: END: used = 3 Thread-4: BEGIN: used = 3 Thread-3: END: used = 3 Thread-5: END: used = 2 Thread-4: END: used = 1 Thread-9: BEGIN: used = 1 Thread-9: END: used = 1 Thread-4: BEGIN: used = 1 Thread-4: END: used = 1 Thread-8: BEGIN: used = 1 Thread-1: BEGIN: used = 2 Thread-1: END: used = 2 Thread-4: BEGIN: used = 2 Thread-8: END: used = 2 Thread-2: BEGIN: used = 2 Thread-7: BEGIN: used = 3 Thread-4: END: used = 3 Thread-0: BEGIN: used = 3 Thread-2: END: used = 3 Thread-0: END: used = 2 Thread-5: BEGIN: used = 2 Thread-3: BEGIN: used = 3 Thread-7: END: used = 3 Thread-6: BEGIN: used = 3 Thread-6: END: used = 3 Thread-1: BEGIN: used = 3 Thread-3: END: used = 3 Thread-7: BEGIN: used = 3 Thread-5: END: used = 3 Thread-4: BEGIN: used = 3 Thread-1: END: used = 3 Thread-4: END: used = 2 Thread-3: BEGIN: used = 2 Thread-0: BEGIN: used = 3 Thread-7: END: used = 3 Thread-7: BEGIN: used = 3 */
UTF-8
Java
3,450
java
Main.java
Java
[]
null
[]
package ch01SingleThreadedExecution.jucSemaphore; import java.util.Random; import java.util.concurrent.Semaphore; class Log { public static void println(String s) { System.out.println(Thread.currentThread().getName() + ": " + s); } } // 资源个数有限 class BoundedResource { private final static Random random = new Random(314159); private final Semaphore semaphore; private final int permits; // 构造函数(permits为资源个数) public BoundedResource(int permits) { this.semaphore = new Semaphore(permits); this.permits = permits; } // 使用资源 public void use() throws InterruptedException { semaphore.acquire(); try { doUse(); } finally { semaphore.release(); } } // 实际使用资源(此处仅使用Thread.sleep) protected void doUse() throws InterruptedException { Log.println("BEGIN: used = " + (permits - semaphore.availablePermits())); Thread.sleep(random.nextInt(500)); Log.println("END: used = " + (permits - semaphore.availablePermits())); } } // 使用资源的线程 class UserThread extends Thread { private final static Random random = new Random(26535); private final BoundedResource resource; public UserThread(BoundedResource resource) { this.resource = resource; } public void run() { try { while (true) { resource.use(); Thread.sleep(random.nextInt(3000)); } } catch (InterruptedException e) { } } } public class Main { public static void main(String[] args) { // 设置3个资源 BoundedResource resource = new BoundedResource(3); // 10个线程使用资源 for (int i = 0; i < 10; i++) { new UserThread(resource).start(); } } } /* Thread-0: BEGIN: used = 1 Thread-1: BEGIN: used = 2 Thread-2: BEGIN: used = 3 Thread-1: END: used = 3 Thread-5: BEGIN: used = 3 Thread-5: END: used = 3 Thread-4: BEGIN: used = 3 Thread-2: END: used = 3 Thread-8: BEGIN: used = 3 Thread-4: END: used = 3 Thread-6: BEGIN: used = 3 Thread-6: END: used = 3 Thread-9: BEGIN: used = 3 Thread-0: END: used = 3 Thread-3: BEGIN: used = 3 Thread-8: END: used = 3 Thread-7: BEGIN: used = 3 Thread-3: END: used = 3 Thread-7: END: used = 2 Thread-9: END: used = 2 Thread-1: BEGIN: used = 2 Thread-3: BEGIN: used = 2 Thread-5: BEGIN: used = 3 Thread-1: END: used = 3 Thread-4: BEGIN: used = 3 Thread-3: END: used = 3 Thread-5: END: used = 2 Thread-4: END: used = 1 Thread-9: BEGIN: used = 1 Thread-9: END: used = 1 Thread-4: BEGIN: used = 1 Thread-4: END: used = 1 Thread-8: BEGIN: used = 1 Thread-1: BEGIN: used = 2 Thread-1: END: used = 2 Thread-4: BEGIN: used = 2 Thread-8: END: used = 2 Thread-2: BEGIN: used = 2 Thread-7: BEGIN: used = 3 Thread-4: END: used = 3 Thread-0: BEGIN: used = 3 Thread-2: END: used = 3 Thread-0: END: used = 2 Thread-5: BEGIN: used = 2 Thread-3: BEGIN: used = 3 Thread-7: END: used = 3 Thread-6: BEGIN: used = 3 Thread-6: END: used = 3 Thread-1: BEGIN: used = 3 Thread-3: END: used = 3 Thread-7: BEGIN: used = 3 Thread-5: END: used = 3 Thread-4: BEGIN: used = 3 Thread-1: END: used = 3 Thread-4: END: used = 2 Thread-3: BEGIN: used = 2 Thread-0: BEGIN: used = 3 Thread-7: END: used = 3 Thread-7: BEGIN: used = 3 */
3,450
0.606504
0.563246
133
24.210526
16.028664
81
false
false
0
0
0
0
0
0
0.180451
false
false
11
3f5d1f0f9229eb21458e17437e0014d6e5398bbe
39,633,958,227,699
b020c8cf6858f12a072c6c4d2d2b16e05401a8d3
/dds/DDS/HistoryQosPolicyKindHelper.java
088953a92a2e2c25f263750ca5777c886801cbf9
[]
no_license
susmitgit/kaizan-dds
https://github.com/susmitgit/kaizan-dds
fe57af2fc3f4c655410e3410e65091a4cf1a3431
98f583a8d8ea4600f7297f95565b70688092ebf3
refs/heads/master
2020-03-17T16:28:16.718000
2018-05-17T03:00:48
2018-05-17T03:00:48
133,749,803
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DDS; public abstract class HistoryQosPolicyKindHelper { // Any and TypeCode operations not currently implemented public static String id() { return "IDL:DDS/HistoryQosPolicyKind:1.0"; } }
UTF-8
Java
200
java
HistoryQosPolicyKindHelper.java
Java
[]
null
[]
package DDS; public abstract class HistoryQosPolicyKindHelper { // Any and TypeCode operations not currently implemented public static String id() { return "IDL:DDS/HistoryQosPolicyKind:1.0"; } }
200
0.78
0.77
5
39
27.856777
74
false
false
0
0
0
0
0
0
0.4
false
false
11
8e1dfeac8608f5f14371b0dcc40f95a658b224dd
39,075,612,498,603
c9d9adf09632a4574b589ed733c4f6255cfde5db
/源代码/SMS/src/main/java/cn/SMS/dao/impl/AttendanceDaoImpl.java
4f3d56e315647a97d58d50d1d79cfe616b15c505
[]
no_license
lpfcumt/Salary-management-system
https://github.com/lpfcumt/Salary-management-system
58517a14a855e423abdecc83462c94e653e34096
44b341f2ffbced4fb67731a584c1aaeb5ec93938
refs/heads/master
2020-07-29T09:30:04.350000
2017-01-09T06:06:14
2017-01-09T06:06:14
73,676,627
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.SMS.dao.impl; import java.util.List; import org.springframework.stereotype.Repository; import cn.SMS.dao.AttendanceDao; import cn.SMS.model.Attendance; import cn.SMS.model.Staff; @Repository("attendanceDao") public class AttendanceDaoImpl extends BaseDaoImpl<Attendance> implements AttendanceDao{ @Override public List<Attendance> queryById(int sid) { // TODO Auto-generated method stub String hql=" from attendance where sid='"+sid+"'"; return findByHql(hql); } @Override public List<Attendance> queryByTime(int year,int month) { // TODO Auto-generated method stub String hql=" from attendance where year='"+year+"' and month='"+month+"'"; return findByHql(hql); } @Override public List<Attendance> listAdBySid(int sid, int year) { // TODO Auto-generated method stub return findByHql(" from attendance where year='"+year+"' and sid='"+sid+"'"); } @Override public List<Attendance> listStaff(int year, int month, String status) { // TODO Auto-generated method stub return findByHql("from attendance where year="+year+" and month="+month+" and status='"+status+"'"); } @Override public void query(Double deduction1, Double deduction2, Double deduction3, Double latetimes, Double leavetimes, Double realdays, Double shulddays,int sid,int year,int month,String time,String status) { // TODO Auto-generated method stub String hql="update attendance s set s.deduction1="+deduction1+",s.deduction2="+deduction2+",s.deduction3="+deduction3+ ",s.latetimes='"+latetimes+"',s.leavetimes='"+leavetimes+"',s.realdays='"+realdays+"',s.shulddays='"+shulddays+"',s.status='"+status+"',s.time='"+time+"' where s.sid="+sid+ " and s.year="+year+" and month="+month+""; getSession().createQuery(hql).executeUpdate(); } @Override public List<Staff> query1() { // TODO Auto-generated method stub return find("from staff"); } @Override public void save1(int month, int sid, String staffname, String status, int year) { // TODO Auto-generated method stub String hql="insert into attendance(month,sid,staffname,status,year) select("+month+","+sid+",'"+staffname+"'"+",'"+status+"'"+","+year+")"; getSession().createQuery(hql).executeUpdate(); } }
UTF-8
Java
2,213
java
AttendanceDaoImpl.java
Java
[]
null
[]
package cn.SMS.dao.impl; import java.util.List; import org.springframework.stereotype.Repository; import cn.SMS.dao.AttendanceDao; import cn.SMS.model.Attendance; import cn.SMS.model.Staff; @Repository("attendanceDao") public class AttendanceDaoImpl extends BaseDaoImpl<Attendance> implements AttendanceDao{ @Override public List<Attendance> queryById(int sid) { // TODO Auto-generated method stub String hql=" from attendance where sid='"+sid+"'"; return findByHql(hql); } @Override public List<Attendance> queryByTime(int year,int month) { // TODO Auto-generated method stub String hql=" from attendance where year='"+year+"' and month='"+month+"'"; return findByHql(hql); } @Override public List<Attendance> listAdBySid(int sid, int year) { // TODO Auto-generated method stub return findByHql(" from attendance where year='"+year+"' and sid='"+sid+"'"); } @Override public List<Attendance> listStaff(int year, int month, String status) { // TODO Auto-generated method stub return findByHql("from attendance where year="+year+" and month="+month+" and status='"+status+"'"); } @Override public void query(Double deduction1, Double deduction2, Double deduction3, Double latetimes, Double leavetimes, Double realdays, Double shulddays,int sid,int year,int month,String time,String status) { // TODO Auto-generated method stub String hql="update attendance s set s.deduction1="+deduction1+",s.deduction2="+deduction2+",s.deduction3="+deduction3+ ",s.latetimes='"+latetimes+"',s.leavetimes='"+leavetimes+"',s.realdays='"+realdays+"',s.shulddays='"+shulddays+"',s.status='"+status+"',s.time='"+time+"' where s.sid="+sid+ " and s.year="+year+" and month="+month+""; getSession().createQuery(hql).executeUpdate(); } @Override public List<Staff> query1() { // TODO Auto-generated method stub return find("from staff"); } @Override public void save1(int month, int sid, String staffname, String status, int year) { // TODO Auto-generated method stub String hql="insert into attendance(month,sid,staffname,status,year) select("+month+","+sid+",'"+staffname+"'"+",'"+status+"'"+","+year+")"; getSession().createQuery(hql).executeUpdate(); } }
2,213
0.714867
0.709896
62
34.69355
38.432842
176
false
false
0
0
0
0
0
0
1.935484
false
false
11
d3759da9e4c67a4142c32a512c2015a1219ce23f
30,640,296,755,945
3e9c0536a5cec1649b9ebe364536b05b6948a99a
/src/data/user/Order.java
e16051a8ed4a05dc4c086ba2ffd4ac477961beac
[]
no_license
InfiniteXyy/j2ee-carpark
https://github.com/InfiniteXyy/j2ee-carpark
d1d6cb14f1048b6e281520550995eabeaab2009c
6a889c7b08c8c6d6600fa826a365d2726d0b6d4e
refs/heads/master
2021-08-31T22:47:46.531000
2017-12-23T07:25:34
2017-12-23T07:25:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package data.user; import java.sql.Date; public class Order { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } private String from; private String to; private int order_car; private Date ddl; private int money; private boolean isAccepted; private String carPic; public String getCarPic() { return carPic; } public void setCarPic(String carPic) { this.carPic = carPic; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public int getOrder_car() { return order_car; } public void setOrder_car(int order_car) { this.order_car = order_car; } public Date getDdl() { return ddl; } public Order() { } public void setDdl(Date ddl) { this.ddl = ddl; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } public boolean isAccepted() { return isAccepted; } public void setAccepted(boolean accepted) { isAccepted = accepted; } public String renderAccepted() { if (isAccepted) return "已被接受"; else return "待处理"; } }
UTF-8
Java
1,479
java
Order.java
Java
[]
null
[]
package data.user; import java.sql.Date; public class Order { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } private String from; private String to; private int order_car; private Date ddl; private int money; private boolean isAccepted; private String carPic; public String getCarPic() { return carPic; } public void setCarPic(String carPic) { this.carPic = carPic; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public int getOrder_car() { return order_car; } public void setOrder_car(int order_car) { this.order_car = order_car; } public Date getDdl() { return ddl; } public Order() { } public void setDdl(Date ddl) { this.ddl = ddl; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } public boolean isAccepted() { return isAccepted; } public void setAccepted(boolean accepted) { isAccepted = accepted; } public String renderAccepted() { if (isAccepted) return "已被接受"; else return "待处理"; } }
1,479
0.554949
0.554949
88
15.647727
13.716314
47
false
false
0
0
0
0
0
0
0.318182
false
false
11
56e32bf723293ecd24b38272873cead7e6ec8233
5,600,637,367,317
cbf430cc6c7a201842029f41359d1d092fc56111
/cadpage/src/net/anei/cadpage/parsers/DE/DEKentCountyEParser.java
880ac48018d8464a9afa7dedfe42a59dffa99aae
[]
no_license
JBassett/cadpage
https://github.com/JBassett/cadpage
65be96632d2179af7717143ab233ce3b8d3e7319
3c0c97f269b855f3d7e4a6976cd179d76df60d6e
refs/heads/master
2016-09-06T08:52:10.364000
2015-01-28T05:45:14
2015-01-28T05:45:14
29,971,570
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.anei.cadpage.parsers.DE; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.anei.cadpage.parsers.MsgInfo.Data; /** * Kent County, DE */ public class DEKentCountyEParser extends DEKentCountyBaseParser { public DEKentCountyEParser() { super("KENT COUNTY", "DE", "Call_Type:CALL! Address:ADDRCITY/SXa! Dev/Sub:PLACE! Xst's:X"); setupMultiWordStreets("COUNTRY ROAD", "PARADISE ALLEY"); } @Override public String getFilter() { return "CADCentral@State.DE.US"; } @Override public boolean parseMsg(String subject, String body, Data data) { if (!subject.equals("!")) return false; body = body.replace(" Dev/Sub:", "\nDev/Sub:"); return parseFields(body.split("\n"), data); } @Override protected Field getField(String name) { if (name.equals("CALL")) return new MyCallField(); if (name.equals("ADDRCITY")) return new MyAddressCityField(); if (name.equals("X")) return new MyCrossField(); return super.getField(name); } private static final Pattern CALL_CODE_PTN = Pattern.compile("^(\\d{1,2}[A-Z]\\d{1,2}[A-Z]?) (?:- )? *(.*)"); private class MyCallField extends CallField { @Override public void parse(String field, Data data) { Matcher match = CALL_CODE_PTN.matcher(field); if (match.matches()) { data.strCode = match.group(1); field = match.group(2); } super.parse(field, data); } @Override public String getFieldNames() { return "CODE CALL"; } } private class MyAddressCityField extends AddressCityField { @Override public void parse(String field, Data data) { int pt = field.lastIndexOf(':'); if (pt >= 0) { data.strPlace = field.substring(pt+1).trim(); field = field.substring(0,pt).trim(); } field = field.replace('@', '&'); super.parse(field, data); adjustCityState(data); } @Override public String getFieldNames() { return super.getFieldNames() + " ST PLACE"; } } private class MyCrossField extends CrossField { @Override public void parse(String field, Data data) { if (field.equals("No Cross Streets Found")) return; super.parse(field, data); } } @Override public String adjustMapAddress(String addr) { addr = COR_PTN.matcher(addr).replaceAll("CORNER"); return super.adjustMapAddress(addr); } private static final Pattern COR_PTN = Pattern.compile("\\bCOR\\b"); }
UTF-8
Java
2,525
java
DEKentCountyEParser.java
Java
[ { "context": "verride\n public String getFilter() {\n return \"CADCentral@State.DE.US\";\n }\n \n @Override\n public boolean parseMsg(St", "end": 529, "score": 0.9999078512191772, "start": 507, "tag": "EMAIL", "value": "CADCentral@State.DE.US" } ]
null
[]
package net.anei.cadpage.parsers.DE; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.anei.cadpage.parsers.MsgInfo.Data; /** * Kent County, DE */ public class DEKentCountyEParser extends DEKentCountyBaseParser { public DEKentCountyEParser() { super("KENT COUNTY", "DE", "Call_Type:CALL! Address:ADDRCITY/SXa! Dev/Sub:PLACE! Xst's:X"); setupMultiWordStreets("COUNTRY ROAD", "PARADISE ALLEY"); } @Override public String getFilter() { return "<EMAIL>"; } @Override public boolean parseMsg(String subject, String body, Data data) { if (!subject.equals("!")) return false; body = body.replace(" Dev/Sub:", "\nDev/Sub:"); return parseFields(body.split("\n"), data); } @Override protected Field getField(String name) { if (name.equals("CALL")) return new MyCallField(); if (name.equals("ADDRCITY")) return new MyAddressCityField(); if (name.equals("X")) return new MyCrossField(); return super.getField(name); } private static final Pattern CALL_CODE_PTN = Pattern.compile("^(\\d{1,2}[A-Z]\\d{1,2}[A-Z]?) (?:- )? *(.*)"); private class MyCallField extends CallField { @Override public void parse(String field, Data data) { Matcher match = CALL_CODE_PTN.matcher(field); if (match.matches()) { data.strCode = match.group(1); field = match.group(2); } super.parse(field, data); } @Override public String getFieldNames() { return "CODE CALL"; } } private class MyAddressCityField extends AddressCityField { @Override public void parse(String field, Data data) { int pt = field.lastIndexOf(':'); if (pt >= 0) { data.strPlace = field.substring(pt+1).trim(); field = field.substring(0,pt).trim(); } field = field.replace('@', '&'); super.parse(field, data); adjustCityState(data); } @Override public String getFieldNames() { return super.getFieldNames() + " ST PLACE"; } } private class MyCrossField extends CrossField { @Override public void parse(String field, Data data) { if (field.equals("No Cross Streets Found")) return; super.parse(field, data); } } @Override public String adjustMapAddress(String addr) { addr = COR_PTN.matcher(addr).replaceAll("CORNER"); return super.adjustMapAddress(addr); } private static final Pattern COR_PTN = Pattern.compile("\\bCOR\\b"); }
2,510
0.633663
0.630099
92
26.423914
23.219761
111
false
false
0
0
0
0
0
0
0.543478
false
false
11
7b48cb42b0c8a3f9e88ddb3fbcc9fc8ccfcbc7e8
10,333,691,354,427
df900c5f72393e5f324cf6c2d27ebee26baf870c
/pet-clinic-data/src/main/java/br/com/rhounsell/sfgpetclinic/model/Owner.java
c64acd45e45100d0ca319bea9f260f61810e61ee
[]
no_license
RaphaelCavalcante/sfg-pet-clinic
https://github.com/RaphaelCavalcante/sfg-pet-clinic
e2460cf7043ecbbcac7319a07cc801db35945fa6
bb0bca576fc17d346d9b1e852ff709312bdea03a
refs/heads/master
2020-04-05T16:59:09.125000
2018-12-29T02:40:37
2018-12-29T02:40:37
157,038,598
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.rhounsell.sfgpetclinic.model; import br.com.rhounsell.sfgpetclinic.model.base.Person; public class Owner extends Person{ /** * */ private static final long serialVersionUID = 1L; }
UTF-8
Java
207
java
Owner.java
Java
[]
null
[]
package br.com.rhounsell.sfgpetclinic.model; import br.com.rhounsell.sfgpetclinic.model.base.Person; public class Owner extends Person{ /** * */ private static final long serialVersionUID = 1L; }
207
0.743961
0.73913
12
16.25
21.209766
55
false
false
0
0
0
0
0
0
0.583333
false
false
11
96544b7c575e8addc9d95574ec4595b2afe30477
32,109,175,542,568
76bdf5bd80271ab3e92c4ae73d16918678b5faea
/arrays/c8_ZeroMatrix.java
7510044f4988d77f510303fb89b2ca05c0cd9b4b
[]
no_license
vsidd/Cracking-the-coding-interview
https://github.com/vsidd/Cracking-the-coding-interview
cf9f1090feb2fd16f4a88e327ee5692352222aa9
47434413f87c52d5fac2a63135c7fcc2f25143f1
refs/heads/master
2021-01-11T16:23:35.282000
2017-01-26T00:26:03
2017-01-26T00:26:03
80,071,333
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ctc.arrays; /** * Created by Siddarthan on 22-Jan-17. */ public class c8_ZeroMatrix { public static void main(String[] args) { int[][] matrix = {{1,0,1},{1,1,1},{1,1,1}}; // matrix = zeroMatrix(matrix); for(int i = 0; i < matrix.length; i++){ for (int j = 0; j < matrix[0].length; j++){ System.out.print(" "+matrix[i][j]); } System.out.println(""); } } public static void zeroMatrix(int[][] matrix){ if(matrix == null) return; boolean columnZeroFlag = false; boolean rowZeroFlag = false; for(int i = 0; i < matrix.length && !rowZeroFlag; i++){ if(matrix[i][0]==0){ rowZeroFlag = true; } } for(int j = 0; j < matrix[0].length && !columnZeroFlag; j++){ if(matrix[0][j]==0){ columnZeroFlag = true; } } for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[0].length; j++){ if(matrix[i][j]==0){ matrix[0][j] = 0; matrix[i][0] = 0; } } } /* for(int i = 0; i < matrix.length; i++){ if(matrix[i][0]==0){ for(int j = 1; j < matrix[0].length; j++){ matrix[i][j] = 0; } } } for(int j = 0; j < matrix[0].length; j++){ if(matrix[0][j]==0){ for(int i = 0; i < matrix.length; i++){ matrix[i][j] = 0; } } } */ for(int i = 1; i < matrix.length; i++){ for(int j = 1; j < matrix[0].length; j++){ if(matrix[i][0] == 0 || matrix[0][j]==0){ matrix[i][j] = 0; } } } if(columnZeroFlag){ for(int j = 0; j < matrix[0].length; j++){ matrix[0][j] = 0; } } if(rowZeroFlag){ for(int i = 0; i < matrix.length; i++){ matrix[i][0] = 0; } } } }
UTF-8
Java
2,039
java
c8_ZeroMatrix.java
Java
[ { "context": "package ctc.arrays;\n\n/**\n * Created by Siddarthan on 22-Jan-17.\n */\npublic class c8_ZeroMatrix {\n ", "end": 49, "score": 0.9997599124908447, "start": 39, "tag": "NAME", "value": "Siddarthan" } ]
null
[]
package ctc.arrays; /** * Created by Siddarthan on 22-Jan-17. */ public class c8_ZeroMatrix { public static void main(String[] args) { int[][] matrix = {{1,0,1},{1,1,1},{1,1,1}}; // matrix = zeroMatrix(matrix); for(int i = 0; i < matrix.length; i++){ for (int j = 0; j < matrix[0].length; j++){ System.out.print(" "+matrix[i][j]); } System.out.println(""); } } public static void zeroMatrix(int[][] matrix){ if(matrix == null) return; boolean columnZeroFlag = false; boolean rowZeroFlag = false; for(int i = 0; i < matrix.length && !rowZeroFlag; i++){ if(matrix[i][0]==0){ rowZeroFlag = true; } } for(int j = 0; j < matrix[0].length && !columnZeroFlag; j++){ if(matrix[0][j]==0){ columnZeroFlag = true; } } for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[0].length; j++){ if(matrix[i][j]==0){ matrix[0][j] = 0; matrix[i][0] = 0; } } } /* for(int i = 0; i < matrix.length; i++){ if(matrix[i][0]==0){ for(int j = 1; j < matrix[0].length; j++){ matrix[i][j] = 0; } } } for(int j = 0; j < matrix[0].length; j++){ if(matrix[0][j]==0){ for(int i = 0; i < matrix.length; i++){ matrix[i][j] = 0; } } } */ for(int i = 1; i < matrix.length; i++){ for(int j = 1; j < matrix[0].length; j++){ if(matrix[i][0] == 0 || matrix[0][j]==0){ matrix[i][j] = 0; } } } if(columnZeroFlag){ for(int j = 0; j < matrix[0].length; j++){ matrix[0][j] = 0; } } if(rowZeroFlag){ for(int i = 0; i < matrix.length; i++){ matrix[i][0] = 0; } } } }
2,039
0.400687
0.371751
79
24.810127
19.06888
69
false
false
0
0
0
0
0
0
1.101266
false
false
11
f738ca8f7e79584f31285ea3ffed28576bc92f22
2,388,001,829,990
08156f1da4de33d251a3f074c5b0bf4a2991aea0
/zapdata/src/main/java/com/srnpr/zapdata/dbface/ITxDefaultService.java
33902a2a0eda8221d2190eb322e6a06f083a794e
[]
no_license
liudongpu/zapsrnpr
https://github.com/liudongpu/zapsrnpr
08fc4aca58a22c1f445b6e99d3c98631e5a255a9
69b14a5c1f16f11164306e66ca21d10d48463fcf
refs/heads/master
2020-05-18T07:12:36.076000
2014-06-12T06:06:37
2014-06-12T06:06:37
11,193,707
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.srnpr.zapdata.dbface; public interface ITxDefaultService { public void setDefaultDao(ITxDao defaultDao); }
UTF-8
Java
143
java
ITxDefaultService.java
Java
[]
null
[]
package com.srnpr.zapdata.dbface; public interface ITxDefaultService { public void setDefaultDao(ITxDao defaultDao); }
143
0.692308
0.692308
11
11
16.991976
46
false
false
0
0
0
0
0
0
0.727273
false
false
11
0fc2e1bfc01af25c65b1f7b258cc6b7a56455c7e
7,447,473,329,190
51dff93202e3ac639dd4f66757d9ff3ec3e1b5da
/app/src/main/java/com/graduation/englishtrain/model/LessonList.java
ca33cda97af215fa1a0f8d7f59c2823e24d5717c
[]
no_license
Simon986793021/EnglishTrain
https://github.com/Simon986793021/EnglishTrain
82e784187e24547bd6ea5c5b318bf2732b57839b
a8330bd5bd38dcce383efa066ca893ae18f73303
refs/heads/master
2021-01-20T03:36:54.179000
2017-05-18T08:58:08
2017-05-18T08:58:08
89,565,046
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.graduation.englishtrain.model; import java.util.List; /** * Created by jiangbo on 2017/5/8. */ public class LessonList { public List<Lesson> rows; public class Lesson { public String courseName; public String teacherName; public String lessonStartTime; public String id; public String courseId; } }
UTF-8
Java
376
java
LessonList.java
Java
[ { "context": ".model;\n\nimport java.util.List;\n\n/**\n * Created by jiangbo on 2017/5/8.\n */\n\npublic class LessonList {\n p", "end": 93, "score": 0.9992002844810486, "start": 86, "tag": "USERNAME", "value": "jiangbo" } ]
null
[]
package com.graduation.englishtrain.model; import java.util.List; /** * Created by jiangbo on 2017/5/8. */ public class LessonList { public List<Lesson> rows; public class Lesson { public String courseName; public String teacherName; public String lessonStartTime; public String id; public String courseId; } }
376
0.646277
0.630319
19
18.789474
14.989747
42
false
false
0
0
0
0
0
0
0.421053
false
false
11
c988b24347ceae9ee0085365454058097e83aef3
584,115,575,690
7473df0bf30a54d5cc188aacd5bc66bea0da4a27
/app/src/main/java/com/ideas/sportscounter/timer/TimePicker.java
92c274a45a61d116c6b2888fb089b8c0a16e4465
[]
no_license
iovorobiev/sports-timer
https://github.com/iovorobiev/sports-timer
5ede6ec4ace0824841b349cecd9723a633ab5559
ee3b5adaf521527faa9cde2338110299bf0ee3ec
refs/heads/master
2021-01-21T14:44:15.941000
2016-06-09T15:16:05
2016-06-09T15:16:05
58,795,093
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ideas.sportscounter.timer; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.support.annotation.StringRes; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import android.widget.Toast; import com.ideas.sportscounter.R; public class TimePicker { static void pickTime(final Context context, @StringRes int res, final OnTimeChosedListener timeChosedListener) { AlertDialog.Builder builder = new AlertDialog.Builder(context); final View pickView = LayoutInflater.from(context).inflate(R.layout.time_chooser, null); builder.setView(pickView); builder.setMessage(res); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //do nothing, dirty hack for default AD behaviour } }); final AlertDialog dialog = builder.create(); dialog.show(); dialog.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText editor = (EditText) pickView.findViewById(R.id.time); String result = editor.getText().toString(); if (TextUtils.isEmpty(result)) { return; } if (!TextUtils.isDigitsOnly(result)) { Toast.makeText(context, R.string.dig_only, Toast.LENGTH_LONG).show(); return; } int resultTime = Integer.parseInt(result); timeChosedListener.onTimeChosed(resultTime); dialog.dismiss(); } }); } public interface OnTimeChosedListener { void onTimeChosed(int time); } }
UTF-8
Java
2,151
java
TimePicker.java
Java
[]
null
[]
package com.ideas.sportscounter.timer; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.support.annotation.StringRes; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import android.widget.Toast; import com.ideas.sportscounter.R; public class TimePicker { static void pickTime(final Context context, @StringRes int res, final OnTimeChosedListener timeChosedListener) { AlertDialog.Builder builder = new AlertDialog.Builder(context); final View pickView = LayoutInflater.from(context).inflate(R.layout.time_chooser, null); builder.setView(pickView); builder.setMessage(res); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //do nothing, dirty hack for default AD behaviour } }); final AlertDialog dialog = builder.create(); dialog.show(); dialog.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText editor = (EditText) pickView.findViewById(R.id.time); String result = editor.getText().toString(); if (TextUtils.isEmpty(result)) { return; } if (!TextUtils.isDigitsOnly(result)) { Toast.makeText(context, R.string.dig_only, Toast.LENGTH_LONG).show(); return; } int resultTime = Integer.parseInt(result); timeChosedListener.onTimeChosed(resultTime); dialog.dismiss(); } }); } public interface OnTimeChosedListener { void onTimeChosed(int time); } }
2,151
0.637843
0.637843
58
36.086208
26.438141
101
false
false
0
0
0
0
0
0
0.655172
false
false
11
c5f9a41b8f0901951e2288a842207e0e0c7a3681
644,245,131,311
54b284cfccd5c66b723ae39496ce239691006971
/FeedbackManagementSystem/src/com/cg/fms/exception/FeedbackException.java
92793c1dc5895d27083a3c6f576db69fea5cff59
[]
no_license
ford15/miniproject
https://github.com/ford15/miniproject
7abe7779a56a21eb2a3d3e44fd2ece6ef64680be
073af88b6485d0c78a2274747ebafab301d4a32c
refs/heads/master
2021-05-08T16:49:00.005000
2018-09-27T18:16:10
2018-09-27T18:16:10
120,173,444
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cg.fms.exception; public class FeedbackException extends Exception { public FeedbackException(String message) { super(message); // TODO Auto-generated constructor stub } }
UTF-8
Java
207
java
FeedbackException.java
Java
[]
null
[]
package com.cg.fms.exception; public class FeedbackException extends Exception { public FeedbackException(String message) { super(message); // TODO Auto-generated constructor stub } }
207
0.714976
0.714976
12
15.25
18.664248
48
false
false
0
0
0
0
0
0
0.75
false
false
11
58b84f569bd24d5a58115d85eb2669b9ea7b4126
27,101,243,700,535
adb1b286cf60f195e938b13354c14d15ad551a04
/App7_6.java
198ff8d3c3d758d43c11b3a0ab51e3c4f830ff69
[]
no_license
qianlongzt/java-demo
https://github.com/qianlongzt/java-demo
ae0a0b0fc5e7c81e18546242fd49ccd183f2f8e3
dfb7cabdfbf4d1804886fad12d394bf785d57602
refs/heads/master
2019-01-16T11:41:07.043000
2016-12-09T01:42:02
2016-12-09T01:42:02
73,538,095
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//filename:App7_6.java class Cylinder { private double radius; private int height; private double pi=3.14; String color; public Cylinder() { this(2.5, 5, "红色"); System.out.println("无参构造方法被调用了"); } public Cylinder(double r, int h, String str) { System.out.println("有参构造方法被调用了"); radius=r; height=h; color=str; } public void show() { System.out.println("圆柱底半径为:"+ radius); System.out.println("圆柱体的高为:"+ height); System.out.println("圆柱的颜色为:"+color); } double area() { return pi* radius* radius; } double volume() { return area()*height; } } public class App7_6 { public static void main(String[] args) { Cylinder volu=new Cylinder(); System.out.println("圆柱底面积="+ volu.area()); System.out.println("圆柱体体积="+volu.volume()); volu.show(); } }
GB18030
Java
948
java
App7_6.java
Java
[]
null
[]
//filename:App7_6.java class Cylinder { private double radius; private int height; private double pi=3.14; String color; public Cylinder() { this(2.5, 5, "红色"); System.out.println("无参构造方法被调用了"); } public Cylinder(double r, int h, String str) { System.out.println("有参构造方法被调用了"); radius=r; height=h; color=str; } public void show() { System.out.println("圆柱底半径为:"+ radius); System.out.println("圆柱体的高为:"+ height); System.out.println("圆柱的颜色为:"+color); } double area() { return pi* radius* radius; } double volume() { return area()*height; } } public class App7_6 { public static void main(String[] args) { Cylinder volu=new Cylinder(); System.out.println("圆柱底面积="+ volu.area()); System.out.println("圆柱体体积="+volu.volume()); volu.show(); } }
948
0.615476
0.603571
44
18.09091
14.907012
47
false
false
0
0
0
0
0
0
0.522727
false
false
11
18753b8c45bdb44abf309202048fe485844ee7cb
7,009,386,671,312
ad8d4156c36c980bd461824918390dea964551d1
/src/test/java/se/lia/template/AldersInverkanParserTest.java
1f9e50bc25144a6ff80430b269d7b22362156fc1
[]
no_license
JohnDennisAnd93/PraktikPeriod1_Skv
https://github.com/JohnDennisAnd93/PraktikPeriod1_Skv
73a0b4f2e01aa1e25a7186e721179ce43f0e5f51
c6833d2b88496546090b05c92d121dcf076d603f
refs/heads/master
2021-07-16T19:00:33.054000
2017-10-19T13:28:12
2017-10-19T13:28:12
107,547,863
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package se.lia.template; import java.io.File; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import se.lia.datafangst.AldersInverkanParser; import se.lia.datafangst.ParserFactory; import se.lia.model.AldersInverkanEntity; public class AldersInverkanParserTest { private AldersInverkanParser p; private AldersInverkanEntity e; private File f; @Before public void setUp() throws Exception { f = new File("XMLUnderlag/AldersInverkan.xml"); p = (AldersInverkanParser)ParserFactory.getParser(f); e = p.makeEntity(); } @Test public void testMakeEntity() { Assert.assertEquals(2001, e.getFastighetsTaxeringsAr()); } @Test public void testSaveEntity() { p.saveEntity(); } }
UTF-8
Java
734
java
AldersInverkanParserTest.java
Java
[]
null
[]
package se.lia.template; import java.io.File; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import se.lia.datafangst.AldersInverkanParser; import se.lia.datafangst.ParserFactory; import se.lia.model.AldersInverkanEntity; public class AldersInverkanParserTest { private AldersInverkanParser p; private AldersInverkanEntity e; private File f; @Before public void setUp() throws Exception { f = new File("XMLUnderlag/AldersInverkan.xml"); p = (AldersInverkanParser)ParserFactory.getParser(f); e = p.makeEntity(); } @Test public void testMakeEntity() { Assert.assertEquals(2001, e.getFastighetsTaxeringsAr()); } @Test public void testSaveEntity() { p.saveEntity(); } }
734
0.749319
0.743869
43
16.069767
17.692984
58
false
false
0
0
0
0
0
0
1.046512
false
false
11
445f1a8959ac861f1be57409eb1357c639ce40e4
24,163,486,070,541
c5179e7ee1124a9bdf2146c618a7ef9ac9797310
/ChatWBPro/Client/ChatClient.java
4d58b7e176d573d6006594f0a7d2b5f792ec6b14
[]
no_license
Lsylvanus/personalJava
https://github.com/Lsylvanus/personalJava
4caf5ae340356117c555f42d93f03aa7b954097f
ac858221c73766d6702a11160f52553e8b3e8736
refs/heads/master
2020-05-21T20:35:51.786000
2016-11-14T07:23:51
2016-11-14T07:23:51
65,553,431
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lsylvanus.Client; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JButton; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.JTextArea; import javax.swing.JLabel; import javax.swing.JComboBox; import javax.swing.JCheckBox; import javax.swing.JTextField; import java.awt.event.ActionListener; import javax.swing.JScrollPane; import java.awt.Color; import java.awt.Font; import javax.swing.border.CompoundBorder; public class ChatClient extends JFrame implements ActionListener { // 连接到服务端的ip地址 String ip = "127.0.0.1"; // 连接到服务端的端口号 int port = 8888; // 用户名 String userName = "封尘"; // 0表示未连接,1表示已连接 int type = 0; private JPanel contentPane; private JTextField clientMessage; private JTextField showStatus; private JMenuBar menuBar; private JMenu operateMenu; private JMenuItem loginItem; private JMenuItem logoffItem; private JMenuItem exitItem; private JMenu conMenu; private JMenuItem userItem; private JMenuItem connectItem; private JMenu helpMenu; private JMenuItem helpItem; private JComboBox comboBox; private JTextArea messageShow; private JCheckBox checkBox; private JButton userButton; private JButton connectButton; private JButton loginButton; private JButton logoffButton; private JButton exitButton; private JButton clientMessageButton; private JLabel label_2; private JComboBox actionlist; Socket socket; ObjectOutputStream output;// 网络套接字输出流 ObjectInputStream input;// 网络套接字输入流 ClientReceive recvThread; private JScrollPane messageScrollPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ChatClient frame = new ChatClient(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public ChatClient() { setIconImage(Toolkit.getDefaultToolkit() .getImage(ChatClient.class.getResource("/image/Foobar_32px_1121452_easyicon.net.png"))); setTitle("\u804A\u5929\u5BA4\u5BA2\u6237\u7AEF"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭程序时的操作 this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { if (type == 1) { DisConnect(); } System.exit(0); } }); setBounds(100, 100, 493, 720); menuBar = new JMenuBar(); setJMenuBar(menuBar); operateMenu = new JMenu("\u64CD\u4F5C"); operateMenu.setFont(new Font("微软雅黑", Font.PLAIN, 12)); menuBar.add(operateMenu); loginItem = new JMenuItem("\u7528\u6237\u767B\u5F55"); loginItem.setFont(new Font("微软雅黑", Font.PLAIN, 12)); operateMenu.add(loginItem); logoffItem = new JMenuItem("\u7528\u6237\u6CE8\u9500"); logoffItem.setFont(new Font("微软雅黑", Font.PLAIN, 12)); operateMenu.add(logoffItem); exitItem = new JMenuItem("\u9000\u51FA"); exitItem.setFont(new Font("微软雅黑", Font.PLAIN, 12)); operateMenu.add(exitItem); conMenu = new JMenu("\u8BBE\u7F6E"); conMenu.setFont(new Font("微软雅黑", Font.PLAIN, 12)); menuBar.add(conMenu); userItem = new JMenuItem("\u7528\u6237\u8BBE\u7F6E"); userItem.setFont(new Font("微软雅黑", Font.PLAIN, 12)); conMenu.add(userItem); connectItem = new JMenuItem("\u8FDE\u63A5\u8BBE\u7F6E"); connectItem.setFont(new Font("微软雅黑", Font.PLAIN, 12)); conMenu.add(connectItem); helpMenu = new JMenu("\u5E2E\u52A9"); helpMenu.setFont(new Font("微软雅黑", Font.PLAIN, 12)); menuBar.add(helpMenu); helpItem = new JMenuItem("\u5E2E\u52A9"); helpItem.setFont(new Font("微软雅黑", Font.PLAIN, 12)); helpMenu.add(helpItem); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); JPanel panel = new JPanel(); panel.setBorder(new CompoundBorder()); JLabel label = new JLabel("\u53D1\u9001\u81F3\uFF1A"); label.setFont(new Font("微软雅黑", Font.PLAIN, 12)); comboBox = new JComboBox(); comboBox.setFont(new Font("微软雅黑", Font.PLAIN, 12)); checkBox = new JCheckBox("\u6084\u6084\u8BDD"); checkBox.setFont(new Font("微软雅黑", Font.PLAIN, 12)); JLabel label_1 = new JLabel("\u53D1\u9001\u6D88\u606F\uFF1A"); label_1.setFont(new Font("微软雅黑", Font.PLAIN, 12)); clientMessage = new JTextField(); clientMessage.setFont(new Font("微软雅黑", Font.PLAIN, 12)); clientMessage.setColumns(10); clientMessageButton = new JButton("\u53D1\u9001"); clientMessageButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); showStatus = new JTextField(); showStatus.setFont(new Font("微软雅黑", Font.PLAIN, 12)); showStatus.setForeground(Color.BLACK); showStatus.setEditable(false); showStatus.setColumns(10); label_2 = new JLabel("\u8868\u60C5\uFF1A"); label_2.setFont(new Font("微软雅黑", Font.PLAIN, 12)); actionlist = new JComboBox(); actionlist.setFont(new Font("微软雅黑", Font.PLAIN, 12)); actionlist.addItem("微笑地"); actionlist.addItem("高兴地"); actionlist.addItem("轻轻地"); actionlist.addItem("生气地"); actionlist.addItem("小心地"); actionlist.addItem("静静地"); actionlist.setSelectedIndex(0); messageScrollPane = new JScrollPane(); if (messageScrollPane.isValidateRoot()) { messageScrollPane.revalidate(); } GroupLayout gl_contentPane = new GroupLayout(contentPane); gl_contentPane.setHorizontalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addContainerGap() .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(messageScrollPane, GroupLayout.PREFERRED_SIZE, 437, GroupLayout.PREFERRED_SIZE) .addComponent(panel, GroupLayout.PREFERRED_SIZE, 447, GroupLayout.PREFERRED_SIZE) .addGroup(gl_contentPane.createSequentialGroup() .addComponent(label) .addGap(1) .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, 92, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(label_2) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(actionlist, GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED, 70, Short.MAX_VALUE) .addComponent(checkBox) .addGap(21)))) .addGroup(gl_contentPane.createSequentialGroup() .addGap(12) .addComponent(label_1) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(clientMessage, GroupLayout.PREFERRED_SIZE, 242, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.UNRELATED) .addComponent(clientMessageButton)) .addGroup(gl_contentPane.createSequentialGroup() .addContainerGap() .addComponent(showStatus, GroupLayout.PREFERRED_SIZE, 278, GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); gl_contentPane.setVerticalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addContainerGap() .addComponent(panel, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.UNRELATED) .addComponent(messageScrollPane, GroupLayout.PREFERRED_SIZE, 412, GroupLayout.PREFERRED_SIZE) .addGap(30) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGap(18) .addComponent(label)) .addGroup(gl_contentPane.createSequentialGroup() .addGap(14) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(label_2) .addComponent(actionlist, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(checkBox)))) .addGap(14) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(label_1) .addComponent(clientMessage, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(clientMessageButton)) .addGap(18) .addComponent(showStatus, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addContainerGap(30, Short.MAX_VALUE)) ); messageShow = new JTextArea(); messageShow.setEditable(false); messageScrollPane.setViewportView(messageShow); userButton = new JButton("\u7528\u6237\u8BBE\u7F6E"); userButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); connectButton = new JButton("\u8FDE\u63A5\u8BBE\u7F6E"); connectButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); loginButton = new JButton("\u767B\u5F55"); loginButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); logoffButton = new JButton("\u6CE8\u9500"); logoffButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); exitButton = new JButton("\u9000\u51FA"); exitButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); loginItem.addActionListener(this); logoffItem.addActionListener(this); exitItem.addActionListener(this); userItem.addActionListener(this); connectItem.addActionListener(this); helpItem.addActionListener(this); loginButton.addActionListener(this); logoffButton.addActionListener(this); userButton.addActionListener(this); connectButton.addActionListener(this); exitButton.addActionListener(this); clientMessage.addActionListener(this); clientMessageButton.addActionListener(this); loginButton.setToolTipText("连接到指定的服务器"); logoffButton.setToolTipText("与服务器断开连接"); userButton.setToolTipText("设置用户信息"); connectButton.setToolTipText("设置所要连接到的服务器信息"); GroupLayout gl_panel = new GroupLayout(panel); gl_panel.setHorizontalGroup( gl_panel.createParallelGroup(Alignment.LEADING) .addGroup(gl_panel.createSequentialGroup() .addContainerGap() .addComponent(userButton) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(connectButton) .addGap(26) .addComponent(loginButton) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(logoffButton) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(exitButton) .addContainerGap(17, Short.MAX_VALUE)) ); gl_panel.setVerticalGroup( gl_panel.createParallelGroup(Alignment.LEADING) .addGroup(gl_panel.createSequentialGroup() .addGroup(gl_panel.createParallelGroup(Alignment.BASELINE) .addComponent(userButton) .addComponent(connectButton) .addComponent(loginButton) .addComponent(logoffButton) .addComponent(exitButton)) .addContainerGap(16, Short.MAX_VALUE)) ); panel.setLayout(gl_panel); contentPane.setLayout(gl_contentPane); } public void init() { } @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); if (obj == userItem || obj == userButton) { // 用户信息设置 // 调出用户信息设置对话框 UserConf userConf = new UserConf(this, userName); userConf.show(); userName = userConf.userInputName; } else if (obj == connectItem || obj == connectButton) { // 连接服务端设置 // 调出连接设置对话框 ConnectConf conConf = new ConnectConf(this, ip, port); conConf.show(); ip = conConf.userInputIp; port = conConf.userInputPort; } else if (obj == loginItem || obj == loginButton) { // 登录 Connect(); } else if (obj == logoffItem || obj == logoffButton) { // 注销 DisConnect(); showStatus.setText(""); } else if (obj == clientMessage || obj == clientMessageButton) { // 发送消息 SendMessage(); clientMessage.setText(""); } else if (obj == exitButton || obj == exitItem) { // 退出 int j = JOptionPane.showConfirmDialog(this, "真的要退出吗?", "退出", JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE); if (j == JOptionPane.YES_OPTION) { if (type == 1) { DisConnect(); } System.exit(0); } } else if (obj == helpItem) { // 菜单栏中的帮助 // 调出帮助对话框 Help helpDialog = new Help(this); helpDialog.show(); } } /** * 发送消息 */ public void SendMessage() { String toSomebody = comboBox.getSelectedItem().toString(); String status = ""; if (checkBox.isSelected()) { status = "悄悄话"; } String action = actionlist.getSelectedItem().toString(); String message = clientMessage.getText(); if (socket.isClosed()) { return; } try { output.writeObject("聊天信息"); output.flush(); output.writeObject(toSomebody); output.flush(); output.writeObject(status); output.flush(); output.writeObject(action); output.flush(); output.writeObject(message); output.flush(); } catch (Exception e) { // } } /** * 获取连接 */ private void Connect() { try { socket = new Socket(ip, port); } catch (Exception e) { JOptionPane.showConfirmDialog(this, "不能连接到指定的服务器。\n请确认连接设置是否正确。", "提示", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE); return; } try { output = new ObjectOutputStream(socket.getOutputStream()); output.flush(); input = new ObjectInputStream(socket.getInputStream()); output.writeObject(userName); output.flush(); recvThread = new ClientReceive(socket, output, input, comboBox, messageShow, showStatus); recvThread.start(); loginButton.setEnabled(false); loginItem.setEnabled(false); userButton.setEnabled(false); userItem.setEnabled(false); connectButton.setEnabled(false); connectItem.setEnabled(false); logoffButton.setEnabled(true); logoffItem.setEnabled(true); clientMessage.setEnabled(true); messageShow.append("连接服务器 " + ip + ":" + port + " 成功...\n"); type = 1;// 标志位设为已连接 } catch (Exception e) { System.out.println(e); return; } } /** * 断开连接,用户下线 */ public void DisConnect() { loginButton.setEnabled(true); loginItem.setEnabled(true); userButton.setEnabled(true); userItem.setEnabled(true); connectButton.setEnabled(true); connectItem.setEnabled(true); logoffButton.setEnabled(false); logoffItem.setEnabled(false); clientMessage.setEnabled(false); if (socket.isClosed()) { return; } try { output.writeObject("用户下线"); output.flush(); input.close(); output.close(); socket.close(); messageShow.append("已经与服务器断开连接...\n"); type = 0;// 标志位设为未连接 } catch (Exception e) { // } } }
GB18030
Java
16,050
java
ChatClient.java
Java
[ { "context": " ActionListener {\r\n\t// 连接到服务端的ip地址\r\n\tString ip = \"127.0.0.1\";\r\n\t// 连接到服务端的端口号\r\n\tint port = 8888;\r\n\t// 用户名\r\n\tS", "end": 1097, "score": 0.9996997117996216, "start": 1088, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "\r\n\tint port = 8888;...
null
[]
package com.lsylvanus.Client; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JButton; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.JTextArea; import javax.swing.JLabel; import javax.swing.JComboBox; import javax.swing.JCheckBox; import javax.swing.JTextField; import java.awt.event.ActionListener; import javax.swing.JScrollPane; import java.awt.Color; import java.awt.Font; import javax.swing.border.CompoundBorder; public class ChatClient extends JFrame implements ActionListener { // 连接到服务端的ip地址 String ip = "127.0.0.1"; // 连接到服务端的端口号 int port = 8888; // 用户名 String userName = "封尘"; // 0表示未连接,1表示已连接 int type = 0; private JPanel contentPane; private JTextField clientMessage; private JTextField showStatus; private JMenuBar menuBar; private JMenu operateMenu; private JMenuItem loginItem; private JMenuItem logoffItem; private JMenuItem exitItem; private JMenu conMenu; private JMenuItem userItem; private JMenuItem connectItem; private JMenu helpMenu; private JMenuItem helpItem; private JComboBox comboBox; private JTextArea messageShow; private JCheckBox checkBox; private JButton userButton; private JButton connectButton; private JButton loginButton; private JButton logoffButton; private JButton exitButton; private JButton clientMessageButton; private JLabel label_2; private JComboBox actionlist; Socket socket; ObjectOutputStream output;// 网络套接字输出流 ObjectInputStream input;// 网络套接字输入流 ClientReceive recvThread; private JScrollPane messageScrollPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ChatClient frame = new ChatClient(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public ChatClient() { setIconImage(Toolkit.getDefaultToolkit() .getImage(ChatClient.class.getResource("/image/Foobar_32px_1121452_easyicon.net.png"))); setTitle("\u804A\u5929\u5BA4\u5BA2\u6237\u7AEF"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭程序时的操作 this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { if (type == 1) { DisConnect(); } System.exit(0); } }); setBounds(100, 100, 493, 720); menuBar = new JMenuBar(); setJMenuBar(menuBar); operateMenu = new JMenu("\u64CD\u4F5C"); operateMenu.setFont(new Font("微软雅黑", Font.PLAIN, 12)); menuBar.add(operateMenu); loginItem = new JMenuItem("\u7528\u6237\u767B\u5F55"); loginItem.setFont(new Font("微软雅黑", Font.PLAIN, 12)); operateMenu.add(loginItem); logoffItem = new JMenuItem("\u7528\u6237\u6CE8\u9500"); logoffItem.setFont(new Font("微软雅黑", Font.PLAIN, 12)); operateMenu.add(logoffItem); exitItem = new JMenuItem("\u9000\u51FA"); exitItem.setFont(new Font("微软雅黑", Font.PLAIN, 12)); operateMenu.add(exitItem); conMenu = new JMenu("\u8BBE\u7F6E"); conMenu.setFont(new Font("微软雅黑", Font.PLAIN, 12)); menuBar.add(conMenu); userItem = new JMenuItem("\u7528\u6237\u8BBE\u7F6E"); userItem.setFont(new Font("微软雅黑", Font.PLAIN, 12)); conMenu.add(userItem); connectItem = new JMenuItem("\u8FDE\u63A5\u8BBE\u7F6E"); connectItem.setFont(new Font("微软雅黑", Font.PLAIN, 12)); conMenu.add(connectItem); helpMenu = new JMenu("\u5E2E\u52A9"); helpMenu.setFont(new Font("微软雅黑", Font.PLAIN, 12)); menuBar.add(helpMenu); helpItem = new JMenuItem("\u5E2E\u52A9"); helpItem.setFont(new Font("微软雅黑", Font.PLAIN, 12)); helpMenu.add(helpItem); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); JPanel panel = new JPanel(); panel.setBorder(new CompoundBorder()); JLabel label = new JLabel("\u53D1\u9001\u81F3\uFF1A"); label.setFont(new Font("微软雅黑", Font.PLAIN, 12)); comboBox = new JComboBox(); comboBox.setFont(new Font("微软雅黑", Font.PLAIN, 12)); checkBox = new JCheckBox("\u6084\u6084\u8BDD"); checkBox.setFont(new Font("微软雅黑", Font.PLAIN, 12)); JLabel label_1 = new JLabel("\u53D1\u9001\u6D88\u606F\uFF1A"); label_1.setFont(new Font("微软雅黑", Font.PLAIN, 12)); clientMessage = new JTextField(); clientMessage.setFont(new Font("微软雅黑", Font.PLAIN, 12)); clientMessage.setColumns(10); clientMessageButton = new JButton("\u53D1\u9001"); clientMessageButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); showStatus = new JTextField(); showStatus.setFont(new Font("微软雅黑", Font.PLAIN, 12)); showStatus.setForeground(Color.BLACK); showStatus.setEditable(false); showStatus.setColumns(10); label_2 = new JLabel("\u8868\u60C5\uFF1A"); label_2.setFont(new Font("微软雅黑", Font.PLAIN, 12)); actionlist = new JComboBox(); actionlist.setFont(new Font("微软雅黑", Font.PLAIN, 12)); actionlist.addItem("微笑地"); actionlist.addItem("高兴地"); actionlist.addItem("轻轻地"); actionlist.addItem("生气地"); actionlist.addItem("小心地"); actionlist.addItem("静静地"); actionlist.setSelectedIndex(0); messageScrollPane = new JScrollPane(); if (messageScrollPane.isValidateRoot()) { messageScrollPane.revalidate(); } GroupLayout gl_contentPane = new GroupLayout(contentPane); gl_contentPane.setHorizontalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addContainerGap() .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(messageScrollPane, GroupLayout.PREFERRED_SIZE, 437, GroupLayout.PREFERRED_SIZE) .addComponent(panel, GroupLayout.PREFERRED_SIZE, 447, GroupLayout.PREFERRED_SIZE) .addGroup(gl_contentPane.createSequentialGroup() .addComponent(label) .addGap(1) .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, 92, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(label_2) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(actionlist, GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED, 70, Short.MAX_VALUE) .addComponent(checkBox) .addGap(21)))) .addGroup(gl_contentPane.createSequentialGroup() .addGap(12) .addComponent(label_1) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(clientMessage, GroupLayout.PREFERRED_SIZE, 242, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.UNRELATED) .addComponent(clientMessageButton)) .addGroup(gl_contentPane.createSequentialGroup() .addContainerGap() .addComponent(showStatus, GroupLayout.PREFERRED_SIZE, 278, GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); gl_contentPane.setVerticalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addContainerGap() .addComponent(panel, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.UNRELATED) .addComponent(messageScrollPane, GroupLayout.PREFERRED_SIZE, 412, GroupLayout.PREFERRED_SIZE) .addGap(30) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGap(18) .addComponent(label)) .addGroup(gl_contentPane.createSequentialGroup() .addGap(14) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(label_2) .addComponent(actionlist, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(checkBox)))) .addGap(14) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(label_1) .addComponent(clientMessage, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(clientMessageButton)) .addGap(18) .addComponent(showStatus, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addContainerGap(30, Short.MAX_VALUE)) ); messageShow = new JTextArea(); messageShow.setEditable(false); messageScrollPane.setViewportView(messageShow); userButton = new JButton("\u7528\u6237\u8BBE\u7F6E"); userButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); connectButton = new JButton("\u8FDE\u63A5\u8BBE\u7F6E"); connectButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); loginButton = new JButton("\u767B\u5F55"); loginButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); logoffButton = new JButton("\u6CE8\u9500"); logoffButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); exitButton = new JButton("\u9000\u51FA"); exitButton.setFont(new Font("微软雅黑", Font.PLAIN, 12)); loginItem.addActionListener(this); logoffItem.addActionListener(this); exitItem.addActionListener(this); userItem.addActionListener(this); connectItem.addActionListener(this); helpItem.addActionListener(this); loginButton.addActionListener(this); logoffButton.addActionListener(this); userButton.addActionListener(this); connectButton.addActionListener(this); exitButton.addActionListener(this); clientMessage.addActionListener(this); clientMessageButton.addActionListener(this); loginButton.setToolTipText("连接到指定的服务器"); logoffButton.setToolTipText("与服务器断开连接"); userButton.setToolTipText("设置用户信息"); connectButton.setToolTipText("设置所要连接到的服务器信息"); GroupLayout gl_panel = new GroupLayout(panel); gl_panel.setHorizontalGroup( gl_panel.createParallelGroup(Alignment.LEADING) .addGroup(gl_panel.createSequentialGroup() .addContainerGap() .addComponent(userButton) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(connectButton) .addGap(26) .addComponent(loginButton) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(logoffButton) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(exitButton) .addContainerGap(17, Short.MAX_VALUE)) ); gl_panel.setVerticalGroup( gl_panel.createParallelGroup(Alignment.LEADING) .addGroup(gl_panel.createSequentialGroup() .addGroup(gl_panel.createParallelGroup(Alignment.BASELINE) .addComponent(userButton) .addComponent(connectButton) .addComponent(loginButton) .addComponent(logoffButton) .addComponent(exitButton)) .addContainerGap(16, Short.MAX_VALUE)) ); panel.setLayout(gl_panel); contentPane.setLayout(gl_contentPane); } public void init() { } @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); if (obj == userItem || obj == userButton) { // 用户信息设置 // 调出用户信息设置对话框 UserConf userConf = new UserConf(this, userName); userConf.show(); userName = userConf.userInputName; } else if (obj == connectItem || obj == connectButton) { // 连接服务端设置 // 调出连接设置对话框 ConnectConf conConf = new ConnectConf(this, ip, port); conConf.show(); ip = conConf.userInputIp; port = conConf.userInputPort; } else if (obj == loginItem || obj == loginButton) { // 登录 Connect(); } else if (obj == logoffItem || obj == logoffButton) { // 注销 DisConnect(); showStatus.setText(""); } else if (obj == clientMessage || obj == clientMessageButton) { // 发送消息 SendMessage(); clientMessage.setText(""); } else if (obj == exitButton || obj == exitItem) { // 退出 int j = JOptionPane.showConfirmDialog(this, "真的要退出吗?", "退出", JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE); if (j == JOptionPane.YES_OPTION) { if (type == 1) { DisConnect(); } System.exit(0); } } else if (obj == helpItem) { // 菜单栏中的帮助 // 调出帮助对话框 Help helpDialog = new Help(this); helpDialog.show(); } } /** * 发送消息 */ public void SendMessage() { String toSomebody = comboBox.getSelectedItem().toString(); String status = ""; if (checkBox.isSelected()) { status = "悄悄话"; } String action = actionlist.getSelectedItem().toString(); String message = clientMessage.getText(); if (socket.isClosed()) { return; } try { output.writeObject("聊天信息"); output.flush(); output.writeObject(toSomebody); output.flush(); output.writeObject(status); output.flush(); output.writeObject(action); output.flush(); output.writeObject(message); output.flush(); } catch (Exception e) { // } } /** * 获取连接 */ private void Connect() { try { socket = new Socket(ip, port); } catch (Exception e) { JOptionPane.showConfirmDialog(this, "不能连接到指定的服务器。\n请确认连接设置是否正确。", "提示", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE); return; } try { output = new ObjectOutputStream(socket.getOutputStream()); output.flush(); input = new ObjectInputStream(socket.getInputStream()); output.writeObject(userName); output.flush(); recvThread = new ClientReceive(socket, output, input, comboBox, messageShow, showStatus); recvThread.start(); loginButton.setEnabled(false); loginItem.setEnabled(false); userButton.setEnabled(false); userItem.setEnabled(false); connectButton.setEnabled(false); connectItem.setEnabled(false); logoffButton.setEnabled(true); logoffItem.setEnabled(true); clientMessage.setEnabled(true); messageShow.append("连接服务器 " + ip + ":" + port + " 成功...\n"); type = 1;// 标志位设为已连接 } catch (Exception e) { System.out.println(e); return; } } /** * 断开连接,用户下线 */ public void DisConnect() { loginButton.setEnabled(true); loginItem.setEnabled(true); userButton.setEnabled(true); userItem.setEnabled(true); connectButton.setEnabled(true); connectItem.setEnabled(true); logoffButton.setEnabled(false); logoffItem.setEnabled(false); clientMessage.setEnabled(false); if (socket.isClosed()) { return; } try { output.writeObject("用户下线"); output.flush(); input.close(); output.close(); socket.close(); messageShow.append("已经与服务器断开连接...\n"); type = 0;// 标志位设为未连接 } catch (Exception e) { // } } }
16,050
0.693376
0.672382
481
29.887733
22.34133
116
false
false
0
0
36
0.015256
0
0
3.218295
false
false
11
2b4454bd53064ae02b837e5a4af5d93d3fbbea65
1,649,267,503,970
ab817faf4cd964dd203472bcec376d4a1593b5dd
/app/src/main/java/com/haladhair/assign1/Main2Activity.java
36ce6dc41691bbe434fceb0baadb7e689c6e2dd8
[]
no_license
haladhair/assignment1
https://github.com/haladhair/assignment1
4231ea1cf2f81de49b2204d309e82ec0ec3b4155
f88439f0abd53ccc04c82e7fa5ea41c5b61ec65f
refs/heads/master
2020-05-01T00:17:46.183000
2019-03-22T15:38:42
2019-03-22T15:38:42
177,165,563
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.haladhair.assign1; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.Button; import android.widget.CalendarView; import android.widget.TextView; import java.util.Date; public class Main2Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); final TextView txtv=findViewById(R.id.txtvi); final TextView txtvg=findViewById(R.id.textView7); final TextView sel=findViewById(R.id.dateselect); Bundle b = getIntent().getExtras(); String firsst = b.getString("firstnam"); String lasst = b.getString("lastnam"); final String datee = b.getString("thedatt"); txtv.setText(firsst + lasst); txtvg.setText(datee); // Intent incoming = getIntent(); // String date = incoming.getStringExtra("date"); // sel.setText(date); // sel.setText(datee); } }
UTF-8
Java
1,116
java
Main2Activity.java
Java
[]
null
[]
package com.haladhair.assign1; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.Button; import android.widget.CalendarView; import android.widget.TextView; import java.util.Date; public class Main2Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); final TextView txtv=findViewById(R.id.txtvi); final TextView txtvg=findViewById(R.id.textView7); final TextView sel=findViewById(R.id.dateselect); Bundle b = getIntent().getExtras(); String firsst = b.getString("firstnam"); String lasst = b.getString("lastnam"); final String datee = b.getString("thedatt"); txtv.setText(firsst + lasst); txtvg.setText(datee); // Intent incoming = getIntent(); // String date = incoming.getStringExtra("date"); // sel.setText(date); // sel.setText(datee); } }
1,116
0.685484
0.681004
48
22.229166
21.458525
57
false
false
0
0
0
0
0
0
0.5
false
false
11
f9b3071114999e0d6be028a6ac13a7724f76f623
1,649,267,507,820
6bcc2745c3326971af0d2f97416ed05443b63368
/src/main/java/com/wct/mybatis/mappers/AnnotationBasedMapper.java
8187f7bac16719085a245746a8af47fac77e3256
[]
no_license
wct710889210/java-
https://github.com/wct710889210/java-
4f8fa697ed968db965871f5a2b2ce593833faed4
61c4add262d0430a72608904ed0ed22dbb0563ea
refs/heads/master
2022-11-25T23:11:28.957000
2019-07-26T01:49:02
2019-07-26T01:49:02
155,478,471
0
0
null
false
2022-11-24T07:12:48
2018-10-31T01:13:37
2019-07-31T01:52:56
2022-11-24T07:12:45
136
0
0
7
Java
false
false
package com.wct.mybatis.mappers; import com.wct.mybatis.entity.Student; import org.apache.ibatis.annotations.Select; public interface AnnotationBasedMapper { @Select("select * from student where stud_id = #{id}") Student selectOne(int id); }
UTF-8
Java
252
java
AnnotationBasedMapper.java
Java
[]
null
[]
package com.wct.mybatis.mappers; import com.wct.mybatis.entity.Student; import org.apache.ibatis.annotations.Select; public interface AnnotationBasedMapper { @Select("select * from student where stud_id = #{id}") Student selectOne(int id); }
252
0.753968
0.753968
9
27
20.297783
58
false
false
0
0
0
0
0
0
0.444444
false
false
11
79484bab845a0ab4bfff60f3476d3714424baafe
13,786,845,055,993
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/17/17_ae81d5fd90e29511f2ef948452b4195b1031dbbe/BullpenWidgetProvider/17_ae81d5fd90e29511f2ef948452b4195b1031dbbe_BullpenWidgetProvider_t.java
08fe1faaf6c823bafea5d7bc703d3eeefc030656
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package com.smilo.bullpen; import android.app.AlarmManager; import android.app.PendingIntent; import android.appwidget.AppWidgetHost; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; import android.widget.RemoteViews; public class BullpenWidgetProvider extends AppWidgetProvider { private static final String TAG = "BullpenWidgetProvider"; // the pending intent to broadcast alarm. private static PendingIntent mSender; // the alarm manager to refresh bullpen widget periodically. private static AlarmManager mManager; // the url string to show selected item. private static String mSelectedItemUrl = null; // Flag to skip notifyAppWidgetViewDataChanged() call on boot. private static boolean mIsSkipFirstCallListViewService = true; private static boolean mIsSkipFirstCallContentService = true; private static boolean mSelectedPermitMobileConnection = false; private static int mSelectedRefreshTime = -1; private static String mSelectedBullpenBoardUrl = null; private static enum PENDING_INTENT_REQUEST_CODE { REQUEST_TOP, REQUEST_PREV, REQUEST_NEXT, REQUEST_REFRESH, REQUEST_SETTING, REQUEST_UNKNOWN, }; @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); String action = intent.getAction(); int pageNum = intent.getIntExtra(Constants.EXTRA_PAGE_NUM, Constants.DEFAULT_PAGE_NUM); int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); AppWidgetManager awm = AppWidgetManager.getInstance(context); int[] appWidgetIds = awm.getAppWidgetIds(new ComponentName(context, getClass())); Log.i(TAG, "onReceive - action[" + action + "], appWidgetId[" + appWidgetId + "], pageNum[" + pageNum + "], appWidgetsNum[" + appWidgetIds.length + "]"); for (int i = 0 ; i < appWidgetIds.length ; i++) { Log.i(TAG, "onReceive - current appWidgetId[" + appWidgetIds[i] + "]"); if (appWidgetId == appWidgetIds[i]) { // After setting configuration activity, this intent will be called. if (action.equals(Constants.ACTION_INIT_LIST)) { boolean selectedPermitMobileConnectionType = intent.getBooleanExtra(Constants.EXTRA_PERMIT_MOBILE_CONNECTION_TYPE, false); int selectedRefreshTimeType = intent.getIntExtra(Constants.EXTRA_REFRESH_TIME_TYPE, -1); int selectedBullpenBoardType = intent.getIntExtra(Constants.EXTRA_BULLPEN_BOARD_TYPE, -1); mSelectedPermitMobileConnection = selectedPermitMobileConnectionType; mSelectedRefreshTime = Utils.getRefreshTime(selectedRefreshTimeType); mSelectedBullpenBoardUrl = Utils.getBullpenBoardUrl(selectedBullpenBoardType); // Send broadcast intent to update mSelectedBullpenBoardUrl and pageNum variable on the BullpenListViewFactory. context.sendBroadcast(buildUpdateListUrlIntent(appWidgetId, Constants.DEFAULT_PAGE_NUM)); if (Utils.isInternetConnected(context, mSelectedPermitMobileConnection) == false) { setRemoteViewToShowLostInternetConnection(context, awm, appWidgetId, pageNum); return; } else { // Broadcast ACTION_SHOW_LIST intent. context.sendBroadcast(buildShowListIntent(context, appWidgetId, Constants.DEFAULT_PAGE_NUM)); } // This intent(ACTION_APPWIDGET_UPDATE) will be called periodically. // This intent(ACTION_SHOW_LIST) will be called when current item pressed. } else if ((action.equals(Constants.ACTION_APPWIDGET_UPDATE)) || (action.equals(Constants.ACTION_SHOW_LIST))) { if (Utils.isInternetConnected(context, mSelectedPermitMobileConnection) == false) { Log.e(TAG, "onReceive - Internet is not connected!"); return; } else { refreshAlarmSetting(context, appWidgetId, pageNum); setRemoteViewToShowList(context, awm, appWidgetId, pageNum); } } else if (action.equals(Constants.ACTION_REFRESH_LIST)){ // Send broadcast intent to update mSelectedBullpenBoardUrl and pageNum variable on the BullpenListViewFactory. context.sendBroadcast(buildUpdateListUrlIntent(appWidgetId, pageNum)); // Broadcast ACTION_SHOW_LIST intent. context.sendBroadcast(buildShowListIntent(context, appWidgetId, pageNum)); // This intent will be called when some item selected. // EXTRA_ITEM_URL was already filled in the BullpenListViewFactory - getViewAt(). } else if (action.equals(Constants.ACTION_SHOW_ITEM)) { removePreviousAlarm(); mSelectedItemUrl = intent.getStringExtra(Constants.EXTRA_ITEM_URL); // Send broadcast intent to update mSelectedItemUrl variable on the BullpenContentFactory. context.sendBroadcast(buildUpdateItemUrlIntent(appWidgetId, pageNum)); if (Utils.isInternetConnected(context, mSelectedPermitMobileConnection) == false) { Log.e(TAG, "onReceive - Internet is not connected!"); return; } else { setRemoteViewToShowItem(context, awm, appWidgetId, pageNum); } } } } } private Intent buildShowListIntent(Context context, int appWidgetId, int pageNum) { Intent intent = new Intent(context, BullpenWidgetProvider.class); intent.setAction(Constants.ACTION_SHOW_LIST); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); return intent; } private Intent buildUpdateListUrlIntent(int appWidgetId, int pageNum) { if (mSelectedBullpenBoardUrl == null) { Log.e(TAG, "buildUpdateListUrlIntent - mSelectedBullpenBoardUrl is null!"); return null; } Intent intent = new Intent(Constants.ACTION_UPDATE_LIST_URL); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.putExtra(Constants.EXTRA_LIST_URL, mSelectedBullpenBoardUrl); intent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); return intent; } private Intent buildUpdateItemUrlIntent(int appWidgetId, int pageNum) { if (mSelectedItemUrl == null) { Log.e(TAG, "buildUpdateItemUrlIntent - mSelectedItemUrl is null!"); return null; } Intent intent = new Intent(Constants.ACTION_UPDATE_ITEM_URL); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.putExtra(Constants.EXTRA_ITEM_URL, mSelectedItemUrl); intent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); return intent; } private Intent buildRefreshListIntent(Context context, int appWidgetId, int pageNum) { Intent intent = new Intent(context, BullpenWidgetProvider.class); intent.setAction(Constants.ACTION_REFRESH_LIST); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); return intent; } private Intent buildShowItemIntent(Context context, int appWidgetId, int pageNum, boolean isAddSelectedItemUri) { if (isAddSelectedItemUri == true && mSelectedItemUrl == null) { Log.e(TAG, "buildShowItemIntent - mSelectedItemUrl is null!"); return null; } Intent intent = new Intent(context, BullpenWidgetProvider.class); intent.setAction(Constants.ACTION_SHOW_ITEM); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); if (isAddSelectedItemUri) intent.putExtra(Constants.EXTRA_ITEM_URL, mSelectedItemUrl); intent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); return intent; } private Intent buildConfigurationActivityIntent(Context context, int appWidgetId) { Intent intent = new Intent(context, BullpenConfigurationActivity.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.putExtra(Constants.EXTRA_PERMIT_MOBILE_CONNECTION_TYPE, mSelectedPermitMobileConnection); intent.putExtra(Constants.EXTRA_REFRESH_TIME_TYPE, Utils.getRefreshTimeType(mSelectedRefreshTime)); intent.putExtra(Constants.EXTRA_BULLPEN_BOARD_TYPE, Utils.getBullpenBoardType(mSelectedBullpenBoardUrl)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } private void setRemoteViewToShowLostInternetConnection(Context context, AppWidgetManager awm, int appWidgetId, int pageNum) { Intent intent = null; PendingIntent pendingIntent = null; // Create new remoteViews RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.lost_internet_connection); // Set refresh button of the remoteViews. intent = buildRefreshListIntent(context, appWidgetId, pageNum); pendingIntent = PendingIntent.getBroadcast( context, PENDING_INTENT_REQUEST_CODE.REQUEST_REFRESH.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnLostInternetRefresh, pendingIntent); // Set setting button of the remoteViews. intent = buildConfigurationActivityIntent(context, appWidgetId); pendingIntent = PendingIntent.getActivity( context, PENDING_INTENT_REQUEST_CODE.REQUEST_SETTING.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnLostInternetSetting, pendingIntent); // Update widget. Log.i(TAG, "updateAppWidget [LostInternetConnection]"); awm.updateAppWidget(appWidgetId, rv); } private void setRemoteViewToShowList(Context context, AppWidgetManager awm, int appWidgetId, int pageNum) { Intent intent = null; PendingIntent pendingIntent = null; // Create new remoteViews. RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.list); // Set a remoteAdapter to the remoteViews. Intent serviceIntent = new Intent(context, BullpenListViewService.class); serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); serviceIntent.putExtra(Constants.EXTRA_LIST_URL, mSelectedBullpenBoardUrl); serviceIntent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); // views.setRemoteAdapter(R.id.listView, serviceIntent); // For API14+ rv.setRemoteAdapter(appWidgetId, R.id.listView, serviceIntent); rv.setScrollPosition(R.id.listView, 0); // Scroll to top // Set title of the remoteViews. if (Utils.isTodayBestUrl(mSelectedBullpenBoardUrl)) { rv.setTextViewText(R.id.textListTitle, Utils.getRemoteViewTitle(context, mSelectedBullpenBoardUrl)); rv.setViewVisibility(R.id.btnListNavPrev, View.GONE); rv.setViewVisibility(R.id.btnListNavNext, View.GONE); } else { rv.setTextViewText(R.id.textListTitle, Utils.getRemoteViewTitleWithPageNum(context, mSelectedBullpenBoardUrl, pageNum)); // Set prev button of the removeViews. rv.setViewVisibility(R.id.btnListNavPrev, View.VISIBLE); intent = buildRefreshListIntent(context, appWidgetId, (pageNum > Constants.DEFAULT_PAGE_NUM ? pageNum - 1 : pageNum)); pendingIntent = PendingIntent.getBroadcast( context, PENDING_INTENT_REQUEST_CODE.REQUEST_PREV.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnListNavPrev, pendingIntent); // Set next button of the remoteViews. rv.setViewVisibility(R.id.btnListNavNext, View.VISIBLE); intent = buildRefreshListIntent(context, appWidgetId, pageNum + 1); pendingIntent = PendingIntent.getBroadcast( context, PENDING_INTENT_REQUEST_CODE.REQUEST_NEXT.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnListNavNext, pendingIntent); } /* // Set top button of the remoteViews. intent = buildRefreshListIntent(context, appWidgetId, Constants.DEFAULT_PAGE_NUM); pendingIntent = PendingIntent.getBroadcast( context, PENDING_INTENT_REQUEST_CODE.REQUEST_TOP.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnListNavTop, pendingIntent); */ // Set refresh button of the remoteViews. intent = buildRefreshListIntent(context, appWidgetId, pageNum); pendingIntent = PendingIntent.getBroadcast( context, PENDING_INTENT_REQUEST_CODE.REQUEST_REFRESH.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnListRefresh, pendingIntent); // Set setting button of the remoteViews. intent = buildConfigurationActivityIntent(context, appWidgetId); pendingIntent = PendingIntent.getActivity( context, PENDING_INTENT_REQUEST_CODE.REQUEST_SETTING.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnListSetting, pendingIntent); // Set a pending intent for click event to the remoteViews. Intent clickIntent = buildShowItemIntent(context, appWidgetId, pageNum, false); PendingIntent linkPendingIntent = PendingIntent.getBroadcast( context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setPendingIntentTemplate(R.id.listView, linkPendingIntent); // Update widget. Log.i(TAG, "updateAppWidget [BaseballListViewService]"); awm.updateAppWidget(appWidgetId, rv); // On first call, we need not execute notifyAppWidgetViewDataChanged() // because onDataSetChanged() is called automatically after BullpenListViewFactory is created. if (mIsSkipFirstCallListViewService) { mIsSkipFirstCallListViewService = false; } else { Log.i(TAG, "notifyAppWidgetViewDataChanged [BaseballListViewService]"); awm.notifyAppWidgetViewDataChanged(appWidgetId, R.id.listView); } } private void setRemoteViewToShowItem(Context context, AppWidgetManager awm, int appWidgetId, int pageNum) { Intent intent = null; PendingIntent pendingIntent = null; // Create new remoteViews. RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.content); // Set a remoteAdapter to the remoteViews. Intent serviceIntent = new Intent(context, BullpenContentService.class); serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); serviceIntent.putExtra(Constants.EXTRA_ITEM_URL, mSelectedItemUrl); serviceIntent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); // views.setRemoteAdapter(R.id.contentView, serviceIntent); // For API14+ rv.setRemoteAdapter(appWidgetId, R.id.contentView, serviceIntent); //rv.setScrollPosition(R.id.contentView, 0); // Scroll to top // Set title of the remoteViews. rv.setTextViewText(R.id.textContentTitle, Utils.getRemoteViewTitle(context, mSelectedBullpenBoardUrl)); // Set top button of the remoteViews. intent = buildRefreshListIntent(context, appWidgetId, pageNum); pendingIntent = PendingIntent.getBroadcast( context, PENDING_INTENT_REQUEST_CODE.REQUEST_TOP.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnContentNavTop, pendingIntent); // Set refresh button of the remoteViews. intent = buildShowItemIntent(context, appWidgetId, pageNum, true); pendingIntent = PendingIntent.getBroadcast( context, PENDING_INTENT_REQUEST_CODE.REQUEST_REFRESH.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnContentRefresh, pendingIntent); // Set setting button of the remoteViews. intent = buildConfigurationActivityIntent(context, appWidgetId); pendingIntent = PendingIntent.getActivity( context, PENDING_INTENT_REQUEST_CODE.REQUEST_SETTING.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnContentSetting, pendingIntent); // Set a pending intent for click event to the remoteViews. Intent clickIntent = buildShowListIntent(context, appWidgetId, pageNum); PendingIntent linkPendingIntent = PendingIntent.getBroadcast( context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setPendingIntentTemplate(R.id.contentView, linkPendingIntent); // Update widget. Log.i(TAG, "updateAppWidget [BaseballContentService]"); awm.updateAppWidget(appWidgetId, rv); // On first call, we need not execute notifyAppWidgetViewDataChanged() // because onDataSetChanged() is called automatically after BullpenContentFactory is created. if (mIsSkipFirstCallContentService) { mIsSkipFirstCallContentService = false; } else { Log.i(TAG, "notifyAppWidgetViewDataChanged [BaseballContentService]"); awm.notifyAppWidgetViewDataChanged(appWidgetId, R.id.contentView); } } private void refreshAlarmSetting(Context context, int appWidgetId, int pageNum) { // If user does not want to refresh, just remove alarm setting. if (mSelectedRefreshTime == -1) { removePreviousAlarm(); // If user wants to refresh, set new alarm. } else { removePreviousAlarm(); setNewAlarm(context, appWidgetId, pageNum); } } private void setNewAlarm(Context context, int appWidgetId, int pageNum) { Log.i(TAG, "setNewAlarm - appWidgetId[" + appWidgetId + "], pageNum[" + pageNum + "]"); Intent updateIntent = new Intent(); updateIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); updateIntent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); updateIntent.setClass(context, BullpenWidgetProvider.class); long alarmTime = System.currentTimeMillis() + (mSelectedRefreshTime <= 0 ? Constants.DEFAULT_INTERVAL_AT_MILLIS : mSelectedRefreshTime); mSender = PendingIntent.getBroadcast(context, 0, updateIntent, 0); mManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mManager.set(AlarmManager.RTC, alarmTime, mSender); } private void removePreviousAlarm() { Log.i(TAG, "removePreviousAlarm"); if (mManager != null && mSender != null) { mSender.cancel(); mManager.cancel(mSender); } } public static void removeWidget(Context context, int appWidgetId) { AppWidgetHost host = new AppWidgetHost(context, 1); host.deleteAppWidgetId(appWidgetId); } @Override public void onUpdate(Context context, AppWidgetManager awm, int[] appWidgetIds) { Log.i(TAG, "onUpdate"); super.onUpdate(context, awm, appWidgetIds); } @Override public void onDeleted(Context context, int[] appWidgetIds) { Log.i(TAG, "onDeleted"); super.onDeleted(context, appWidgetIds); } @Override public void onDisabled(Context context) { Log.i(TAG, "onDisabled"); removePreviousAlarm(); super.onDisabled(context); } @Override public void onEnabled(Context context) { Log.i(TAG, "onEnabled"); removePreviousAlarm(); super.onEnabled(context); } }
UTF-8
Java
21,361
java
17_ae81d5fd90e29511f2ef948452b4195b1031dbbe_BullpenWidgetProvider_t.java
Java
[]
null
[]
package com.smilo.bullpen; import android.app.AlarmManager; import android.app.PendingIntent; import android.appwidget.AppWidgetHost; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; import android.widget.RemoteViews; public class BullpenWidgetProvider extends AppWidgetProvider { private static final String TAG = "BullpenWidgetProvider"; // the pending intent to broadcast alarm. private static PendingIntent mSender; // the alarm manager to refresh bullpen widget periodically. private static AlarmManager mManager; // the url string to show selected item. private static String mSelectedItemUrl = null; // Flag to skip notifyAppWidgetViewDataChanged() call on boot. private static boolean mIsSkipFirstCallListViewService = true; private static boolean mIsSkipFirstCallContentService = true; private static boolean mSelectedPermitMobileConnection = false; private static int mSelectedRefreshTime = -1; private static String mSelectedBullpenBoardUrl = null; private static enum PENDING_INTENT_REQUEST_CODE { REQUEST_TOP, REQUEST_PREV, REQUEST_NEXT, REQUEST_REFRESH, REQUEST_SETTING, REQUEST_UNKNOWN, }; @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); String action = intent.getAction(); int pageNum = intent.getIntExtra(Constants.EXTRA_PAGE_NUM, Constants.DEFAULT_PAGE_NUM); int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); AppWidgetManager awm = AppWidgetManager.getInstance(context); int[] appWidgetIds = awm.getAppWidgetIds(new ComponentName(context, getClass())); Log.i(TAG, "onReceive - action[" + action + "], appWidgetId[" + appWidgetId + "], pageNum[" + pageNum + "], appWidgetsNum[" + appWidgetIds.length + "]"); for (int i = 0 ; i < appWidgetIds.length ; i++) { Log.i(TAG, "onReceive - current appWidgetId[" + appWidgetIds[i] + "]"); if (appWidgetId == appWidgetIds[i]) { // After setting configuration activity, this intent will be called. if (action.equals(Constants.ACTION_INIT_LIST)) { boolean selectedPermitMobileConnectionType = intent.getBooleanExtra(Constants.EXTRA_PERMIT_MOBILE_CONNECTION_TYPE, false); int selectedRefreshTimeType = intent.getIntExtra(Constants.EXTRA_REFRESH_TIME_TYPE, -1); int selectedBullpenBoardType = intent.getIntExtra(Constants.EXTRA_BULLPEN_BOARD_TYPE, -1); mSelectedPermitMobileConnection = selectedPermitMobileConnectionType; mSelectedRefreshTime = Utils.getRefreshTime(selectedRefreshTimeType); mSelectedBullpenBoardUrl = Utils.getBullpenBoardUrl(selectedBullpenBoardType); // Send broadcast intent to update mSelectedBullpenBoardUrl and pageNum variable on the BullpenListViewFactory. context.sendBroadcast(buildUpdateListUrlIntent(appWidgetId, Constants.DEFAULT_PAGE_NUM)); if (Utils.isInternetConnected(context, mSelectedPermitMobileConnection) == false) { setRemoteViewToShowLostInternetConnection(context, awm, appWidgetId, pageNum); return; } else { // Broadcast ACTION_SHOW_LIST intent. context.sendBroadcast(buildShowListIntent(context, appWidgetId, Constants.DEFAULT_PAGE_NUM)); } // This intent(ACTION_APPWIDGET_UPDATE) will be called periodically. // This intent(ACTION_SHOW_LIST) will be called when current item pressed. } else if ((action.equals(Constants.ACTION_APPWIDGET_UPDATE)) || (action.equals(Constants.ACTION_SHOW_LIST))) { if (Utils.isInternetConnected(context, mSelectedPermitMobileConnection) == false) { Log.e(TAG, "onReceive - Internet is not connected!"); return; } else { refreshAlarmSetting(context, appWidgetId, pageNum); setRemoteViewToShowList(context, awm, appWidgetId, pageNum); } } else if (action.equals(Constants.ACTION_REFRESH_LIST)){ // Send broadcast intent to update mSelectedBullpenBoardUrl and pageNum variable on the BullpenListViewFactory. context.sendBroadcast(buildUpdateListUrlIntent(appWidgetId, pageNum)); // Broadcast ACTION_SHOW_LIST intent. context.sendBroadcast(buildShowListIntent(context, appWidgetId, pageNum)); // This intent will be called when some item selected. // EXTRA_ITEM_URL was already filled in the BullpenListViewFactory - getViewAt(). } else if (action.equals(Constants.ACTION_SHOW_ITEM)) { removePreviousAlarm(); mSelectedItemUrl = intent.getStringExtra(Constants.EXTRA_ITEM_URL); // Send broadcast intent to update mSelectedItemUrl variable on the BullpenContentFactory. context.sendBroadcast(buildUpdateItemUrlIntent(appWidgetId, pageNum)); if (Utils.isInternetConnected(context, mSelectedPermitMobileConnection) == false) { Log.e(TAG, "onReceive - Internet is not connected!"); return; } else { setRemoteViewToShowItem(context, awm, appWidgetId, pageNum); } } } } } private Intent buildShowListIntent(Context context, int appWidgetId, int pageNum) { Intent intent = new Intent(context, BullpenWidgetProvider.class); intent.setAction(Constants.ACTION_SHOW_LIST); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); return intent; } private Intent buildUpdateListUrlIntent(int appWidgetId, int pageNum) { if (mSelectedBullpenBoardUrl == null) { Log.e(TAG, "buildUpdateListUrlIntent - mSelectedBullpenBoardUrl is null!"); return null; } Intent intent = new Intent(Constants.ACTION_UPDATE_LIST_URL); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.putExtra(Constants.EXTRA_LIST_URL, mSelectedBullpenBoardUrl); intent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); return intent; } private Intent buildUpdateItemUrlIntent(int appWidgetId, int pageNum) { if (mSelectedItemUrl == null) { Log.e(TAG, "buildUpdateItemUrlIntent - mSelectedItemUrl is null!"); return null; } Intent intent = new Intent(Constants.ACTION_UPDATE_ITEM_URL); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.putExtra(Constants.EXTRA_ITEM_URL, mSelectedItemUrl); intent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); return intent; } private Intent buildRefreshListIntent(Context context, int appWidgetId, int pageNum) { Intent intent = new Intent(context, BullpenWidgetProvider.class); intent.setAction(Constants.ACTION_REFRESH_LIST); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); return intent; } private Intent buildShowItemIntent(Context context, int appWidgetId, int pageNum, boolean isAddSelectedItemUri) { if (isAddSelectedItemUri == true && mSelectedItemUrl == null) { Log.e(TAG, "buildShowItemIntent - mSelectedItemUrl is null!"); return null; } Intent intent = new Intent(context, BullpenWidgetProvider.class); intent.setAction(Constants.ACTION_SHOW_ITEM); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); if (isAddSelectedItemUri) intent.putExtra(Constants.EXTRA_ITEM_URL, mSelectedItemUrl); intent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); return intent; } private Intent buildConfigurationActivityIntent(Context context, int appWidgetId) { Intent intent = new Intent(context, BullpenConfigurationActivity.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.putExtra(Constants.EXTRA_PERMIT_MOBILE_CONNECTION_TYPE, mSelectedPermitMobileConnection); intent.putExtra(Constants.EXTRA_REFRESH_TIME_TYPE, Utils.getRefreshTimeType(mSelectedRefreshTime)); intent.putExtra(Constants.EXTRA_BULLPEN_BOARD_TYPE, Utils.getBullpenBoardType(mSelectedBullpenBoardUrl)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } private void setRemoteViewToShowLostInternetConnection(Context context, AppWidgetManager awm, int appWidgetId, int pageNum) { Intent intent = null; PendingIntent pendingIntent = null; // Create new remoteViews RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.lost_internet_connection); // Set refresh button of the remoteViews. intent = buildRefreshListIntent(context, appWidgetId, pageNum); pendingIntent = PendingIntent.getBroadcast( context, PENDING_INTENT_REQUEST_CODE.REQUEST_REFRESH.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnLostInternetRefresh, pendingIntent); // Set setting button of the remoteViews. intent = buildConfigurationActivityIntent(context, appWidgetId); pendingIntent = PendingIntent.getActivity( context, PENDING_INTENT_REQUEST_CODE.REQUEST_SETTING.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnLostInternetSetting, pendingIntent); // Update widget. Log.i(TAG, "updateAppWidget [LostInternetConnection]"); awm.updateAppWidget(appWidgetId, rv); } private void setRemoteViewToShowList(Context context, AppWidgetManager awm, int appWidgetId, int pageNum) { Intent intent = null; PendingIntent pendingIntent = null; // Create new remoteViews. RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.list); // Set a remoteAdapter to the remoteViews. Intent serviceIntent = new Intent(context, BullpenListViewService.class); serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); serviceIntent.putExtra(Constants.EXTRA_LIST_URL, mSelectedBullpenBoardUrl); serviceIntent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); // views.setRemoteAdapter(R.id.listView, serviceIntent); // For API14+ rv.setRemoteAdapter(appWidgetId, R.id.listView, serviceIntent); rv.setScrollPosition(R.id.listView, 0); // Scroll to top // Set title of the remoteViews. if (Utils.isTodayBestUrl(mSelectedBullpenBoardUrl)) { rv.setTextViewText(R.id.textListTitle, Utils.getRemoteViewTitle(context, mSelectedBullpenBoardUrl)); rv.setViewVisibility(R.id.btnListNavPrev, View.GONE); rv.setViewVisibility(R.id.btnListNavNext, View.GONE); } else { rv.setTextViewText(R.id.textListTitle, Utils.getRemoteViewTitleWithPageNum(context, mSelectedBullpenBoardUrl, pageNum)); // Set prev button of the removeViews. rv.setViewVisibility(R.id.btnListNavPrev, View.VISIBLE); intent = buildRefreshListIntent(context, appWidgetId, (pageNum > Constants.DEFAULT_PAGE_NUM ? pageNum - 1 : pageNum)); pendingIntent = PendingIntent.getBroadcast( context, PENDING_INTENT_REQUEST_CODE.REQUEST_PREV.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnListNavPrev, pendingIntent); // Set next button of the remoteViews. rv.setViewVisibility(R.id.btnListNavNext, View.VISIBLE); intent = buildRefreshListIntent(context, appWidgetId, pageNum + 1); pendingIntent = PendingIntent.getBroadcast( context, PENDING_INTENT_REQUEST_CODE.REQUEST_NEXT.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnListNavNext, pendingIntent); } /* // Set top button of the remoteViews. intent = buildRefreshListIntent(context, appWidgetId, Constants.DEFAULT_PAGE_NUM); pendingIntent = PendingIntent.getBroadcast( context, PENDING_INTENT_REQUEST_CODE.REQUEST_TOP.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnListNavTop, pendingIntent); */ // Set refresh button of the remoteViews. intent = buildRefreshListIntent(context, appWidgetId, pageNum); pendingIntent = PendingIntent.getBroadcast( context, PENDING_INTENT_REQUEST_CODE.REQUEST_REFRESH.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnListRefresh, pendingIntent); // Set setting button of the remoteViews. intent = buildConfigurationActivityIntent(context, appWidgetId); pendingIntent = PendingIntent.getActivity( context, PENDING_INTENT_REQUEST_CODE.REQUEST_SETTING.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnListSetting, pendingIntent); // Set a pending intent for click event to the remoteViews. Intent clickIntent = buildShowItemIntent(context, appWidgetId, pageNum, false); PendingIntent linkPendingIntent = PendingIntent.getBroadcast( context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setPendingIntentTemplate(R.id.listView, linkPendingIntent); // Update widget. Log.i(TAG, "updateAppWidget [BaseballListViewService]"); awm.updateAppWidget(appWidgetId, rv); // On first call, we need not execute notifyAppWidgetViewDataChanged() // because onDataSetChanged() is called automatically after BullpenListViewFactory is created. if (mIsSkipFirstCallListViewService) { mIsSkipFirstCallListViewService = false; } else { Log.i(TAG, "notifyAppWidgetViewDataChanged [BaseballListViewService]"); awm.notifyAppWidgetViewDataChanged(appWidgetId, R.id.listView); } } private void setRemoteViewToShowItem(Context context, AppWidgetManager awm, int appWidgetId, int pageNum) { Intent intent = null; PendingIntent pendingIntent = null; // Create new remoteViews. RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.content); // Set a remoteAdapter to the remoteViews. Intent serviceIntent = new Intent(context, BullpenContentService.class); serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); serviceIntent.putExtra(Constants.EXTRA_ITEM_URL, mSelectedItemUrl); serviceIntent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); // views.setRemoteAdapter(R.id.contentView, serviceIntent); // For API14+ rv.setRemoteAdapter(appWidgetId, R.id.contentView, serviceIntent); //rv.setScrollPosition(R.id.contentView, 0); // Scroll to top // Set title of the remoteViews. rv.setTextViewText(R.id.textContentTitle, Utils.getRemoteViewTitle(context, mSelectedBullpenBoardUrl)); // Set top button of the remoteViews. intent = buildRefreshListIntent(context, appWidgetId, pageNum); pendingIntent = PendingIntent.getBroadcast( context, PENDING_INTENT_REQUEST_CODE.REQUEST_TOP.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnContentNavTop, pendingIntent); // Set refresh button of the remoteViews. intent = buildShowItemIntent(context, appWidgetId, pageNum, true); pendingIntent = PendingIntent.getBroadcast( context, PENDING_INTENT_REQUEST_CODE.REQUEST_REFRESH.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnContentRefresh, pendingIntent); // Set setting button of the remoteViews. intent = buildConfigurationActivityIntent(context, appWidgetId); pendingIntent = PendingIntent.getActivity( context, PENDING_INTENT_REQUEST_CODE.REQUEST_SETTING.ordinal(), intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.btnContentSetting, pendingIntent); // Set a pending intent for click event to the remoteViews. Intent clickIntent = buildShowListIntent(context, appWidgetId, pageNum); PendingIntent linkPendingIntent = PendingIntent.getBroadcast( context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setPendingIntentTemplate(R.id.contentView, linkPendingIntent); // Update widget. Log.i(TAG, "updateAppWidget [BaseballContentService]"); awm.updateAppWidget(appWidgetId, rv); // On first call, we need not execute notifyAppWidgetViewDataChanged() // because onDataSetChanged() is called automatically after BullpenContentFactory is created. if (mIsSkipFirstCallContentService) { mIsSkipFirstCallContentService = false; } else { Log.i(TAG, "notifyAppWidgetViewDataChanged [BaseballContentService]"); awm.notifyAppWidgetViewDataChanged(appWidgetId, R.id.contentView); } } private void refreshAlarmSetting(Context context, int appWidgetId, int pageNum) { // If user does not want to refresh, just remove alarm setting. if (mSelectedRefreshTime == -1) { removePreviousAlarm(); // If user wants to refresh, set new alarm. } else { removePreviousAlarm(); setNewAlarm(context, appWidgetId, pageNum); } } private void setNewAlarm(Context context, int appWidgetId, int pageNum) { Log.i(TAG, "setNewAlarm - appWidgetId[" + appWidgetId + "], pageNum[" + pageNum + "]"); Intent updateIntent = new Intent(); updateIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); updateIntent.putExtra(Constants.EXTRA_PAGE_NUM, pageNum); updateIntent.setClass(context, BullpenWidgetProvider.class); long alarmTime = System.currentTimeMillis() + (mSelectedRefreshTime <= 0 ? Constants.DEFAULT_INTERVAL_AT_MILLIS : mSelectedRefreshTime); mSender = PendingIntent.getBroadcast(context, 0, updateIntent, 0); mManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mManager.set(AlarmManager.RTC, alarmTime, mSender); } private void removePreviousAlarm() { Log.i(TAG, "removePreviousAlarm"); if (mManager != null && mSender != null) { mSender.cancel(); mManager.cancel(mSender); } } public static void removeWidget(Context context, int appWidgetId) { AppWidgetHost host = new AppWidgetHost(context, 1); host.deleteAppWidgetId(appWidgetId); } @Override public void onUpdate(Context context, AppWidgetManager awm, int[] appWidgetIds) { Log.i(TAG, "onUpdate"); super.onUpdate(context, awm, appWidgetIds); } @Override public void onDeleted(Context context, int[] appWidgetIds) { Log.i(TAG, "onDeleted"); super.onDeleted(context, appWidgetIds); } @Override public void onDisabled(Context context) { Log.i(TAG, "onDisabled"); removePreviousAlarm(); super.onDisabled(context); } @Override public void onEnabled(Context context) { Log.i(TAG, "onEnabled"); removePreviousAlarm(); super.onEnabled(context); } }
21,361
0.65334
0.652451
424
49.372643
35.467602
145
false
false
0
0
0
0
0
0
1.063679
false
false
11
cd5a0cd5bf971d6026f65764ffad43f1acd82fad
21,311,627,790,356
c40464d9aeec73ce5e0030248523aba0cd1e25b6
/sharding-proxy/server/src/main/java/com/neo/demo/shardingproxy/service/OrderService.java
14679265f892557e1fb1511b4f8e070bc8c30060
[]
no_license
Gryffindor-CN/neo-demo
https://github.com/Gryffindor-CN/neo-demo
09a7a085667788604c629773d804cdf4bcca86b1
4bfe2f12ddd153ee0f2a3f4f9564d341d6b59ace
refs/heads/master
2023-07-09T20:16:33.808000
2021-02-09T02:13:52
2021-02-09T02:13:52
171,977,579
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.neo.demo.shardingproxy.service; import com.neo.demo.shardingproxy.entity.Order; import org.springframework.stereotype.Service; import java.util.List; @Service public interface OrderService { void createOrder(); Order findById(Long id); List<Order> findAll(); }
UTF-8
Java
291
java
OrderService.java
Java
[]
null
[]
package com.neo.demo.shardingproxy.service; import com.neo.demo.shardingproxy.entity.Order; import org.springframework.stereotype.Service; import java.util.List; @Service public interface OrderService { void createOrder(); Order findById(Long id); List<Order> findAll(); }
291
0.756014
0.756014
16
17.1875
17.582729
47
false
false
0
0
0
0
0
0
0.4375
false
false
11
e63d907c2aa31b8ec48441ef6329c821e8c966b8
12,120,397,765,837
e19998dff4ab7e5c21fd842c06ac82e673c6c8f7
/src/br/com/uninassau/ead/programacao1/unidade3/Addition.java
188bbe872a8b00893cd70d61f54e19b305109385
[ "MIT" ]
permissive
jfranciscos4/uninassau-ead-programacao1
https://github.com/jfranciscos4/uninassau-ead-programacao1
c4c5b0ba6c5f923a20688f1453d00713abe68847
2ea14325d2a27405e77c2f9bb01ad23b830f73e2
HEAD
2016-08-10T17:43:47.095000
2016-02-24T00:36:43
2016-02-24T00:36:43
47,428,033
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Figura 3.2: Addition.java * Programa de adição que utiliza JOptionPAne para entrada e saída. * */ package br.com.uninassau.ead.programacao1.unidade3; import javax.swing.JOptionPane; /** * @author jfranciscos4 * */ public class Addition { /** * @param args */ public static void main(String[] args) { // obtém a entreada de usuário a partir dos diálogos de entrada // JOptionPane String firstNumber = JOptionPane.showInputDialog("Enter first integer"); String secondNumber = JOptionPane.showInputDialog("Enter second integer"); // converte String em valores int para utilização em um cálculo int number1 = Integer.parseInt(firstNumber); int number2 = Integer.parseInt(secondNumber); int sum = number1 + number2; // soma os números // exibe o resultado em um diálogo de mensagem JOptionPane JOptionPane.showMessageDialog(null, "this sum is " + sum, "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE); } }
ISO-8859-1
Java
960
java
Addition.java
Java
[ { "context": ";\n\nimport javax.swing.JOptionPane;\n\n/**\n * @author jfranciscos4\n *\n */\npublic class Addition {\n\n\t/**\n\t * @param a", "end": 222, "score": 0.9996086955070496, "start": 210, "tag": "USERNAME", "value": "jfranciscos4" } ]
null
[]
/** * Figura 3.2: Addition.java * Programa de adição que utiliza JOptionPAne para entrada e saída. * */ package br.com.uninassau.ead.programacao1.unidade3; import javax.swing.JOptionPane; /** * @author jfranciscos4 * */ public class Addition { /** * @param args */ public static void main(String[] args) { // obtém a entreada de usuário a partir dos diálogos de entrada // JOptionPane String firstNumber = JOptionPane.showInputDialog("Enter first integer"); String secondNumber = JOptionPane.showInputDialog("Enter second integer"); // converte String em valores int para utilização em um cálculo int number1 = Integer.parseInt(firstNumber); int number2 = Integer.parseInt(secondNumber); int sum = number1 + number2; // soma os números // exibe o resultado em um diálogo de mensagem JOptionPane JOptionPane.showMessageDialog(null, "this sum is " + sum, "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE); } }
960
0.728135
0.718651
34
26.911764
29.528021
110
false
false
0
0
0
0
0
0
1.058824
false
false
11
ce39680e9031072a1f3c5105b284616c9eb9f3f3
16,045,997,863,550
6a0ce0f59facca35b8a176f54de8e4028da5698e
/JavaTestMahesh/src/com/mahesh/encapsulation/EmployeeDetails.java
495235fe8ff6310e578ecf04e545997aa36ee743
[]
no_license
SoftgenAndoird/SoftgenJava
https://github.com/SoftgenAndoird/SoftgenJava
cb1d4990e7df13e4436dfafb629bdab0fc8b5c7e
0f332f5ef1858e6342bf97cbafe67297787838c0
refs/heads/master
2021-01-17T10:17:08.710000
2016-06-15T16:46:14
2016-06-15T16:46:14
57,441,750
7
0
null
false
2016-06-15T16:46:15
2016-04-30T12:52:46
2016-05-27T10:45:52
2016-06-15T16:46:14
136
3
0
0
Java
null
null
package com.mahesh.encapsulation; public class EmployeeDetails { public static void main(String[] args) { Employee obj = new Employee(); obj.empAddress = "BTM"; obj.empAge = 32; obj.empBatch = 32522; obj.empGender = "Male"; obj.empId = 5; obj.empNme = "Softgen"; obj.empSalary = 59324; obj.EmployeeAttributes(); } }
UTF-8
Java
338
java
EmployeeDetails.java
Java
[ { "context": "Gender = \"Male\";\n\t\tobj.empId = 5;\n\t\tobj.empNme = \"Softgen\";\n\t\tobj.empSalary = 59324;\n\t\tobj.EmployeeAttribut", "end": 276, "score": 0.9124066829681396, "start": 269, "tag": "NAME", "value": "Softgen" } ]
null
[]
package com.mahesh.encapsulation; public class EmployeeDetails { public static void main(String[] args) { Employee obj = new Employee(); obj.empAddress = "BTM"; obj.empAge = 32; obj.empBatch = 32522; obj.empGender = "Male"; obj.empId = 5; obj.empNme = "Softgen"; obj.empSalary = 59324; obj.EmployeeAttributes(); } }
338
0.677515
0.639053
16
20.125
12.51936
41
false
false
0
0
0
0
0
0
1.875
false
false
11
2679d0c410b97122593800e2b8d5aa1cac4aafbd
35,854,387,006,621
f1bf91aa0d75cb801220c3619a94a722b2cc149e
/src/main/java/com/riekr/mame/utils/SerUtils.java
31e7070c384ba6bd491a2b0ea34119b8396c112b
[]
no_license
Riekr/Mame_Java_Bridge
https://github.com/Riekr/Mame_Java_Bridge
6df2244ae5ca6b972e73832c653e2d1e03fe5016
c91cd542c68008a6c4190a9d3efd41df9e9f24f2
refs/heads/master
2020-04-04T06:53:56.635000
2018-12-04T22:15:33
2018-12-04T22:15:33
155,760,302
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.riekr.mame.utils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.nio.file.Path; import java.util.*; public final class SerUtils { private SerUtils() { } public static void writePath(@NotNull ObjectOutput out, @Nullable Path path) throws IOException { if (path == null) out.writeObject(null); else out.writeObject(path.toString()); } public static Path readPath(@NotNull ObjectInput in) throws IOException, ClassNotFoundException { Object o = in.readObject(); if (o == null) return null; return Path.of((String) o); } public static void writePaths(@NotNull ObjectOutput out, @Nullable Collection<Path> pathSet) throws IOException { if (pathSet == null) { out.writeInt(-1); return; } out.writeInt(pathSet.size()); for (Path p : pathSet) writePath(out, p); } public static void writePaths(@NotNull ObjectOutput out, @Nullable Map<Path, ?> pathMap) throws IOException { if (pathMap == null) { out.writeInt(-1); return; } out.writeInt(pathMap.size()); for (Map.Entry<Path, ?> e : pathMap.entrySet()) { writePath(out, e.getKey()); out.writeObject(e.getValue()); } } public static Set<Path> readPathSet(@NotNull ObjectInput in) throws IOException, ClassNotFoundException { final int sz = in.readInt(); if (sz < 0) return null; Set<Path> res = new LinkedHashSet<>(sz); for (int i = 0; i < sz; i++) res.add(readPath(in)); return res; } public static <T> Map<Path, T> readPathMap(@NotNull ObjectInput in) throws IOException, ClassNotFoundException { final int sz = in.readInt(); if (sz < 0) return null; HashMap<Path, T> res = new HashMap<>(sz); for (int i = 0; i < sz; i++) //noinspection unchecked res.put(readPath(in), (T) in.readObject()); return res; } }
UTF-8
Java
1,914
java
SerUtils.java
Java
[]
null
[]
package com.riekr.mame.utils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.nio.file.Path; import java.util.*; public final class SerUtils { private SerUtils() { } public static void writePath(@NotNull ObjectOutput out, @Nullable Path path) throws IOException { if (path == null) out.writeObject(null); else out.writeObject(path.toString()); } public static Path readPath(@NotNull ObjectInput in) throws IOException, ClassNotFoundException { Object o = in.readObject(); if (o == null) return null; return Path.of((String) o); } public static void writePaths(@NotNull ObjectOutput out, @Nullable Collection<Path> pathSet) throws IOException { if (pathSet == null) { out.writeInt(-1); return; } out.writeInt(pathSet.size()); for (Path p : pathSet) writePath(out, p); } public static void writePaths(@NotNull ObjectOutput out, @Nullable Map<Path, ?> pathMap) throws IOException { if (pathMap == null) { out.writeInt(-1); return; } out.writeInt(pathMap.size()); for (Map.Entry<Path, ?> e : pathMap.entrySet()) { writePath(out, e.getKey()); out.writeObject(e.getValue()); } } public static Set<Path> readPathSet(@NotNull ObjectInput in) throws IOException, ClassNotFoundException { final int sz = in.readInt(); if (sz < 0) return null; Set<Path> res = new LinkedHashSet<>(sz); for (int i = 0; i < sz; i++) res.add(readPath(in)); return res; } public static <T> Map<Path, T> readPathMap(@NotNull ObjectInput in) throws IOException, ClassNotFoundException { final int sz = in.readInt(); if (sz < 0) return null; HashMap<Path, T> res = new HashMap<>(sz); for (int i = 0; i < sz; i++) //noinspection unchecked res.put(readPath(in), (T) in.readObject()); return res; } }
1,914
0.687565
0.684431
73
25.219177
27.882948
114
false
false
0
0
0
0
0
0
2.136986
false
false
11
185e6db346adb5eea7577b9899eb805351e62440
35,381,940,604,056
a4a51084cfb715c7076c810520542af38a854868
/src/main/java/com/tencent/liteav/basic/d/d.java
9cf26370c8bc98d4881e0d7a26cccf37f3e44e8a
[]
no_license
BharathPalanivelu/repotest
https://github.com/BharathPalanivelu/repotest
ddaf56a94eb52867408e0e769f35bef2d815da72
f78ae38738d2ba6c9b9b4049f3092188fabb5b59
refs/heads/master
2020-09-30T18:55:04.802000
2019-12-02T10:52:08
2019-12-02T10:52:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tencent.liteav.basic.d; import android.graphics.Bitmap; import android.graphics.Matrix; import android.opengl.GLES20; import android.os.HandlerThread; import android.view.Surface; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.tencent.liteav.basic.d.f; import com.tencent.liteav.basic.log.TXCLog; import java.nio.ByteBuffer; import javax.microedition.khronos.egl.EGLContext; public class d implements f.a { /* renamed from: a reason: collision with root package name */ private volatile HandlerThread f31272a = null; /* renamed from: b reason: collision with root package name */ private volatile f f31273b = null; /* renamed from: c reason: collision with root package name */ private g f31274c = null; /* renamed from: d reason: collision with root package name */ private int f31275d = 0; /* renamed from: e reason: collision with root package name */ private boolean f31276e = false; /* renamed from: f reason: collision with root package name */ private float f31277f = 1.0f; /* renamed from: g reason: collision with root package name */ private float f31278g = 1.0f; private int h = 0; private int i = 0; private boolean j = false; private n k = null; private boolean l = false; public void d() { } public void a(EGLContext eGLContext, Surface surface) { TXCLog.i("TXGLSurfaceRenderThread", "surface-render: surface render start " + surface); b(eGLContext, surface); } public void a() { TXCLog.i("TXGLSurfaceRenderThread", "surface-render: surface render stop "); f(); } public Surface b() { Surface b2; synchronized (this) { b2 = this.f31273b != null ? this.f31273b.b() : null; } return b2; } public void a(Runnable runnable) { synchronized (this) { if (this.f31273b != null) { this.f31273b.post(runnable); } } } public void a(int i2, boolean z, int i3, int i4, int i5, int i6, int i7, boolean z2) { GLES20.glFinish(); synchronized (this) { if (this.f31273b != null) { final int i8 = i2; final boolean z3 = z; final int i9 = i3; final int i10 = i4; final int i11 = i5; final int i12 = i6; final int i13 = i7; final boolean z4 = z2; this.f31273b.post(new Runnable() { public void run() { try { d.this.b(i8, z3, i9, i10, i11, i12, i13, z4); } catch (Exception unused) { TXCLog.e("TXGLSurfaceRenderThread", "surface-render: render texture error occurred!"); } } }); } } } public void a(n nVar) { this.k = nVar; this.j = true; } public void c() { this.f31274c = new g(); if (this.f31274c.a()) { this.f31274c.a(k.f31351e, k.a(j.NORMAL, false, false)); } } public void e() { g gVar = this.f31274c; if (gVar != null) { gVar.d(); this.f31274c = null; } } private void b(EGLContext eGLContext, Surface surface) { f(); synchronized (this) { this.f31272a = new HandlerThread("TXGLSurfaceRenderThread"); this.f31272a.start(); this.f31273b = new f(this.f31272a.getLooper()); this.f31273b.a((f.a) this); this.f31273b.f31309g = eGLContext; this.f31273b.f31305c = surface; TXCLog.w("TXGLSurfaceRenderThread", "surface-render: create gl thread " + this.f31272a.getName()); } a(100); } private void f() { synchronized (this) { if (this.f31273b != null) { f.a(this.f31273b, this.f31272a); TXCLog.w("TXGLSurfaceRenderThread", "surface-render: destroy gl thread"); } this.f31273b = null; this.f31272a = null; } } private void a(int i2) { synchronized (this) { if (this.f31273b != null) { this.f31273b.sendEmptyMessage(i2); } } } /* access modifiers changed from: private */ public void b(int i2, boolean z, int i3, int i4, int i5, int i6, int i7, boolean z2) { boolean z3 = z; int i8 = i3; int i9 = i6; int i10 = i7; if (i9 != 0 && i10 != 0 && this.f31274c != null) { if (this.l) { this.l = false; return; } if (z2) { GLES20.glClearColor(BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED, 1.0f); GLES20.glClear(16640); GLES20.glBindFramebuffer(36160, 0); if (this.f31273b != null) { this.f31273b.c(); } this.l = true; } int i11 = i4 != 0 ? i4 : i9; int i12 = i5 != 0 ? i5 : i10; this.h = i11; this.i = i12; GLES20.glViewport(0, 0, i11, i12); float f2 = i12 != 0 ? ((float) i11) / ((float) i12) : 1.0f; float f3 = i10 != 0 ? ((float) i9) / ((float) i10) : 1.0f; if (!(this.f31276e == z3 && this.f31275d == i8 && this.f31277f == f2 && this.f31278g == f3)) { this.f31276e = z3; this.f31275d = i8; this.f31277f = f2; this.f31278g = f3; int i13 = (720 - this.f31275d) % 360; boolean z4 = i13 == 90 || i13 == 270; int i14 = z4 ? i12 : i11; if (z4) { i12 = i11; } this.f31274c.a(i6, i7, i13, k.a(j.NORMAL, false, true), ((float) i14) / ((float) i12), z4 ? false : this.f31276e, z4 ? this.f31276e : false); if (z4) { this.f31274c.g(); } else { this.f31274c.h(); } } GLES20.glClearColor(BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED, 1.0f); GLES20.glClear(16640); GLES20.glBindFramebuffer(36160, 0); this.f31274c.a(i2); g(); if (this.f31273b != null) { this.f31273b.c(); } } } private void g() { if (this.j) { int i2 = this.h; if (i2 != 0) { int i3 = this.i; if (i3 != 0) { boolean z = i2 <= i3; int i4 = this.i; int i5 = this.h; if (i4 < i5) { i4 = i5; } int i6 = this.i; int i7 = this.h; if (i6 >= i7) { i6 = i7; } if (z) { int i8 = i6; i6 = i4; i4 = i8; } ByteBuffer allocate = ByteBuffer.allocate(i4 * i6 * 4); Bitmap createBitmap = Bitmap.createBitmap(i4, i6, Bitmap.Config.ARGB_8888); allocate.position(0); GLES20.glReadPixels(0, 0, i4, i6, 6408, 5121, allocate); final n nVar = this.k; if (nVar != null) { final ByteBuffer byteBuffer = allocate; final Bitmap bitmap = createBitmap; final int i9 = i4; final int i10 = i6; new Thread(new Runnable() { public void run() { byteBuffer.position(0); bitmap.copyPixelsFromBuffer(byteBuffer); Matrix matrix = new Matrix(); matrix.setScale(1.0f, -1.0f); nVar.a(Bitmap.createBitmap(bitmap, 0, 0, i9, i10, matrix, false)); bitmap.recycle(); } }).start(); } } } this.k = null; this.j = false; } } }
UTF-8
Java
8,677
java
d.java
Java
[]
null
[]
package com.tencent.liteav.basic.d; import android.graphics.Bitmap; import android.graphics.Matrix; import android.opengl.GLES20; import android.os.HandlerThread; import android.view.Surface; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.tencent.liteav.basic.d.f; import com.tencent.liteav.basic.log.TXCLog; import java.nio.ByteBuffer; import javax.microedition.khronos.egl.EGLContext; public class d implements f.a { /* renamed from: a reason: collision with root package name */ private volatile HandlerThread f31272a = null; /* renamed from: b reason: collision with root package name */ private volatile f f31273b = null; /* renamed from: c reason: collision with root package name */ private g f31274c = null; /* renamed from: d reason: collision with root package name */ private int f31275d = 0; /* renamed from: e reason: collision with root package name */ private boolean f31276e = false; /* renamed from: f reason: collision with root package name */ private float f31277f = 1.0f; /* renamed from: g reason: collision with root package name */ private float f31278g = 1.0f; private int h = 0; private int i = 0; private boolean j = false; private n k = null; private boolean l = false; public void d() { } public void a(EGLContext eGLContext, Surface surface) { TXCLog.i("TXGLSurfaceRenderThread", "surface-render: surface render start " + surface); b(eGLContext, surface); } public void a() { TXCLog.i("TXGLSurfaceRenderThread", "surface-render: surface render stop "); f(); } public Surface b() { Surface b2; synchronized (this) { b2 = this.f31273b != null ? this.f31273b.b() : null; } return b2; } public void a(Runnable runnable) { synchronized (this) { if (this.f31273b != null) { this.f31273b.post(runnable); } } } public void a(int i2, boolean z, int i3, int i4, int i5, int i6, int i7, boolean z2) { GLES20.glFinish(); synchronized (this) { if (this.f31273b != null) { final int i8 = i2; final boolean z3 = z; final int i9 = i3; final int i10 = i4; final int i11 = i5; final int i12 = i6; final int i13 = i7; final boolean z4 = z2; this.f31273b.post(new Runnable() { public void run() { try { d.this.b(i8, z3, i9, i10, i11, i12, i13, z4); } catch (Exception unused) { TXCLog.e("TXGLSurfaceRenderThread", "surface-render: render texture error occurred!"); } } }); } } } public void a(n nVar) { this.k = nVar; this.j = true; } public void c() { this.f31274c = new g(); if (this.f31274c.a()) { this.f31274c.a(k.f31351e, k.a(j.NORMAL, false, false)); } } public void e() { g gVar = this.f31274c; if (gVar != null) { gVar.d(); this.f31274c = null; } } private void b(EGLContext eGLContext, Surface surface) { f(); synchronized (this) { this.f31272a = new HandlerThread("TXGLSurfaceRenderThread"); this.f31272a.start(); this.f31273b = new f(this.f31272a.getLooper()); this.f31273b.a((f.a) this); this.f31273b.f31309g = eGLContext; this.f31273b.f31305c = surface; TXCLog.w("TXGLSurfaceRenderThread", "surface-render: create gl thread " + this.f31272a.getName()); } a(100); } private void f() { synchronized (this) { if (this.f31273b != null) { f.a(this.f31273b, this.f31272a); TXCLog.w("TXGLSurfaceRenderThread", "surface-render: destroy gl thread"); } this.f31273b = null; this.f31272a = null; } } private void a(int i2) { synchronized (this) { if (this.f31273b != null) { this.f31273b.sendEmptyMessage(i2); } } } /* access modifiers changed from: private */ public void b(int i2, boolean z, int i3, int i4, int i5, int i6, int i7, boolean z2) { boolean z3 = z; int i8 = i3; int i9 = i6; int i10 = i7; if (i9 != 0 && i10 != 0 && this.f31274c != null) { if (this.l) { this.l = false; return; } if (z2) { GLES20.glClearColor(BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED, 1.0f); GLES20.glClear(16640); GLES20.glBindFramebuffer(36160, 0); if (this.f31273b != null) { this.f31273b.c(); } this.l = true; } int i11 = i4 != 0 ? i4 : i9; int i12 = i5 != 0 ? i5 : i10; this.h = i11; this.i = i12; GLES20.glViewport(0, 0, i11, i12); float f2 = i12 != 0 ? ((float) i11) / ((float) i12) : 1.0f; float f3 = i10 != 0 ? ((float) i9) / ((float) i10) : 1.0f; if (!(this.f31276e == z3 && this.f31275d == i8 && this.f31277f == f2 && this.f31278g == f3)) { this.f31276e = z3; this.f31275d = i8; this.f31277f = f2; this.f31278g = f3; int i13 = (720 - this.f31275d) % 360; boolean z4 = i13 == 90 || i13 == 270; int i14 = z4 ? i12 : i11; if (z4) { i12 = i11; } this.f31274c.a(i6, i7, i13, k.a(j.NORMAL, false, true), ((float) i14) / ((float) i12), z4 ? false : this.f31276e, z4 ? this.f31276e : false); if (z4) { this.f31274c.g(); } else { this.f31274c.h(); } } GLES20.glClearColor(BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED, 1.0f); GLES20.glClear(16640); GLES20.glBindFramebuffer(36160, 0); this.f31274c.a(i2); g(); if (this.f31273b != null) { this.f31273b.c(); } } } private void g() { if (this.j) { int i2 = this.h; if (i2 != 0) { int i3 = this.i; if (i3 != 0) { boolean z = i2 <= i3; int i4 = this.i; int i5 = this.h; if (i4 < i5) { i4 = i5; } int i6 = this.i; int i7 = this.h; if (i6 >= i7) { i6 = i7; } if (z) { int i8 = i6; i6 = i4; i4 = i8; } ByteBuffer allocate = ByteBuffer.allocate(i4 * i6 * 4); Bitmap createBitmap = Bitmap.createBitmap(i4, i6, Bitmap.Config.ARGB_8888); allocate.position(0); GLES20.glReadPixels(0, 0, i4, i6, 6408, 5121, allocate); final n nVar = this.k; if (nVar != null) { final ByteBuffer byteBuffer = allocate; final Bitmap bitmap = createBitmap; final int i9 = i4; final int i10 = i6; new Thread(new Runnable() { public void run() { byteBuffer.position(0); bitmap.copyPixelsFromBuffer(byteBuffer); Matrix matrix = new Matrix(); matrix.setScale(1.0f, -1.0f); nVar.a(Bitmap.createBitmap(bitmap, 0, 0, i9, i10, matrix, false)); bitmap.recycle(); } }).start(); } } } this.k = null; this.j = false; } } }
8,677
0.463063
0.399101
254
33.161419
25.745146
157
false
false
0
0
0
0
0
0
0.779528
false
false
11
b3003f3ff80542b63e581bf36a63709ed2050256
39,015,482,921,317
ff25ddcf93c94258d42c973ce7189ad4d2ca3571
/pet-api/src/main/java/com/anvy/petcare/modules/wx/WxConfig.java
144a3e18007857967bc38a104eb8cb4ca63956c6
[]
no_license
laogq/petcare
https://github.com/laogq/petcare
d8aa726dfb1bd21f1c1fda7a8e4948145398d913
2a465eafc4cb74e2163d7b9f4fed96bc0774202d
refs/heads/main
2023-07-05T13:01:16.949000
2021-08-05T10:30:34
2021-08-05T10:30:34
330,654,657
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.anvy.petcare.modules.wx; import com.alibaba.fastjson.JSONObject; import com.anvy.petcare.config.ApplicationContextRegister; import com.anvy.petcare.modules.wx.util.MsgModel; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import lombok.extern.slf4j.Slf4j; import netscape.javascript.JSObject; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextInitializer; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; @Slf4j @RestController public class WxConfig { @Resource private RestTemplate restTemplate; @Value("${wx.secretKey}") private String secretKey; @Value("${wx.access_token_url}") private String tokenUrl; private static JSONObject accessTokenJson = new JSONObject(); private static String accessToken; @RequestMapping("wxConfig") public String verifyConfig(HttpServletRequest request, HttpServletResponse response) throws IOException { log.info(" PARAM VAL: >>>signature" + request.getParameter("signature")); log.info(" PARAM VAL: >>>timestamp" + request.getParameter("timestamp")); log.info(" PARAM VAL: >>>nonce" + request.getParameter("nonce")); log.info(" PARAM VAL: >>>echostr" + request.getParameter("echostr")); String echostr = request.getParameter("echostr"); ServletInputStream inputStream = request.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8")); String msg = ""; String str = ""; while((str = reader.readLine()) != null){ msg += str; } String openid = request.getParameter("openid"); log.info("用户OPENID:{}",openid); log.info("用户发送的消息:{}",msg); String anvy = MsgModel.normalMsg(openid,"gh_eb62f9fe0cb6"); log.info("返回用户的消息:{}",anvy); return anvy; } @RequestMapping("sendMsg") public void sendMsg(HttpServletRequest request, HttpServletResponse response) throws IOException { JSONObject object = new JSONObject(); object.put("touser","o18sY6-KFL2Wx7SVjM5XjdR6dElg"); object.put("msgtype","text"); JSONObject obj = new JSONObject(); obj.put("content","abc"); object.put("text",obj); HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_JSON); HttpEntity<JSONObject> entity = new HttpEntity<>(object,header); addKf(); log.info("post url====={}","https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken); ResponseEntity<JSONObject> result = restTemplate.postForEntity("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken, entity, JSONObject.class); JSONObject body = result.getBody(); log.info("send Msg::{}",body); } private void addKf(){ validToken(); String url = "https://api.weixin.qq.com/customservice/kfaccount/add?access_token="+accessToken; JSONObject data = new JSONObject(); data.put("kf_account","test1@test"); data.put("nickname","小小客服"); data.put("password","pswmd5"); HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_JSON); HttpEntity<JSONObject> entity = new HttpEntity<>(header); ResponseEntity<JSONObject> json = restTemplate.postForEntity(url, entity, JSONObject.class); log.info("添加客服******************{}",json); } /* public String getAccessToken(String accessToken) { accessToken = accessToken; if (accessToken == null) { return getToken(); } else { getAccessTokenTime = Long.parseLong(configurationService.get("getAccessTokenTime")); long totalSeconds = (System.currentTimeMillis() - getAccessTokenTime) / 1000; expires_in = Integer.parseInt(configurationService.get("expires_in")); if (totalSeconds > expires_in) { return doAccessToken(configurationService); } else { return accessToken; } } }*/ private void validToken(){ String access_token = accessTokenJson.getString("access_token"); if(null == access_token){ accessToken = getToken(); } if(null != access_token){ Long startTime = accessTokenJson.getLong("start_time"); long temp = System.currentTimeMillis() - startTime; Long expiresIn = accessTokenJson.getLong("expires_in"); if(temp > expiresIn){ accessToken = getToken(); } } } private String getToken() { HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_JSON); ResponseEntity<JSONObject> forEntity = restTemplate.getForEntity(tokenUrl, JSONObject.class); JSONObject body = forEntity.getBody(); log.info("********************{}********************",body); accessTokenJson.putAll(body); accessTokenJson.put("start_time",System.currentTimeMillis()); return body.getString("access_token"); } }
UTF-8
Java
6,019
java
WxConfig.java
Java
[ { "context": "(\"nickname\",\"小小客服\");\n data.put(\"password\",\"pswmd5\");\n HttpHeaders header = new HttpHeaders()", "end": 3942, "score": 0.9993520975112915, "start": 3936, "tag": "PASSWORD", "value": "pswmd5" } ]
null
[]
package com.anvy.petcare.modules.wx; import com.alibaba.fastjson.JSONObject; import com.anvy.petcare.config.ApplicationContextRegister; import com.anvy.petcare.modules.wx.util.MsgModel; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import lombok.extern.slf4j.Slf4j; import netscape.javascript.JSObject; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextInitializer; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; @Slf4j @RestController public class WxConfig { @Resource private RestTemplate restTemplate; @Value("${wx.secretKey}") private String secretKey; @Value("${wx.access_token_url}") private String tokenUrl; private static JSONObject accessTokenJson = new JSONObject(); private static String accessToken; @RequestMapping("wxConfig") public String verifyConfig(HttpServletRequest request, HttpServletResponse response) throws IOException { log.info(" PARAM VAL: >>>signature" + request.getParameter("signature")); log.info(" PARAM VAL: >>>timestamp" + request.getParameter("timestamp")); log.info(" PARAM VAL: >>>nonce" + request.getParameter("nonce")); log.info(" PARAM VAL: >>>echostr" + request.getParameter("echostr")); String echostr = request.getParameter("echostr"); ServletInputStream inputStream = request.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8")); String msg = ""; String str = ""; while((str = reader.readLine()) != null){ msg += str; } String openid = request.getParameter("openid"); log.info("用户OPENID:{}",openid); log.info("用户发送的消息:{}",msg); String anvy = MsgModel.normalMsg(openid,"gh_eb62f9fe0cb6"); log.info("返回用户的消息:{}",anvy); return anvy; } @RequestMapping("sendMsg") public void sendMsg(HttpServletRequest request, HttpServletResponse response) throws IOException { JSONObject object = new JSONObject(); object.put("touser","o18sY6-KFL2Wx7SVjM5XjdR6dElg"); object.put("msgtype","text"); JSONObject obj = new JSONObject(); obj.put("content","abc"); object.put("text",obj); HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_JSON); HttpEntity<JSONObject> entity = new HttpEntity<>(object,header); addKf(); log.info("post url====={}","https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken); ResponseEntity<JSONObject> result = restTemplate.postForEntity("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken, entity, JSONObject.class); JSONObject body = result.getBody(); log.info("send Msg::{}",body); } private void addKf(){ validToken(); String url = "https://api.weixin.qq.com/customservice/kfaccount/add?access_token="+accessToken; JSONObject data = new JSONObject(); data.put("kf_account","test1@test"); data.put("nickname","小小客服"); data.put("password","<PASSWORD>"); HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_JSON); HttpEntity<JSONObject> entity = new HttpEntity<>(header); ResponseEntity<JSONObject> json = restTemplate.postForEntity(url, entity, JSONObject.class); log.info("添加客服******************{}",json); } /* public String getAccessToken(String accessToken) { accessToken = accessToken; if (accessToken == null) { return getToken(); } else { getAccessTokenTime = Long.parseLong(configurationService.get("getAccessTokenTime")); long totalSeconds = (System.currentTimeMillis() - getAccessTokenTime) / 1000; expires_in = Integer.parseInt(configurationService.get("expires_in")); if (totalSeconds > expires_in) { return doAccessToken(configurationService); } else { return accessToken; } } }*/ private void validToken(){ String access_token = accessTokenJson.getString("access_token"); if(null == access_token){ accessToken = getToken(); } if(null != access_token){ Long startTime = accessTokenJson.getLong("start_time"); long temp = System.currentTimeMillis() - startTime; Long expiresIn = accessTokenJson.getLong("expires_in"); if(temp > expiresIn){ accessToken = getToken(); } } } private String getToken() { HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_JSON); ResponseEntity<JSONObject> forEntity = restTemplate.getForEntity(tokenUrl, JSONObject.class); JSONObject body = forEntity.getBody(); log.info("********************{}********************",body); accessTokenJson.putAll(body); accessTokenJson.put("start_time",System.currentTimeMillis()); return body.getString("access_token"); } }
6,023
0.67192
0.668231
148
39.304054
29.554728
180
false
false
0
0
0
0
0
0
0.804054
false
false
11
e9236de3e39ddca8c039387570a4a095f0273bf1
39,101,382,286,011
807dabdf7b43b2315fa0e71cadb72c38300bb883
/src/main/java/com/BackEndUsersApplication.java
cb399b557c234abed1632da10eae83a7beb1d92a
[]
no_license
Hazrian/ProjetBackEnd
https://github.com/Hazrian/ProjetBackEnd
995b23c346fe84c005f11d40103e32604a4683b6
63c55bc2bfdc29f33494ab3219de3be94700ba44
refs/heads/master
2023-01-23T20:13:29.371000
2020-11-16T16:37:05
2020-11-16T16:37:05
313,345,704
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BackEndUsersApplication { public static void main(String[] args) { SpringApplication.run(BackEndUsersApplication.class, args); } }
UTF-8
Java
308
java
BackEndUsersApplication.java
Java
[]
null
[]
package com; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BackEndUsersApplication { public static void main(String[] args) { SpringApplication.run(BackEndUsersApplication.class, args); } }
308
0.824675
0.824675
13
22.692308
24.665094
68
false
false
0
0
0
0
0
0
0.692308
false
false
11
e313e0fc771cbbd1809a265abd82b844b88ddc39
24,756,191,544,871
496f9d19b2779b333c46f7b21127e0e8a4700ecd
/src/main/java/com/jd/jr/dp/behavioral/chain/chain2/Engineer.java
067951087e537fbc9a54a8921fcdc6fe0042891b
[]
no_license
benjaminwhx/designPattern-example
https://github.com/benjaminwhx/designPattern-example
25e048109af22ce45d45cd339796ec1bd7727df8
378868743637ccd063346f0024c085ea55f77d5c
refs/heads/master
2020-12-24T10:31:29.518000
2019-08-04T13:49:12
2019-08-04T13:49:12
73,147,556
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Alipay.com Inc. Copyright (c) 2004-2019 All Rights Reserved. */ package com.jd.jr.dp.behavioral.chain.chain2; /** * * @author benjamin * @version $Id: Engineer.java, v 0.1 2019年08月03日 2:29 PM benjamin Exp $ */ public abstract class Engineer { private Engineer nextEngineer; public void setNextEngineer(Engineer nextEngineer) { this.nextEngineer = nextEngineer; } public void approval(int amount) { if (needApproval(amount)) { approvalInner(amount); if (nextEngineer != null) { nextEngineer.approval(amount); } } } /** * 是否需要审批 * @param amount * @return */ public abstract boolean needApproval(int amount); /** * 审批 */ public abstract void approvalInner(int amount); }
UTF-8
Java
849
java
Engineer.java
Java
[ { "context": ".jr.dp.behavioral.chain.chain2;\n\n/**\n *\n * @author benjamin\n * @version $Id: Engineer.java, v 0.1 2019年08月03日", "end": 145, "score": 0.9990323781967163, "start": 137, "tag": "USERNAME", "value": "benjamin" }, { "context": "sion $Id: Engineer.java, v 0.1 2019年08月03日...
null
[]
/** * Alipay.com Inc. Copyright (c) 2004-2019 All Rights Reserved. */ package com.jd.jr.dp.behavioral.chain.chain2; /** * * @author benjamin * @version $Id: Engineer.java, v 0.1 2019年08月03日 2:29 PM benjamin Exp $ */ public abstract class Engineer { private Engineer nextEngineer; public void setNextEngineer(Engineer nextEngineer) { this.nextEngineer = nextEngineer; } public void approval(int amount) { if (needApproval(amount)) { approvalInner(amount); if (nextEngineer != null) { nextEngineer.approval(amount); } } } /** * 是否需要审批 * @param amount * @return */ public abstract boolean needApproval(int amount); /** * 审批 */ public abstract void approvalInner(int amount); }
849
0.596131
0.569528
39
20.23077
20.772839
72
false
false
0
0
0
0
0
0
0.205128
false
false
11
d2ea37b523de727f52ddf9e1e7e5b1ae923f5aab
34,797,825,069,953
c7160d93ae00c9ebef1129f788afa2c00392f8b5
/src/com/battle/Battle.java
ca13f3e88373da8361493a5a7612e09562783111
[ "MIT" ]
permissive
mablack01/jPokemonBattle
https://github.com/mablack01/jPokemonBattle
e3cd2ba78432e8a91d7af1b765125a779a3ac445
7d35581a86161e24398bbe38c8f9aae8fbe2b712
refs/heads/master
2021-01-20T09:12:44.636000
2014-04-18T02:45:48
2014-04-18T02:45:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.battle; public class Battle { }
UTF-8
Java
51
java
Battle.java
Java
[]
null
[]
package com.battle; public class Battle { }
51
0.647059
0.647059
5
8.2
9.662298
21
false
false
0
0
0
0
0
0
0.2
false
false
11
60b541e9eeaaf50f88777b633cb93b841bad2be8
30,451,318,130,404
b9d5229e1c29cf517dff624c30aa2301f082844c
/lms/app/models/RequisitionPOJO.java
dec3251259bc6f7f6a52cc2b088fe1183070d7c4
[]
no_license
KHAMGroup/lms
https://github.com/KHAMGroup/lms
07d7ef182adb76aad475a126f279ecb4b372d62e
c15c89e6b421608dacbd886596e992091098549b
refs/heads/master
2021-01-19T18:33:14.536000
2013-12-03T00:06:24
2013-12-03T00:06:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package models; //import java.util.Arrays; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Set; import play.data.validation.Constraints.*; import play.db.jpa.Transactional; public class RequisitionPOJO { //case data public String clientID; //client id# public String subjectFirstName; public String subjectLastName; public String otherIdNumber; public String sampleType; public Date dateCollected; @Required @MaxLength(7) public String caseNumber; public Date dateReceived; public String caseNote; public String receivedByEmployee; //employee id# //services public List<Integer> testNumber; public RequisitionPOJO(){ } @Transactional public static void persistRequisition(RequisitionPOJO req, List<String> err){ //performs non-trivial input validation, and persists the new requisition //if there are no errors. Employee emp; int empID = -1; Client cli; int cliID = -1; //check if caseNumber is unique CaseEntityObject newCase = CaseEntityObject.findByCaseNumber(req.caseNumber); if(newCase.getCaseNumber() != null && newCase.getCaseNumber().length() > 0){ //a case with this case# already exists err.add("Case#: " + req.caseNumber + " already exists."); return; //if we don't return here, there is a rollback exception. don't know why. }else{ //good to proceed. newCase = new CaseEntityObject(); newCase.setCaseNumber(req.caseNumber); } if(req.receivedByEmployee.length() > 0){ //check if it's a valid # try{ empID = Integer.parseInt(req.receivedByEmployee); }catch (Exception ex){ err.add("Receieved by employee id# can only contain digits"); empID = -1; } //check if receivedByEmployee is valid # emp = Employee.findById(empID); if((emp != null) && (emp.getEmployeeNumber() == empID)){ }else{ err.add("Employee: " + req.receivedByEmployee + " was not found."); } }else{ err.add("Must enter a \"received by\" employee number"); emp = null; } //parse clientID from form. try{ cliID = Integer.parseInt(req.clientID); }catch (Exception ex){ err.add("Client: " + req.clientID + " not found."); } //link client to case. cli = Client.findByClientNumber(cliID); newCase.setClient(cli); //add case tests List<CaseTest> theTests = new LinkedList<CaseTest>(); CaseTest theTest; for(Integer testNum : req.testNumber){ if(testNum != null && testNum != -1){ TestEntityObject t = TestEntityObject.findByTestNumber((int)testNum); if(t == null){ err.add("Test number: " + testNum + " is not valid."); } theTest = new CaseTest(); theTest.setTest(t); //link the test to the caseTest theTests.add(theTest); } } newCase.setCaseTests(theTests); //fill in other standard fields for the case from the form. newCase.setSubjectFirstname(req.subjectFirstName); newCase.setSubjectLastname(req.subjectLastName); newCase.setReceivedDate(req.dateReceived); newCase.setDateCollected(req.dateCollected); newCase.setReceivedByEmployee(emp); newCase.setSampleType(req.sampleType); newCase.setEmailResultsOk(cli.getEmailReportOk()); newCase.setAllTasksCompleted(false); if(req.otherIdNumber != null && (req.otherIdNumber.length() > 0)){ newCase.setOtherIdNumber(req.otherIdNumber); } if(req.caseNote != null && (req.caseNote.length() > 0)){ Comment comment = new Comment(); comment.setCommentText(req.caseNote); newCase.setCaseNote(comment); } if(err.size() == 0){ newCase.save(); } } public void fillFromEntity(CaseEntityObject c) { clientID = c.getClientNumber()+""; subjectFirstName = c.getSubjectFirstname(); subjectLastName = c.getSubjectLastname(); otherIdNumber = c.getOtherIdNumber(); sampleType = c.getSampleType(); dateCollected = c.getDateCollected(); caseNumber = c.getCaseNumber(); dateReceived = c.getReceivedDate(); caseNote = c.getCaseNoteText(); if(c.getReceivedByEmployee() != null){ receivedByEmployee = c.getReceivedByEmployee().getEmployeeNumber()+""; } Set<Integer> caseTests = c.getCaseTestNumbers(); testNumber = new ArrayList<Integer>(caseTests.size()); testNumber.addAll(caseTests); } public static void updateRequisition(RequisitionPOJO req, List<String> err) { //performs non-trivial input validation, and persists the updated requisition //if there are no errors. Employee emp; int empID = -1; Client cli; int cliID = -1; CaseEntityObject existingCase = CaseEntityObject.findByCaseNumber(req.caseNumber); if(req.receivedByEmployee.length() > 0){ //check if it's a valid # try{ empID = Integer.parseInt(req.receivedByEmployee); }catch (Exception ex){ err.add("Receieved by employee id# can only contain digits"); empID = -1; } //check if receivedByEmployee is valid # emp = Employee.findById(empID); if((emp == null) || (emp.getEmployeeNumber() != empID)){ err.add("Employee: " + req.receivedByEmployee + " was not found."); return; } }else{ err.add("Must enter a \"received by\" employee number"); emp = null; return; } //add case tests List<CaseTest> theTests = new LinkedList<CaseTest>(); if(req.testNumber != null){ for(Integer testNum : req.testNumber){ if(testNum != null && testNum != -1 && !(existingCase.getCaseTestNumbers().contains(testNum))){ CaseTest theTest; TestEntityObject t = TestEntityObject.findByTestNumber((int)testNum); if(t == null){ err.add("Test number: " + testNum + " is not valid."); return; } theTest = new CaseTest(); theTest.setTest(t); //link the test to the caseTest theTests.add(theTest); } } } // existingCase.setCaseTests(theTests); existingCase.getCaseTests().addAll(theTests); //fill in other standard fields for the case from the form. existingCase.setSubjectFirstname(req.subjectFirstName); existingCase.setSubjectLastname(req.subjectLastName); existingCase.setReceivedDate(req.dateReceived); existingCase.setDateCollected(req.dateCollected); existingCase.setReceivedByEmployee(emp); existingCase.setSampleType(req.sampleType); // existingCase.setEmailResultsOk(cli.getEmailReportOk()); if(req.otherIdNumber != null && (req.otherIdNumber.length() > 0)){ existingCase.setOtherIdNumber(req.otherIdNumber); } if(req.caseNote != null && (req.caseNote.length() > 0)){ Comment comment = null; if(existingCase.getCaseNote() == null || !(existingCase.getCaseNoteText().equals(req.caseNote))){ comment = new Comment(); } else{ comment = existingCase.getCaseNote(); } comment.setCommentText(req.caseNote); existingCase.setCaseNote(comment); } if(err.size() == 0){ existingCase.update(existingCase.getCasePK()); } } }
UTF-8
Java
7,400
java
RequisitionPOJO.java
Java
[]
null
[]
package models; //import java.util.Arrays; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Set; import play.data.validation.Constraints.*; import play.db.jpa.Transactional; public class RequisitionPOJO { //case data public String clientID; //client id# public String subjectFirstName; public String subjectLastName; public String otherIdNumber; public String sampleType; public Date dateCollected; @Required @MaxLength(7) public String caseNumber; public Date dateReceived; public String caseNote; public String receivedByEmployee; //employee id# //services public List<Integer> testNumber; public RequisitionPOJO(){ } @Transactional public static void persistRequisition(RequisitionPOJO req, List<String> err){ //performs non-trivial input validation, and persists the new requisition //if there are no errors. Employee emp; int empID = -1; Client cli; int cliID = -1; //check if caseNumber is unique CaseEntityObject newCase = CaseEntityObject.findByCaseNumber(req.caseNumber); if(newCase.getCaseNumber() != null && newCase.getCaseNumber().length() > 0){ //a case with this case# already exists err.add("Case#: " + req.caseNumber + " already exists."); return; //if we don't return here, there is a rollback exception. don't know why. }else{ //good to proceed. newCase = new CaseEntityObject(); newCase.setCaseNumber(req.caseNumber); } if(req.receivedByEmployee.length() > 0){ //check if it's a valid # try{ empID = Integer.parseInt(req.receivedByEmployee); }catch (Exception ex){ err.add("Receieved by employee id# can only contain digits"); empID = -1; } //check if receivedByEmployee is valid # emp = Employee.findById(empID); if((emp != null) && (emp.getEmployeeNumber() == empID)){ }else{ err.add("Employee: " + req.receivedByEmployee + " was not found."); } }else{ err.add("Must enter a \"received by\" employee number"); emp = null; } //parse clientID from form. try{ cliID = Integer.parseInt(req.clientID); }catch (Exception ex){ err.add("Client: " + req.clientID + " not found."); } //link client to case. cli = Client.findByClientNumber(cliID); newCase.setClient(cli); //add case tests List<CaseTest> theTests = new LinkedList<CaseTest>(); CaseTest theTest; for(Integer testNum : req.testNumber){ if(testNum != null && testNum != -1){ TestEntityObject t = TestEntityObject.findByTestNumber((int)testNum); if(t == null){ err.add("Test number: " + testNum + " is not valid."); } theTest = new CaseTest(); theTest.setTest(t); //link the test to the caseTest theTests.add(theTest); } } newCase.setCaseTests(theTests); //fill in other standard fields for the case from the form. newCase.setSubjectFirstname(req.subjectFirstName); newCase.setSubjectLastname(req.subjectLastName); newCase.setReceivedDate(req.dateReceived); newCase.setDateCollected(req.dateCollected); newCase.setReceivedByEmployee(emp); newCase.setSampleType(req.sampleType); newCase.setEmailResultsOk(cli.getEmailReportOk()); newCase.setAllTasksCompleted(false); if(req.otherIdNumber != null && (req.otherIdNumber.length() > 0)){ newCase.setOtherIdNumber(req.otherIdNumber); } if(req.caseNote != null && (req.caseNote.length() > 0)){ Comment comment = new Comment(); comment.setCommentText(req.caseNote); newCase.setCaseNote(comment); } if(err.size() == 0){ newCase.save(); } } public void fillFromEntity(CaseEntityObject c) { clientID = c.getClientNumber()+""; subjectFirstName = c.getSubjectFirstname(); subjectLastName = c.getSubjectLastname(); otherIdNumber = c.getOtherIdNumber(); sampleType = c.getSampleType(); dateCollected = c.getDateCollected(); caseNumber = c.getCaseNumber(); dateReceived = c.getReceivedDate(); caseNote = c.getCaseNoteText(); if(c.getReceivedByEmployee() != null){ receivedByEmployee = c.getReceivedByEmployee().getEmployeeNumber()+""; } Set<Integer> caseTests = c.getCaseTestNumbers(); testNumber = new ArrayList<Integer>(caseTests.size()); testNumber.addAll(caseTests); } public static void updateRequisition(RequisitionPOJO req, List<String> err) { //performs non-trivial input validation, and persists the updated requisition //if there are no errors. Employee emp; int empID = -1; Client cli; int cliID = -1; CaseEntityObject existingCase = CaseEntityObject.findByCaseNumber(req.caseNumber); if(req.receivedByEmployee.length() > 0){ //check if it's a valid # try{ empID = Integer.parseInt(req.receivedByEmployee); }catch (Exception ex){ err.add("Receieved by employee id# can only contain digits"); empID = -1; } //check if receivedByEmployee is valid # emp = Employee.findById(empID); if((emp == null) || (emp.getEmployeeNumber() != empID)){ err.add("Employee: " + req.receivedByEmployee + " was not found."); return; } }else{ err.add("Must enter a \"received by\" employee number"); emp = null; return; } //add case tests List<CaseTest> theTests = new LinkedList<CaseTest>(); if(req.testNumber != null){ for(Integer testNum : req.testNumber){ if(testNum != null && testNum != -1 && !(existingCase.getCaseTestNumbers().contains(testNum))){ CaseTest theTest; TestEntityObject t = TestEntityObject.findByTestNumber((int)testNum); if(t == null){ err.add("Test number: " + testNum + " is not valid."); return; } theTest = new CaseTest(); theTest.setTest(t); //link the test to the caseTest theTests.add(theTest); } } } // existingCase.setCaseTests(theTests); existingCase.getCaseTests().addAll(theTests); //fill in other standard fields for the case from the form. existingCase.setSubjectFirstname(req.subjectFirstName); existingCase.setSubjectLastname(req.subjectLastName); existingCase.setReceivedDate(req.dateReceived); existingCase.setDateCollected(req.dateCollected); existingCase.setReceivedByEmployee(emp); existingCase.setSampleType(req.sampleType); // existingCase.setEmailResultsOk(cli.getEmailReportOk()); if(req.otherIdNumber != null && (req.otherIdNumber.length() > 0)){ existingCase.setOtherIdNumber(req.otherIdNumber); } if(req.caseNote != null && (req.caseNote.length() > 0)){ Comment comment = null; if(existingCase.getCaseNote() == null || !(existingCase.getCaseNoteText().equals(req.caseNote))){ comment = new Comment(); } else{ comment = existingCase.getCaseNote(); } comment.setCommentText(req.caseNote); existingCase.setCaseNote(comment); } if(err.size() == 0){ existingCase.update(existingCase.getCasePK()); } } }
7,400
0.645405
0.642973
262
27.244274
23.515495
100
false
false
0
0
0
0
0
0
2.10687
false
false
11
2e737ec674c5597df3dd78c9a422791ea306f906
32,049,046,019,977
ec07f8e4d5fe3525d2caebe39f08c586e9745269
/src/main/java/com/master/qianyi/manager/controller/InfoManController.java
2cd6eacbd59762411fb1eff6924efdc75ee9be1c
[]
no_license
zuoanlang/app-qianyi
https://github.com/zuoanlang/app-qianyi
f23593ec103cc0af12d8d26f2aa7ce4311d90d2b
0001bb58b6d1cfff409b1f0d5a763b66087120d9
refs/heads/master
2022-07-03T06:15:30.241000
2019-10-31T10:53:27
2019-10-31T10:53:27
174,149,388
2
0
null
false
2022-06-21T00:58:09
2019-03-06T13:22:04
2020-04-23T02:07:07
2022-06-21T00:58:06
7,734
0
0
4
JavaScript
false
false
package com.master.qianyi.manager.controller; import com.master.qianyi.manager.service.InfoManService; import com.master.qianyi.utils.EasyUIDataGridResult; import com.master.qianyi.utils.ResultBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * 后台管理-资讯编辑模块 */ @RestController @RequestMapping("/infoMan") public class InfoManController { @Autowired private InfoManService infoServiceImpl; @RequestMapping("/addNews") public ResultBean addNews(@RequestParam(value="infoType")Long infoType, @RequestParam(value="infoTitle")String infoTitle, @RequestParam(value="infoImgPath")String infoImgPath, @RequestParam(value="infoWriter")String infoWriter, @RequestParam(value="infoContent")String infoContent){ return infoServiceImpl.addNews(infoType,infoTitle,infoImgPath,infoWriter,infoContent); } @RequestMapping("/editNews") public ResultBean editNews(@RequestParam(value="infoId")String infoId, @RequestParam(value="infoType")Long infoType, @RequestParam(value="infoTitle")String infoTitle, @RequestParam(value="infoImgPath")String infoImgPath, @RequestParam(value="infoWriter")String infoWriter, @RequestParam(value="effectFlag")String effectFlag, @RequestParam(value="infoContent")String infoContent){ return infoServiceImpl.editNews(infoId,infoType,infoTitle,infoImgPath,infoWriter,effectFlag,infoContent); } @RequestMapping("/deleteNews") public ResultBean deleteNews(@RequestParam(value="infoIds")String infoIds){ return infoServiceImpl.deleteNews(infoIds); } @RequestMapping("/publish") public ResultBean publish(@RequestParam(value="infoIds")String infoIds, @RequestParam(value="type")int type){ return infoServiceImpl.publish(infoIds,type); } //获取infoList @GetMapping("/getInfoList") public EasyUIDataGridResult getInfoList(@RequestParam(value="page")int pageNum , @RequestParam(value="rows")int pageSize, String infoId,String infoTitle,String infoWriter) { EasyUIDataGridResult infoList = infoServiceImpl.getNewsInfoList(pageNum, pageSize,infoId,infoTitle,infoWriter); return infoList; } }
UTF-8
Java
2,842
java
InfoManController.java
Java
[]
null
[]
package com.master.qianyi.manager.controller; import com.master.qianyi.manager.service.InfoManService; import com.master.qianyi.utils.EasyUIDataGridResult; import com.master.qianyi.utils.ResultBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * 后台管理-资讯编辑模块 */ @RestController @RequestMapping("/infoMan") public class InfoManController { @Autowired private InfoManService infoServiceImpl; @RequestMapping("/addNews") public ResultBean addNews(@RequestParam(value="infoType")Long infoType, @RequestParam(value="infoTitle")String infoTitle, @RequestParam(value="infoImgPath")String infoImgPath, @RequestParam(value="infoWriter")String infoWriter, @RequestParam(value="infoContent")String infoContent){ return infoServiceImpl.addNews(infoType,infoTitle,infoImgPath,infoWriter,infoContent); } @RequestMapping("/editNews") public ResultBean editNews(@RequestParam(value="infoId")String infoId, @RequestParam(value="infoType")Long infoType, @RequestParam(value="infoTitle")String infoTitle, @RequestParam(value="infoImgPath")String infoImgPath, @RequestParam(value="infoWriter")String infoWriter, @RequestParam(value="effectFlag")String effectFlag, @RequestParam(value="infoContent")String infoContent){ return infoServiceImpl.editNews(infoId,infoType,infoTitle,infoImgPath,infoWriter,effectFlag,infoContent); } @RequestMapping("/deleteNews") public ResultBean deleteNews(@RequestParam(value="infoIds")String infoIds){ return infoServiceImpl.deleteNews(infoIds); } @RequestMapping("/publish") public ResultBean publish(@RequestParam(value="infoIds")String infoIds, @RequestParam(value="type")int type){ return infoServiceImpl.publish(infoIds,type); } //获取infoList @GetMapping("/getInfoList") public EasyUIDataGridResult getInfoList(@RequestParam(value="page")int pageNum , @RequestParam(value="rows")int pageSize, String infoId,String infoTitle,String infoWriter) { EasyUIDataGridResult infoList = infoServiceImpl.getNewsInfoList(pageNum, pageSize,infoId,infoTitle,infoWriter); return infoList; } }
2,842
0.666075
0.666075
61
45.19672
34.500568
119
false
false
0
0
0
0
0
0
0.754098
false
false
11
16fe29fed23283daa50c5b3271c78137839e6554
2,551,210,624,988
e0465ef8f80363a7657031a3a024d5cc4a1aa062
/TicTacToe/src/tictactoe/service/TicTacToeService.java
eb96b433942b7c610ddd768090db2f1e808d2cd8
[]
no_license
Wtorix/java-teaching
https://github.com/Wtorix/java-teaching
497544e9735e40779c9e6ef10ddcd7538a5faa27
64a3a049be8e3f05d68e729b764bec6f660e1132
refs/heads/master
2020-05-07T08:38:39.521000
2019-01-06T10:15:17
2019-01-09T19:30:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tictactoe.service; import tictactoe.model.FieldState; import tictactoe.model.TicTacToeGame; /** * Created by agurgul on 03.07.2017. */ public class TicTacToeService { private TicTacToeGame board; private boolean xMoves; public TicTacToeService() { board = new TicTacToeGame(); xMoves = true; } public void move(int x, int y, FieldState state) { if (board.isMoveLegal(x, y)) { board.move(x, y, state); } } }
UTF-8
Java
490
java
TicTacToeService.java
Java
[ { "context": " tictactoe.model.TicTacToeGame;\n\n/**\n * Created by agurgul on 03.07.2017.\n */\npublic class TicTacToeService ", "end": 127, "score": 0.9993488192558289, "start": 120, "tag": "USERNAME", "value": "agurgul" } ]
null
[]
package tictactoe.service; import tictactoe.model.FieldState; import tictactoe.model.TicTacToeGame; /** * Created by agurgul on 03.07.2017. */ public class TicTacToeService { private TicTacToeGame board; private boolean xMoves; public TicTacToeService() { board = new TicTacToeGame(); xMoves = true; } public void move(int x, int y, FieldState state) { if (board.isMoveLegal(x, y)) { board.move(x, y, state); } } }
490
0.632653
0.616327
24
19.416666
16.720537
54
false
false
0
0
0
0
0
0
0.541667
false
false
11
aca293668775cd2bdb7f1841ed29ed9c8208980a
6,459,630,878,927
b690d16eadce75ddf8dd45bba3171fd1236925a9
/Lab8/spr/src/main/java/com/iot/spring/spr/controller/SportContoller.java
ef3bb5db549c9841900c9e5f61e7c649bbef7dc1
[]
no_license
Sv1at1k/DataBases
https://github.com/Sv1at1k/DataBases
60558dc177493bbfff8c3e6b47fde5c3083b526b
ebff78fe5a3bebb4287480e885fa2669d0134de9
refs/heads/master
2020-04-01T07:17:37.127000
2018-11-05T20:54:32
2018-11-05T20:54:32
152,984,280
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.iot.spring.spr.controller; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.iot.spring.spr.DTO.SportDTO; import com.iot.spring.spr.domain.Sport; import com.iot.spring.spr.exceptions.ExistsSportsmanForSportException; import com.iot.spring.spr.exceptions.NoSuchSportException; import com.iot.spring.spr.exceptions.NoSuchSportsmanException; import com.iot.spring.spr.service.SportService; @RestController public class SportContoller { @Autowired SportService sportService; @GetMapping(value = "/api/sport/{sport_id}") public ResponseEntity<SportDTO> getSport(@PathVariable Integer sport_id) throws NoSuchSportException, NoSuchSportsmanException { Sport sport = sportService.getSport(sport_id); Link link = linkTo(methodOn(SportContoller.class).getSport(sport_id)).withSelfRel(); SportDTO sportDTO = new SportDTO(sport, link); return new ResponseEntity<>(sportDTO, HttpStatus.OK); } @GetMapping(value = "/api/sport") public ResponseEntity<List<SportDTO>> getAllSports() throws NoSuchSportException, NoSuchSportsmanException { List<Sport> sportList = sportService.getAllSport(); Link link = linkTo(methodOn(SportContoller.class).getAllSports()).withSelfRel(); List<SportDTO> sportDTO = new ArrayList<>(); for (Sport entity : sportList) { Link selfLink = new Link(link.getHref() + "/" + entity.getId()).withSelfRel(); SportDTO dto = new SportDTO(entity, selfLink); sportDTO.add(dto); } return new ResponseEntity<>(sportDTO, HttpStatus.OK); } @PostMapping(value = "/api/sport") public ResponseEntity<SportDTO> addSport(@RequestBody Sport newSport) throws NoSuchSportException, NoSuchSportsmanException { sportService.createSport(newSport); Link link = linkTo(methodOn(SportContoller.class).getSport(newSport.getId())).withSelfRel(); SportDTO sportDTO = new SportDTO(newSport, link); return new ResponseEntity<>(sportDTO, HttpStatus.CREATED); } @PutMapping(value = "/api/sport/{sport_id}") public ResponseEntity<SportDTO> updateBook(@RequestBody Sport uSport, @PathVariable Integer sport_id) throws NoSuchSportException, NoSuchSportsmanException { sportService.updateSport(uSport, sport_id); Sport sport = sportService.getSport(sport_id); Link link = linkTo(methodOn(SportContoller.class).getSport(sport_id)).withSelfRel(); SportDTO sportDTO = new SportDTO(sport, link); return new ResponseEntity<>(sportDTO, HttpStatus.OK); } @DeleteMapping(value = "/api/sport/{sport_id}") public ResponseEntity deleteSport(@PathVariable Integer sport_id) throws NoSuchSportException, ExistsSportsmanForSportException { sportService.deleteSport(sport_id); return new ResponseEntity(HttpStatus.OK); } }
UTF-8
Java
3,498
java
SportContoller.java
Java
[]
null
[]
package com.iot.spring.spr.controller; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.iot.spring.spr.DTO.SportDTO; import com.iot.spring.spr.domain.Sport; import com.iot.spring.spr.exceptions.ExistsSportsmanForSportException; import com.iot.spring.spr.exceptions.NoSuchSportException; import com.iot.spring.spr.exceptions.NoSuchSportsmanException; import com.iot.spring.spr.service.SportService; @RestController public class SportContoller { @Autowired SportService sportService; @GetMapping(value = "/api/sport/{sport_id}") public ResponseEntity<SportDTO> getSport(@PathVariable Integer sport_id) throws NoSuchSportException, NoSuchSportsmanException { Sport sport = sportService.getSport(sport_id); Link link = linkTo(methodOn(SportContoller.class).getSport(sport_id)).withSelfRel(); SportDTO sportDTO = new SportDTO(sport, link); return new ResponseEntity<>(sportDTO, HttpStatus.OK); } @GetMapping(value = "/api/sport") public ResponseEntity<List<SportDTO>> getAllSports() throws NoSuchSportException, NoSuchSportsmanException { List<Sport> sportList = sportService.getAllSport(); Link link = linkTo(methodOn(SportContoller.class).getAllSports()).withSelfRel(); List<SportDTO> sportDTO = new ArrayList<>(); for (Sport entity : sportList) { Link selfLink = new Link(link.getHref() + "/" + entity.getId()).withSelfRel(); SportDTO dto = new SportDTO(entity, selfLink); sportDTO.add(dto); } return new ResponseEntity<>(sportDTO, HttpStatus.OK); } @PostMapping(value = "/api/sport") public ResponseEntity<SportDTO> addSport(@RequestBody Sport newSport) throws NoSuchSportException, NoSuchSportsmanException { sportService.createSport(newSport); Link link = linkTo(methodOn(SportContoller.class).getSport(newSport.getId())).withSelfRel(); SportDTO sportDTO = new SportDTO(newSport, link); return new ResponseEntity<>(sportDTO, HttpStatus.CREATED); } @PutMapping(value = "/api/sport/{sport_id}") public ResponseEntity<SportDTO> updateBook(@RequestBody Sport uSport, @PathVariable Integer sport_id) throws NoSuchSportException, NoSuchSportsmanException { sportService.updateSport(uSport, sport_id); Sport sport = sportService.getSport(sport_id); Link link = linkTo(methodOn(SportContoller.class).getSport(sport_id)).withSelfRel(); SportDTO sportDTO = new SportDTO(sport, link); return new ResponseEntity<>(sportDTO, HttpStatus.OK); } @DeleteMapping(value = "/api/sport/{sport_id}") public ResponseEntity deleteSport(@PathVariable Integer sport_id) throws NoSuchSportException, ExistsSportsmanForSportException { sportService.deleteSport(sport_id); return new ResponseEntity(HttpStatus.OK); } }
3,498
0.794454
0.794454
89
38.303371
28.977095
109
false
false
0
0
0
0
0
0
1.58427
false
false
11
f8888639cfe3f26c9592ee142fd43f8c0c11532f
34,351,148,482,626
d92f558043d05214dd632e5fcfc90ae726d26bf6
/20210224/src/Test1.java
3281c2b42a5a577f2d37f1d03e74b1534f80b54d
[]
no_license
Melody-Gai/JAVA
https://github.com/Melody-Gai/JAVA
bd7a09322ae08a5e46a7cf64200aeb2fd301bbc1
32e6ded7f459a03d36ead1d6f5db9cd113fad8ed
refs/heads/master
2021-07-01T13:07:52.300000
2021-02-24T14:22:05
2021-02-24T14:22:05
226,022,468
0
0
null
false
2020-10-28T15:03:49
2019-12-05T05:22:52
2020-10-28T15:02:57
2020-10-28T15:03:48
5,409
0
0
1
Java
false
false
/** * @program: 20210224 * @description:无头双向链表 * @author: GAI * @create: 2021-02-24 16:54 **/ public class Test1 { public static void main(String[] args) { MyLinkedList myLinkedList = new MyLinkedList(); myLinkedList.addFirst(1); myLinkedList.addFirst(2); myLinkedList.addFirst(3); myLinkedList.addFirst(4); myLinkedList.display(); myLinkedList.addLast(99); myLinkedList.display(); // myLinkedList.addIndex(2,199); /* myLinkedList.remove(2); myLinkedList.display();*/ /* System.out.println(myLinkedList.contains(3)); System.out.println(myLinkedList.size());*/ } }
UTF-8
Java
693
java
Test1.java
Java
[ { "context": "ogram: 20210224\n * @description:无头双向链表\n * @author: GAI\n * @create: 2021-02-24 16:54\n **/\npublic class Te", "end": 66, "score": 0.9986653923988342, "start": 63, "tag": "NAME", "value": "GAI" } ]
null
[]
/** * @program: 20210224 * @description:无头双向链表 * @author: GAI * @create: 2021-02-24 16:54 **/ public class Test1 { public static void main(String[] args) { MyLinkedList myLinkedList = new MyLinkedList(); myLinkedList.addFirst(1); myLinkedList.addFirst(2); myLinkedList.addFirst(3); myLinkedList.addFirst(4); myLinkedList.display(); myLinkedList.addLast(99); myLinkedList.display(); // myLinkedList.addIndex(2,199); /* myLinkedList.remove(2); myLinkedList.display();*/ /* System.out.println(myLinkedList.contains(3)); System.out.println(myLinkedList.size());*/ } }
693
0.615611
0.56701
23
28.434782
15.14517
55
false
false
0
0
0
0
0
0
0.608696
false
false
11
c0c453e0ed346a471f9f7c104197c7384a0f0912
32,839,320,007,658
6df4fc502db7d6334af2395c15cb3f05050484f9
/MAS[2]/src/mas/associationWithAttribute/Przepisanie.java
ea17efe28b52411c184ec208980a6f053c2e81cb
[]
no_license
Iaremii/MAS-project-2
https://github.com/Iaremii/MAS-project-2
d2e9f2e2a24dd7cf5401443fb32fdc296f60364f
e22a863058e33734d68bf464c93aacc6075b0376
refs/heads/master
2020-03-14T23:19:18.536000
2018-05-02T11:57:11
2018-05-02T11:57:11
131,842,295
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mas.associationWithAttribute; import java.util.Vector; /** * * @author Oleksandr */ public class Przepisanie { private int okres; private Ksiazka ksiazka; private Biblioteka biblioteka; public Przepisanie(Ksiazka ksiazka, Biblioteka biblioteka, int okres) { setKsiazka(ksiazka); setBiblioteka(biblioteka); setOkres(okres); ((Vector) (ksiazka.przypisanie.get(ksiazka))).add(this); ((Vector) (biblioteka.przypisanie.get(biblioteka))).add(this); } public Ksiazka getKsiazka() { return ksiazka; } public Biblioteka getBiblioteka() { return biblioteka; } public int getOkres() { return okres; } public void setBiblioteka(Biblioteka biblioteka) { this.biblioteka = biblioteka; } public void setKsiazka(Ksiazka ksiazka) { this.ksiazka = ksiazka; } public void setOkres(int okres) { this.okres = okres; } }
UTF-8
Java
1,224
java
Przepisanie.java
Java
[ { "context": "\n\r\nimport java.util.Vector;\r\n\r\n/**\r\n *\r\n * @author Oleksandr\r\n */\r\npublic class Przepisanie {\r\n\r\n private int", "end": 288, "score": 0.9899730682373047, "start": 279, "tag": "NAME", "value": "Oleksandr" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mas.associationWithAttribute; import java.util.Vector; /** * * @author Oleksandr */ public class Przepisanie { private int okres; private Ksiazka ksiazka; private Biblioteka biblioteka; public Przepisanie(Ksiazka ksiazka, Biblioteka biblioteka, int okres) { setKsiazka(ksiazka); setBiblioteka(biblioteka); setOkres(okres); ((Vector) (ksiazka.przypisanie.get(ksiazka))).add(this); ((Vector) (biblioteka.przypisanie.get(biblioteka))).add(this); } public Ksiazka getKsiazka() { return ksiazka; } public Biblioteka getBiblioteka() { return biblioteka; } public int getOkres() { return okres; } public void setBiblioteka(Biblioteka biblioteka) { this.biblioteka = biblioteka; } public void setKsiazka(Ksiazka ksiazka) { this.ksiazka = ksiazka; } public void setOkres(int okres) { this.okres = okres; } }
1,224
0.620098
0.620098
53
21.094339
21.547022
79
false
false
0
0
0
0
0
0
0.396226
false
false
11
c1d0d2bf415cf035a5199ab305ba50932a980db2
17,257,178,658,226
42ea850df712094c88e41f9e18f8b7dfcd8ac441
/source_code/Web前端/Ajax零基础入门课程(通俗易懂)/ajax/ajax02/src/com/itany/dao/impl/CourseDaoImpl.java
de8be69fff19942ac740a6d07eebe3cf5c0247d9
[]
no_license
anzhihe/Free-Web-Books
https://github.com/anzhihe/Free-Web-Books
fed98f50f624626d734b91eb06e0720674a5d3ac
aed9ee3403fd6bf3fd6e19a6ed856532dc8c4662
refs/heads/master
2023-07-25T01:06:28.438000
2023-02-13T04:07:28
2023-02-13T04:07:28
175,641,596
661
259
null
false
2023-07-19T10:16:52
2019-03-14T14:45:18
2023-07-19T02:58:59
2023-07-19T10:16:51
1,556,100
616
244
3
JavaScript
false
false
package com.itany.dao.impl; import java.util.List; import com.itany.dao.CourseDao; import com.itany.entity.Course; import com.itany.mapper.CourseMapper; import com.itany.util.JdbcTemplate; import com.itany.util.RowMapper; public class CourseDaoImpl implements CourseDao { private JdbcTemplate<Course> jt=new JdbcTemplate<Course>(); private RowMapper<Course> rm=new CourseMapper(); @Override public List<Course> selectByItemId(int itemId) { String sql="select * from course where itemId=?"; return jt.query(sql, rm, itemId); } @Override public Course selectByCourseId(int courseId) { String sql="select * from course where courseId=?"; return jt.queryForObject(sql, rm, courseId); } @Override public List<Course> selectByCourseName(String courseName) { String sql="select * from course where courseName like ?"; return jt.query(sql, rm, courseName+"%"); } }
UTF-8
Java
890
java
CourseDaoImpl.java
Java
[]
null
[]
package com.itany.dao.impl; import java.util.List; import com.itany.dao.CourseDao; import com.itany.entity.Course; import com.itany.mapper.CourseMapper; import com.itany.util.JdbcTemplate; import com.itany.util.RowMapper; public class CourseDaoImpl implements CourseDao { private JdbcTemplate<Course> jt=new JdbcTemplate<Course>(); private RowMapper<Course> rm=new CourseMapper(); @Override public List<Course> selectByItemId(int itemId) { String sql="select * from course where itemId=?"; return jt.query(sql, rm, itemId); } @Override public Course selectByCourseId(int courseId) { String sql="select * from course where courseId=?"; return jt.queryForObject(sql, rm, courseId); } @Override public List<Course> selectByCourseName(String courseName) { String sql="select * from course where courseName like ?"; return jt.query(sql, rm, courseName+"%"); } }
890
0.750562
0.750562
34
25.17647
21.914904
60
false
false
0
0
0
0
0
0
1.352941
false
false
11
b4edbf939230e317b8714319bca28b163c6c0bfb
34,540,127,037,045
9451358446bf72961eff27a315c8f6ff3e228313
/src/main/java/com/test/hibernatet/Dao/personaDao.java
c535d3455c99b83a20b3eab0311e9d5e5fe3493f
[]
no_license
30Gerardo09/Receta
https://github.com/30Gerardo09/Receta
393fdf7b5dd1fe9ef45c14255d15fb33c380f09a
bf5922779c570c170fdf0605a52fc0e966397fc2
refs/heads/master
2022-12-16T15:05:25.255000
2020-09-19T13:38:18
2020-09-19T13:38:18
296,910,220
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.test.hibernatet.Dao; import com.test.hibernatet.modelo.Persona; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; /** * * @author GERSON */ public class personaDao { protected EntityManager em; private EntityManagerFactory tran = null; public personaDao (){ tran = Persistence.createEntityManagerFactory("HibernatePU"); } public Persona fyndbyId(Persona p){ em = getEntityManager(); return em.find(Persona.class, p.getCodigo()); } private EntityManager getEntityManager(){ return tran.createEntityManager(); } public void selectall(){ //Iniciamos variable que contiene la sentencia a ejecutar String hql = "SELECT p from Persona p"; em = getEntityManager(); Query query = em.createQuery(hql); List<Persona> lista = query.getResultList(); for (Persona p : lista){ System.out.print(p + "\n"); } } public void Insertar (Persona persona){ try{ em = getEntityManager(); em.getTransaction().begin(); em.persist(persona); em.getTransaction().commit(); }catch (Exception ex){ System.out.println("Error al insertar el objeto:" + ex.getMessage()); }finally{ if(em !=null){ em.close(); } } } public void actualizar (Persona persona){ try{ em = getEntityManager(); em.getTransaction().begin(); em.merge(persona); em.getTransaction().commit(); }catch (Exception ex){ System.out.println("Error al actualizar el objeto:"+ex.getMessage()); }finally{ if(em !=null){ em.close(); } } } public void eliminar (Persona persona){ try{ em = getEntityManager(); em.getTransaction().begin(); em.remove(em.merge(persona)); em.getTransaction().commit(); }catch (Exception ex){ System.out.println("Error al eliminar el objeto persona:"+ ex.getMessage()); }finally{ if(em !=null){ em.close(); } } } }
UTF-8
Java
2,952
java
personaDao.java
Java
[ { "context": " javax.persistence.Query;\r\n\r\n\r\n/**\r\n *\r\n * @author GERSON\r\n */\r\n\r\n\r\npublic class personaDao {\r\n \r\n prot", "end": 485, "score": 0.8971350193023682, "start": 479, "tag": "NAME", "value": "GERSON" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.test.hibernatet.Dao; import com.test.hibernatet.modelo.Persona; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; /** * * @author GERSON */ public class personaDao { protected EntityManager em; private EntityManagerFactory tran = null; public personaDao (){ tran = Persistence.createEntityManagerFactory("HibernatePU"); } public Persona fyndbyId(Persona p){ em = getEntityManager(); return em.find(Persona.class, p.getCodigo()); } private EntityManager getEntityManager(){ return tran.createEntityManager(); } public void selectall(){ //Iniciamos variable que contiene la sentencia a ejecutar String hql = "SELECT p from Persona p"; em = getEntityManager(); Query query = em.createQuery(hql); List<Persona> lista = query.getResultList(); for (Persona p : lista){ System.out.print(p + "\n"); } } public void Insertar (Persona persona){ try{ em = getEntityManager(); em.getTransaction().begin(); em.persist(persona); em.getTransaction().commit(); }catch (Exception ex){ System.out.println("Error al insertar el objeto:" + ex.getMessage()); }finally{ if(em !=null){ em.close(); } } } public void actualizar (Persona persona){ try{ em = getEntityManager(); em.getTransaction().begin(); em.merge(persona); em.getTransaction().commit(); }catch (Exception ex){ System.out.println("Error al actualizar el objeto:"+ex.getMessage()); }finally{ if(em !=null){ em.close(); } } } public void eliminar (Persona persona){ try{ em = getEntityManager(); em.getTransaction().begin(); em.remove(em.merge(persona)); em.getTransaction().commit(); }catch (Exception ex){ System.out.println("Error al eliminar el objeto persona:"+ ex.getMessage()); }finally{ if(em !=null){ em.close(); } } } }
2,952
0.50271
0.50271
136
19.705883
19.458145
84
false
false
0
0
0
0
0
0
0.294118
false
false
11
43e8222e9bdf286f00e1e5eef9935415f3a22723
39,041,252,724,835
d53eac16a50b2903a7d866c09a8605503b7c1055
/src/main/java/ru/hse/homework/utils/Client.java
0286af91aa030b0e3d09f7df725e21ace86f8989
[]
no_license
Galaximum/java-homework
https://github.com/Galaximum/java-homework
7c43d83fb0faf34d0478805b98c172dbffee4a89
3b393029602420b8dd2722e4331f972c453b1a6e
refs/heads/main
2023-02-17T20:24:45.530000
2021-01-22T11:55:35
2021-01-22T11:55:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.hse.homework.utils; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import ru.hse.homework.data.Location; import java.util.Optional; public class Client { /** * константа - строка подключения по умолчанию */ private static final String DEFAULT_CONNECT_STRING = "https://freegeoip.app/json/"; /** * поле - строка подключения */ private final String connectString; /** * Создает экземпляр класса со строкой подключения по умолчанию * * @see #Client(String) */ public Client() { connectString = DEFAULT_CONNECT_STRING; } /** * Создает экземпляр класса с уникальной строкой подключения * * @param ip ip адрес пользователя * @see #Client() */ public Client(String ip) { connectString = DEFAULT_CONNECT_STRING + ip; } /** * Получает местонахождение пользователя * * @return Местонахождение пользователя */ public Optional<Location> getLocation() { ClientConfig clientConfig = new DefaultClientConfig(); com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(clientConfig); WebResource webResource = client.resource(connectString); ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); // Статус 200 = успешно if (response.getStatus() != 200) { System.out.println("Failed with HTTP Error code: " + response.getStatus()); String error = response.getEntity(String.class); System.out.print("Error: " + error); return Optional.empty(); } String output = response.getEntity(String.class); try { return Optional.of(parseJSON(output)); } catch (ParseException ex) { System.out.println(ex.getMessage()); return Optional.empty(); } } /** * Создает экземпляр класса {@link Location} из JSON строки * * @param jsonString JSON строка * @return экземпляр класса {@link Location} * @throws ParseException если произошла ошибка при парсинге JSON строки */ private Location parseJSON(String jsonString) throws ParseException { Object obj = new JSONParser().parse(jsonString); JSONObject jo = (JSONObject) obj; String ip = (String) jo.get("ip"); String countryCode = (String) jo.get("country_code"); String countryName = (String) jo.get("country_name"); String regionCode = (String) jo.get("region_code"); String regionName = (String) jo.get("region_name"); String city = (String) jo.get("city"); String zipCode = (String) jo.get("zip_code"); String timeZone = (String) jo.get("time_zone"); Double latitude = (Double) jo.get("latitude"); Double longitude = (Double) jo.get("longitude"); Long metroCode = (Long) jo.get("metro_code"); return new Location(ip, countryCode, countryName, regionCode, regionName, city, zipCode, timeZone, latitude, longitude, metroCode); } }
UTF-8
Java
3,774
java
Client.java
Java
[]
null
[]
package ru.hse.homework.utils; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import ru.hse.homework.data.Location; import java.util.Optional; public class Client { /** * константа - строка подключения по умолчанию */ private static final String DEFAULT_CONNECT_STRING = "https://freegeoip.app/json/"; /** * поле - строка подключения */ private final String connectString; /** * Создает экземпляр класса со строкой подключения по умолчанию * * @see #Client(String) */ public Client() { connectString = DEFAULT_CONNECT_STRING; } /** * Создает экземпляр класса с уникальной строкой подключения * * @param ip ip адрес пользователя * @see #Client() */ public Client(String ip) { connectString = DEFAULT_CONNECT_STRING + ip; } /** * Получает местонахождение пользователя * * @return Местонахождение пользователя */ public Optional<Location> getLocation() { ClientConfig clientConfig = new DefaultClientConfig(); com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(clientConfig); WebResource webResource = client.resource(connectString); ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); // Статус 200 = успешно if (response.getStatus() != 200) { System.out.println("Failed with HTTP Error code: " + response.getStatus()); String error = response.getEntity(String.class); System.out.print("Error: " + error); return Optional.empty(); } String output = response.getEntity(String.class); try { return Optional.of(parseJSON(output)); } catch (ParseException ex) { System.out.println(ex.getMessage()); return Optional.empty(); } } /** * Создает экземпляр класса {@link Location} из JSON строки * * @param jsonString JSON строка * @return экземпляр класса {@link Location} * @throws ParseException если произошла ошибка при парсинге JSON строки */ private Location parseJSON(String jsonString) throws ParseException { Object obj = new JSONParser().parse(jsonString); JSONObject jo = (JSONObject) obj; String ip = (String) jo.get("ip"); String countryCode = (String) jo.get("country_code"); String countryName = (String) jo.get("country_name"); String regionCode = (String) jo.get("region_code"); String regionName = (String) jo.get("region_name"); String city = (String) jo.get("city"); String zipCode = (String) jo.get("zip_code"); String timeZone = (String) jo.get("time_zone"); Double latitude = (Double) jo.get("latitude"); Double longitude = (Double) jo.get("longitude"); Long metroCode = (Long) jo.get("metro_code"); return new Location(ip, countryCode, countryName, regionCode, regionName, city, zipCode, timeZone, latitude, longitude, metroCode); } }
3,774
0.641713
0.639965
103
32.330097
26.303822
104
false
false
0
0
0
0
0
0
0.485437
false
false
11
9b8be5b582ff28932b27658080ced0a8976f933d
34,729,105,606,199
dead033db0668da6ecd8aee18cfa9881c4a89349
/ChecaGarciaJesusMP/src/org/mp/sesion04/StackLinkedList.java
f3922af25a5762a83a326abf0a7fe6e8f6e101ec
[]
no_license
Fromau5/MP2014UAL
https://github.com/Fromau5/MP2014UAL
1f529b74e6324ba2e99cea17ad7027a4227b395a
6a1420b979e85c14d9d1d79ffd81b862a10d8fdc
refs/heads/master
2016-09-05T16:47:08.204000
2015-04-29T22:36:20
2015-04-29T22:36:20
34,820,372
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.mp.sesion04; // //UAL //1º Grado en Ingeniería Informática // //PRÁCTICA: Sesión 04 //ASIGNATURA: Metodología de la programación // /** * Class that creates a stack with a linked list (StackLinkedList). * @author Jesús Checa * @version 1.0 * @param <T> * */ public class StackLinkedList<T> implements Stack<T>{ //Class attributes private ListNode<T> topOfStack; //The last inserted node private int size; //The number of nodes of the list /** * Builder */ public StackLinkedList(){ this.size=0; this.topOfStack=null; } // //****OTHER METHODS**** // /** * Method that inserts a node with an element x * @param x the element that is inserted */ @Override public void push(T x){ this.topOfStack=new ListNode<T>(x, this.topOfStack); size++; } /** * Method that eliminates the last inserted node */ @Override public void pop() throws EmptyStackException{ if(isEmpty()){ throw new EmptyStackException("Pila Vacia"); } this.topOfStack=this.topOfStack.next; size--; } /** * Method that returns the element of the last inserted node * @return the element of the last inserted node */ @Override public T peek() throws EmptyStackException{ if(isEmpty()){ throw new EmptyStackException("Pila Vacia"); } return this.topOfStack.element; } /** * Method that returns the element of the last inserted node and eliminates that node * @return the element of the last inserted node */ @Override public T peekAndPop() throws EmptyStackException{ if(isEmpty()){ throw new EmptyStackException("Pila Vacia"); } T temporalElement=this.topOfStack.element; this.topOfStack=this.topOfStack.next; size--; return temporalElement; } /** * Method that returns if the linked list is empty or not * @return if the list is empty or not */ @Override public boolean isEmpty(){ return (this.topOfStack==null?true:false); } /** * Method that clears the list (all the nodes are eliminated) */ @Override public void clear(){ this.topOfStack=null; } /** * Method that returns the size of the list * @return the size of the linked list (its number of nodes) */ @Override public int size(){ return this.size; } }
ISO-8859-1
Java
2,372
java
StackLinkedList.java
Java
[ { "context": "k with a linked list (StackLinkedList).\r\n* @author Jesús Checa\r\n* @version 1.0\r\n* @param <T>\r\n*\r\n*/\r\npublic clas", "end": 246, "score": 0.9998548030853271, "start": 235, "tag": "NAME", "value": "Jesús Checa" } ]
null
[]
package org.mp.sesion04; // //UAL //1º Grado en Ingeniería Informática // //PRÁCTICA: Sesión 04 //ASIGNATURA: Metodología de la programación // /** * Class that creates a stack with a linked list (StackLinkedList). * @author <NAME> * @version 1.0 * @param <T> * */ public class StackLinkedList<T> implements Stack<T>{ //Class attributes private ListNode<T> topOfStack; //The last inserted node private int size; //The number of nodes of the list /** * Builder */ public StackLinkedList(){ this.size=0; this.topOfStack=null; } // //****OTHER METHODS**** // /** * Method that inserts a node with an element x * @param x the element that is inserted */ @Override public void push(T x){ this.topOfStack=new ListNode<T>(x, this.topOfStack); size++; } /** * Method that eliminates the last inserted node */ @Override public void pop() throws EmptyStackException{ if(isEmpty()){ throw new EmptyStackException("Pila Vacia"); } this.topOfStack=this.topOfStack.next; size--; } /** * Method that returns the element of the last inserted node * @return the element of the last inserted node */ @Override public T peek() throws EmptyStackException{ if(isEmpty()){ throw new EmptyStackException("Pila Vacia"); } return this.topOfStack.element; } /** * Method that returns the element of the last inserted node and eliminates that node * @return the element of the last inserted node */ @Override public T peekAndPop() throws EmptyStackException{ if(isEmpty()){ throw new EmptyStackException("Pila Vacia"); } T temporalElement=this.topOfStack.element; this.topOfStack=this.topOfStack.next; size--; return temporalElement; } /** * Method that returns if the linked list is empty or not * @return if the list is empty or not */ @Override public boolean isEmpty(){ return (this.topOfStack==null?true:false); } /** * Method that clears the list (all the nodes are eliminated) */ @Override public void clear(){ this.topOfStack=null; } /** * Method that returns the size of the list * @return the size of the linked list (its number of nodes) */ @Override public int size(){ return this.size; } }
2,366
0.645939
0.642555
117
18.205128
20.289587
86
false
false
0
0
0
0
0
0
1.273504
false
false
11
eccaf3c738f694fb541ca0e84d35b6f6d3397c00
3,058,016,784,882
b8335529093d8ea0d4588db56a6194b904876037
/ATM/src/main/java/cn/ysjh/pojo/account.java
66695c3378f2014dbf8252e10807cb61f45c690c
[]
no_license
ysjh0014/warehouse
https://github.com/ysjh0014/warehouse
cd2de7a13f6a2c540389b978d4e82a23fb5d8b44
f645e62f51e25545b7073f87867164dfee898377
refs/heads/master
2021-06-29T04:05:40.194000
2019-05-16T06:03:20
2019-05-16T06:07:46
111,516,876
15
14
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.ysjh.pojo; public class account { private String uuid; private int balance; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; } }
UTF-8
Java
318
java
account.java
Java
[]
null
[]
package cn.ysjh.pojo; public class account { private String uuid; private int balance; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; } }
318
0.68239
0.68239
22
13.454545
12.313065
38
false
false
0
0
0
0
0
0
1.227273
false
false
11
97e6569453988d6d6a3a8d6091c0e806b3bb2c6e
3,058,016,783,328
2fc214a94252518820f9fcbd0ae4c5d2a5eb9ff1
/OldExam2017_V2/Solutions/by Maxim/Colors.java
aeed15c48b78469fc6e0cbebe72963545454ce52
[]
no_license
jonibim/UltimateTestCollection2IP90
https://github.com/jonibim/UltimateTestCollection2IP90
bb8637a4131fc1d89274f733338fb87381b2dd8e
d78fdd44f4923bda97473b0d56b0e18a800d4f78
refs/heads/master
2022-07-05T08:42:45.997000
2022-06-20T18:17:51
2022-06-20T18:17:51
217,848,810
5
3
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.*; import javax.swing.*; import java.awt.event.*; class Colors { JFrame frame; JPanel colorPanel; int numcols = 6; int numrows = 4; void buildColorPanel() { colorPanel = new JPanel(); colorPanel.setLayout( new GridLayout(numrows, numcols) ); int numcells = numrows * numcols; for (int i = 0; i < numcells; i++) { FlyingLabel label = new FlyingLabel(); label.setOpaque(true); int whiteness = i * 255 / numcells; label.setBackground( new Color(255, whiteness, whiteness) ); colorPanel.add(label); } frame.add(colorPanel); } void buildGUI() { SwingUtilities.invokeLater( new Runnable() { public void run() { frame = new JFrame("Flying Colors"); buildColorPanel(); frame.setSize(500, 300); frame.setLocation(300, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } public static void main(String[] args) { (new Colors()).buildGUI(); } } class FlyingLabel extends JLabel implements MouseListener { Color origColor; FlyingLabel() { addMouseListener(this); } @Override public void mousePressed( MouseEvent e) { if (getBackground() == Color.YELLOW) { setBackground(origColor); } else { origColor = getBackground(); setBackground(Color.YELLOW); } } @Override public void mouseReleased( MouseEvent e) { } @Override public void mouseClicked( MouseEvent e) { } @Override public void mouseEntered( MouseEvent e) { } @Override public void mouseExited( MouseEvent e) { } }
UTF-8
Java
1,779
java
Colors.java
Java
[]
null
[]
import java.awt.*; import javax.swing.*; import java.awt.event.*; class Colors { JFrame frame; JPanel colorPanel; int numcols = 6; int numrows = 4; void buildColorPanel() { colorPanel = new JPanel(); colorPanel.setLayout( new GridLayout(numrows, numcols) ); int numcells = numrows * numcols; for (int i = 0; i < numcells; i++) { FlyingLabel label = new FlyingLabel(); label.setOpaque(true); int whiteness = i * 255 / numcells; label.setBackground( new Color(255, whiteness, whiteness) ); colorPanel.add(label); } frame.add(colorPanel); } void buildGUI() { SwingUtilities.invokeLater( new Runnable() { public void run() { frame = new JFrame("Flying Colors"); buildColorPanel(); frame.setSize(500, 300); frame.setLocation(300, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } public static void main(String[] args) { (new Colors()).buildGUI(); } } class FlyingLabel extends JLabel implements MouseListener { Color origColor; FlyingLabel() { addMouseListener(this); } @Override public void mousePressed( MouseEvent e) { if (getBackground() == Color.YELLOW) { setBackground(origColor); } else { origColor = getBackground(); setBackground(Color.YELLOW); } } @Override public void mouseReleased( MouseEvent e) { } @Override public void mouseClicked( MouseEvent e) { } @Override public void mouseEntered( MouseEvent e) { } @Override public void mouseExited( MouseEvent e) { } }
1,779
0.586284
0.57448
75
22.733334
17.917093
67
false
false
0
0
0
0
0
0
0.48
false
false
11
834a9485e7414df55c41febe2aa1b453ec77291d
24,146,306,195,875
ad2c19e24e32c5ab13b26bf1b79107c74e5dd19c
/EDD/Poryectos/ClaseFecha/ClaseFechaSegundoDia/David Castro Martín/Fecha.java
cc771bd7701e4e56abcbc7d913c28abe8eae67ed
[ "MIT" ]
permissive
chelunike/Clase2111DAWM
https://github.com/chelunike/Clase2111DAWM
2039b9f5903fb9e54cd6ca040fff67f7f3f067f2
5542b9af93db7e5ebe8628e585171d1c8cd7fa4f
refs/heads/master
2020-03-09T23:36:16.142000
2018-04-25T17:32:18
2018-04-25T17:32:18
129,061,763
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fecha; public class Fecha { private int dia,mes,año; //Constructores public Fecha(int dia,int mes,int año){ this.dia=dia; this.mes=mes; this.año=año; } public Fecha(String cad){ int lon = cad.length(); String dd,mm,aa; if (lon == 10) { if ((cad.charAt(2) == '-' || cad.charAt(2) == '/') && (cad.charAt(5) == '-' || cad.charAt(5) == '/')) { dd = cad.substring(0, 2); mm = cad.substring(3, 5); aa = cad.substring(6); try { dia = Integer.parseInt(dd); mes = Integer.parseUnsignedInt(mm); año = Integer.parseInt(aa); } catch (NumberFormatException e) {//(ExceptionType name) System.out.println(e.getMessage()); } // } } }//Fin del constructor //Metodos public void setDatos(int d,int m,int a){ this.dia=d; this.mes=m; this.año=a; } public int getDia(){ return this.dia; } public int getMes(){ return this.mes; } public int getAño(){ return this.año; } public boolean esCorrecta(){ boolean correcta=false; if(dia>0 && dia<=31){ if(mes>0 && mes<=12){ if(dia<=diasDelMes() && año>=1582) correcta=true; } }//Fin primer if if(mes==2){ if(esBisiesto() && dia>0 && dia<=29) correcta=true; } return correcta; } private int diasDelMes(){ int dias=31; switch (mes){ case 2: dias=28; break; case 4: case 6: case 9: case 11: dias=30; } return dias; } private boolean esBisiesto(){ boolean b=false; if(año%400==0) b=true; else{ if(año%4==0 && año%100!=0) b=true; } return b; } public boolean mayorQue(Fecha f){ if(año>f.getAño()) return true; if(año<f.getAño()) return false; if(mes>f.getMes()) return true; if(mes<f.getMes()) return false; return dia>f.getDia(); } public static void intercambiar(Fecha f1, Fecha f2){ int auxD=f1.getDia(), auxM=f1.getMes(), auxA=f1.getAño(); f1.setDatos(f2.getDia(), f2.getMes(), f2.getAño()); f2.setDatos(auxD, auxM, auxA); } public int difAños(Fecha f1, Fecha f2){ int año1=f1.getAño(); int año2=f2.getAño(); int dif=0; if(año1!=año2) dif=año2-año1; return dif; } }//Fin clase
UTF-8
Java
3,217
java
Fecha.java
Java
[]
null
[]
package fecha; public class Fecha { private int dia,mes,año; //Constructores public Fecha(int dia,int mes,int año){ this.dia=dia; this.mes=mes; this.año=año; } public Fecha(String cad){ int lon = cad.length(); String dd,mm,aa; if (lon == 10) { if ((cad.charAt(2) == '-' || cad.charAt(2) == '/') && (cad.charAt(5) == '-' || cad.charAt(5) == '/')) { dd = cad.substring(0, 2); mm = cad.substring(3, 5); aa = cad.substring(6); try { dia = Integer.parseInt(dd); mes = Integer.parseUnsignedInt(mm); año = Integer.parseInt(aa); } catch (NumberFormatException e) {//(ExceptionType name) System.out.println(e.getMessage()); } // } } }//Fin del constructor //Metodos public void setDatos(int d,int m,int a){ this.dia=d; this.mes=m; this.año=a; } public int getDia(){ return this.dia; } public int getMes(){ return this.mes; } public int getAño(){ return this.año; } public boolean esCorrecta(){ boolean correcta=false; if(dia>0 && dia<=31){ if(mes>0 && mes<=12){ if(dia<=diasDelMes() && año>=1582) correcta=true; } }//Fin primer if if(mes==2){ if(esBisiesto() && dia>0 && dia<=29) correcta=true; } return correcta; } private int diasDelMes(){ int dias=31; switch (mes){ case 2: dias=28; break; case 4: case 6: case 9: case 11: dias=30; } return dias; } private boolean esBisiesto(){ boolean b=false; if(año%400==0) b=true; else{ if(año%4==0 && año%100!=0) b=true; } return b; } public boolean mayorQue(Fecha f){ if(año>f.getAño()) return true; if(año<f.getAño()) return false; if(mes>f.getMes()) return true; if(mes<f.getMes()) return false; return dia>f.getDia(); } public static void intercambiar(Fecha f1, Fecha f2){ int auxD=f1.getDia(), auxM=f1.getMes(), auxA=f1.getAño(); f1.setDatos(f2.getDia(), f2.getMes(), f2.getAño()); f2.setDatos(auxD, auxM, auxA); } public int difAños(Fecha f1, Fecha f2){ int año1=f1.getAño(); int año2=f2.getAño(); int dif=0; if(año1!=año2) dif=año2-año1; return dif; } }//Fin clase
3,217
0.4
0.378683
147
20.687075
15.811303
73
false
false
0
0
0
0
0
0
0.462585
false
false
11
a3c9cd764a4793455d820ceff104d8874a0de1bf
38,577,396,270,266
4774ad93a53e135731d9f90207a89e7ffbd480bb
/VideoPlayer/app/src/main/java/com/software/videoplayer/fragment/bt/BtFragment.java
ff6019412a47029b9753b1cf53e755474beeb12c
[]
no_license
AngelaTT/tests
https://github.com/AngelaTT/tests
57ed15df5041d3a1a24118fab248617e297a3d4b
1936bfa4fea96f4b9886a470c55d7cc1cb59a1f8
refs/heads/master
2021-01-20T12:24:17.017000
2017-05-05T10:00:35
2017-05-05T10:00:35
90,359,768
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.software.videoplayer.fragment.bt; import android.app.Activity; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import com.github.clans.fab.FloatingActionButton; import com.github.clans.fab.FloatingActionMenu; import com.software.videoplayer.R; import com.software.videoplayer.activity.MainActivity; import com.software.videoplayer.activity.file.LocaleFileBrowser; import com.software.videoplayer.constants.MyConstants; import com.software.videoplayer.interfaces.MyOnBackPressed; import com.software.videoplayer.service.BtCacheSerVice; import java.io.File; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder;/* import qixiao.com.btdownload.AddTorrentActivity; import qixiao.com.btdownload.constants.btConstant; import qixiao.com.btdownload.core.Torrent; import qixiao.com.btdownload.dialogs.ErrorReportAlertDialog; import qixiao.com.btdownload.dialogs.filemanager.FileManagerConfig; import qixiao.com.btdownload.dialogs.filemanager.FileManagerDialog;*/ /** * A simple {@link Fragment} subclass. */ public class BtFragment extends Fragment implements MyOnBackPressed { @BindView(R.id.add_link_button) FloatingActionButton addLinkButton; @BindView(R.id.open_file_button) FloatingActionButton openFileButton; @BindView(R.id.add_torrent_button) FloatingActionMenu addTorrentButton; Unbinder unbinder; @BindView(R.id.bt_root) ViewPager btRoot; DownloadingBtFragment downloadingBtFragment; DownloadedBtFragment downloadedBtFragment; private MainActivity activity; private RadioButton left_check; private RadioButton right_check; List<Fragment> list; private static BtFragment instance = null; public static BtFragment getInstance(){ if (instance == null){ instance = new BtFragment(); } return instance; } @Override public void onAttach(Context context) { super.onAttach(context); activity = (MainActivity) context; RadioGroup radioGroup = (RadioGroup) activity.findViewById(R.id.bt_check); left_check = ((RadioButton) activity.findViewById(R.id.left_check)); right_check = ((RadioButton) activity.findViewById(R.id.right_check)); if (radioGroup != null) { radioGroup.setOnCheckedChangeListener((group, checkedId) -> { switch (checkedId) { case R.id.left_check: btRoot.setCurrentItem(0); break; case R.id.right_check: btRoot.setCurrentItem(1); break; } }); } getContext().startService(new Intent(getContext(), BtCacheSerVice.class)); activity.myOnBackPressed = this; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_bt, container, false); unbinder = ButterKnife.bind(this, view); list = new ArrayList<>(); downloadingBtFragment = new DownloadingBtFragment(); downloadedBtFragment = new DownloadedBtFragment(); list.add(downloadingBtFragment); list.add(downloadedBtFragment); btRoot.setAdapter(new FragmentPagerAdapter(getActivity().getSupportFragmentManager()) { @Override public Fragment getItem(int position) { return list.get(position); } @Override public int getCount() { return list.size(); } @Override public void destroyItem(ViewGroup container, int position, Object object) { //null } }); btRoot.setOnPageChangeListener(onPageChangeListener); return view; } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (position == 0){ left_check.setChecked(true); }else if (position == 1){ right_check.setChecked(true); } } @Override public void onPageScrollStateChanged(int state) { } }; @OnClick({R.id.add_link_button, R.id.open_file_button}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.add_link_button: EditText editText = new EditText(getContext()); AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle("输入磁力链接:") .setView(editText, 40, 0, 40, 0) .setNegativeButton("取消", null) .setPositiveButton("确定", (dialog, which) -> { String magnet = editText.getText().toString(); if (magnet.startsWith("magnet:")) { Intent intent = new Intent(MyConstants.NEW_BT_TASK); intent.putExtra("magnet", magnet); getContext().sendBroadcast(intent); } else { builder.setMessage("无效的链接地址!"); builder.create().show(); } }) .create().show(); addTorrentButton.close(true); break; case R.id.open_file_button: Intent intent4 = new Intent(getActivity(), LocaleFileBrowser.class); intent4.putExtra("title", getString(R.string.bxfile_extsdcard)); intent4.putExtra("startPath", Environment.getExternalStorageDirectory().getAbsolutePath()); startActivity(intent4); addTorrentButton.close(true); // torrentFileChooserDialog(); break; } } @Override public void onBackPressed() { if (btRoot.getCurrentItem() == 0) { if (downloadingBtFragment.changeState) { downloadingBtFragment.updateViewToNormal(); } else { gotoHome(); } } else { if (downloadedBtFragment.changeStateDown) { downloadedBtFragment.updateViewToNormal(); } else { gotoHome(); } } } /* @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case btConstant.TORRENT_FILE_CHOOSE_REQUEST: if (resultCode == Activity.RESULT_OK) { if (data.hasExtra(FileManagerDialog.TAG_RETURNED_PATH)) { String path = data.getStringExtra(FileManagerDialog.TAG_RETURNED_PATH); try { addTorrentDialog(Uri.fromFile(new File(path))); } catch (Exception e) { // sentError = e; // Log.e(TAG, Log.getStackTraceString(e)); if (getFragmentManager() .findFragmentByTag(btConstant.TAG_ERROR_OPEN_TORRENT_FILE_DIALOG) == null) { ErrorReportAlertDialog errDialog = ErrorReportAlertDialog.newInstance( activity.getApplicationContext(), getString(qixiao.com.btdownload.R.string.error), getString(qixiao.com.btdownload.R.string.error_open_torrent_file),//无法打开目标种子文件 Log.getStackTraceString(e), this); *//* FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(errDialog, TAG_ERROR_OPEN_TORRENT_FILE_DIALOG); ft.commitAllowingStateLoss();*//* } } } } break; case btConstant.ADD_TORRENT_REQUEST: if (resultCode == Activity.RESULT_OK) { if (data.hasExtra(AddTorrentActivity.TAG_RESULT_TORRENT)) { Torrent torrent = data.getParcelableExtra(AddTorrentActivity.TAG_RESULT_TORRENT); if (torrent != null) { ArrayList<Torrent> list = new ArrayList<>(); list.add(torrent); // addTorrentsRequest(list); } } } break; } }*/ private void gotoHome() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 注意 intent.addCategory(Intent.CATEGORY_HOME); this.startActivity(intent); } /* private void addTorrentDialog(Uri uri) { if (uri == null) { return; } Intent i = new Intent(activity, AddTorrentActivity.class); i.putExtra(AddTorrentActivity.TAG_URI, uri); startActivityForResult(i, btConstant.ADD_TORRENT_REQUEST); } private void torrentFileChooserDialog() { Intent i = new Intent(activity, FileManagerDialog.class); List<String> fileType = new ArrayList<>(); fileType.add("torrent"); FileManagerConfig config = new FileManagerConfig(null, getString(qixiao.com.btdownload.R.string.torrent_file_chooser_title),//选择 torrent 文件 fileType,//torrent FileManagerConfig.FILE_CHOOSER_MODE); i.putExtra(FileManagerDialog.TAG_CONFIG, config); startActivityForResult(i, btConstant.TORRENT_FILE_CHOOSE_REQUEST); }*/ }
UTF-8
Java
11,042
java
BtFragment.java
Java
[]
null
[]
package com.software.videoplayer.fragment.bt; import android.app.Activity; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import com.github.clans.fab.FloatingActionButton; import com.github.clans.fab.FloatingActionMenu; import com.software.videoplayer.R; import com.software.videoplayer.activity.MainActivity; import com.software.videoplayer.activity.file.LocaleFileBrowser; import com.software.videoplayer.constants.MyConstants; import com.software.videoplayer.interfaces.MyOnBackPressed; import com.software.videoplayer.service.BtCacheSerVice; import java.io.File; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder;/* import qixiao.com.btdownload.AddTorrentActivity; import qixiao.com.btdownload.constants.btConstant; import qixiao.com.btdownload.core.Torrent; import qixiao.com.btdownload.dialogs.ErrorReportAlertDialog; import qixiao.com.btdownload.dialogs.filemanager.FileManagerConfig; import qixiao.com.btdownload.dialogs.filemanager.FileManagerDialog;*/ /** * A simple {@link Fragment} subclass. */ public class BtFragment extends Fragment implements MyOnBackPressed { @BindView(R.id.add_link_button) FloatingActionButton addLinkButton; @BindView(R.id.open_file_button) FloatingActionButton openFileButton; @BindView(R.id.add_torrent_button) FloatingActionMenu addTorrentButton; Unbinder unbinder; @BindView(R.id.bt_root) ViewPager btRoot; DownloadingBtFragment downloadingBtFragment; DownloadedBtFragment downloadedBtFragment; private MainActivity activity; private RadioButton left_check; private RadioButton right_check; List<Fragment> list; private static BtFragment instance = null; public static BtFragment getInstance(){ if (instance == null){ instance = new BtFragment(); } return instance; } @Override public void onAttach(Context context) { super.onAttach(context); activity = (MainActivity) context; RadioGroup radioGroup = (RadioGroup) activity.findViewById(R.id.bt_check); left_check = ((RadioButton) activity.findViewById(R.id.left_check)); right_check = ((RadioButton) activity.findViewById(R.id.right_check)); if (radioGroup != null) { radioGroup.setOnCheckedChangeListener((group, checkedId) -> { switch (checkedId) { case R.id.left_check: btRoot.setCurrentItem(0); break; case R.id.right_check: btRoot.setCurrentItem(1); break; } }); } getContext().startService(new Intent(getContext(), BtCacheSerVice.class)); activity.myOnBackPressed = this; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_bt, container, false); unbinder = ButterKnife.bind(this, view); list = new ArrayList<>(); downloadingBtFragment = new DownloadingBtFragment(); downloadedBtFragment = new DownloadedBtFragment(); list.add(downloadingBtFragment); list.add(downloadedBtFragment); btRoot.setAdapter(new FragmentPagerAdapter(getActivity().getSupportFragmentManager()) { @Override public Fragment getItem(int position) { return list.get(position); } @Override public int getCount() { return list.size(); } @Override public void destroyItem(ViewGroup container, int position, Object object) { //null } }); btRoot.setOnPageChangeListener(onPageChangeListener); return view; } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (position == 0){ left_check.setChecked(true); }else if (position == 1){ right_check.setChecked(true); } } @Override public void onPageScrollStateChanged(int state) { } }; @OnClick({R.id.add_link_button, R.id.open_file_button}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.add_link_button: EditText editText = new EditText(getContext()); AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle("输入磁力链接:") .setView(editText, 40, 0, 40, 0) .setNegativeButton("取消", null) .setPositiveButton("确定", (dialog, which) -> { String magnet = editText.getText().toString(); if (magnet.startsWith("magnet:")) { Intent intent = new Intent(MyConstants.NEW_BT_TASK); intent.putExtra("magnet", magnet); getContext().sendBroadcast(intent); } else { builder.setMessage("无效的链接地址!"); builder.create().show(); } }) .create().show(); addTorrentButton.close(true); break; case R.id.open_file_button: Intent intent4 = new Intent(getActivity(), LocaleFileBrowser.class); intent4.putExtra("title", getString(R.string.bxfile_extsdcard)); intent4.putExtra("startPath", Environment.getExternalStorageDirectory().getAbsolutePath()); startActivity(intent4); addTorrentButton.close(true); // torrentFileChooserDialog(); break; } } @Override public void onBackPressed() { if (btRoot.getCurrentItem() == 0) { if (downloadingBtFragment.changeState) { downloadingBtFragment.updateViewToNormal(); } else { gotoHome(); } } else { if (downloadedBtFragment.changeStateDown) { downloadedBtFragment.updateViewToNormal(); } else { gotoHome(); } } } /* @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case btConstant.TORRENT_FILE_CHOOSE_REQUEST: if (resultCode == Activity.RESULT_OK) { if (data.hasExtra(FileManagerDialog.TAG_RETURNED_PATH)) { String path = data.getStringExtra(FileManagerDialog.TAG_RETURNED_PATH); try { addTorrentDialog(Uri.fromFile(new File(path))); } catch (Exception e) { // sentError = e; // Log.e(TAG, Log.getStackTraceString(e)); if (getFragmentManager() .findFragmentByTag(btConstant.TAG_ERROR_OPEN_TORRENT_FILE_DIALOG) == null) { ErrorReportAlertDialog errDialog = ErrorReportAlertDialog.newInstance( activity.getApplicationContext(), getString(qixiao.com.btdownload.R.string.error), getString(qixiao.com.btdownload.R.string.error_open_torrent_file),//无法打开目标种子文件 Log.getStackTraceString(e), this); *//* FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(errDialog, TAG_ERROR_OPEN_TORRENT_FILE_DIALOG); ft.commitAllowingStateLoss();*//* } } } } break; case btConstant.ADD_TORRENT_REQUEST: if (resultCode == Activity.RESULT_OK) { if (data.hasExtra(AddTorrentActivity.TAG_RESULT_TORRENT)) { Torrent torrent = data.getParcelableExtra(AddTorrentActivity.TAG_RESULT_TORRENT); if (torrent != null) { ArrayList<Torrent> list = new ArrayList<>(); list.add(torrent); // addTorrentsRequest(list); } } } break; } }*/ private void gotoHome() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 注意 intent.addCategory(Intent.CATEGORY_HOME); this.startActivity(intent); } /* private void addTorrentDialog(Uri uri) { if (uri == null) { return; } Intent i = new Intent(activity, AddTorrentActivity.class); i.putExtra(AddTorrentActivity.TAG_URI, uri); startActivityForResult(i, btConstant.ADD_TORRENT_REQUEST); } private void torrentFileChooserDialog() { Intent i = new Intent(activity, FileManagerDialog.class); List<String> fileType = new ArrayList<>(); fileType.add("torrent"); FileManagerConfig config = new FileManagerConfig(null, getString(qixiao.com.btdownload.R.string.torrent_file_chooser_title),//选择 torrent 文件 fileType,//torrent FileManagerConfig.FILE_CHOOSER_MODE); i.putExtra(FileManagerDialog.TAG_CONFIG, config); startActivityForResult(i, btConstant.TORRENT_FILE_CHOOSE_REQUEST); }*/ }
11,042
0.581556
0.579825
301
35.458473
26.940979
118
false
false
0
0
0
0
0
0
0.574751
false
false
11