text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ReadPK other = (ReadPK) obj;
if (idISIEAdministrator != other.idISIEAdministrator)
return false;
if (idRepport != other.idRepport)
return false;
return true;
} | 5 |
private void addEmptyThings(){
SortedSet<String> keys = new TreeSet<String>(data.keySet());
for (String path : keys) {
while(true){
path = deleteLastLevel(path);
if(path == null || path.equals("")) {
break;
}
if(data.get(path) == null){
data.put(path, " ");
}
}
}
} | 5 |
private static void checkProjectValid(){
List<ProjectError> errors = new ArrayList<ProjectError>();
File file;
for(String path : allPath){
file = new File(path);
if(!file.exists()){
errors.add(new ProjectError(ProjectError.FOLDER_MISSING, path));
}
}
/*
String errorMessage = "";
if(!(new File(projectPath).exists())){
errorMessage = "This project is invalid.\nCan't find project folder (" + projectPath + ")";
}
else if(!(new File(assetsPath).exists())){
errorMessage = "This project is invalid.\nCan't find assets folder (" + assetsPath + ")";
}
else if(!(new File(dataGamePath).exists())){
errorMessage = "This project is invalid.\nCan't find assets folder (" + dataGamePath + ")";
}
else if(!(new File(dataEditorPath).exists())){
errorMessage = "This project is invalid.\nCan't find assets folder (" + dataEditorPath + ")";
}
//else if(!(new File(settingsPath).exists())){
// errorMessage = "This project is invalid.\nCan't find settings folder (" + settingsPath + ")";
//}
*/
if(errors.size() == 0){ //Valid project
}
else{ //Invalid project
closeProject();
WidgetMgr.MAIN_WINDOW.setVisible(true);
JOptionPane.showMessageDialog(WidgetMgr.MAIN_WINDOW, "Can't find folder (" + errors.get(0).path + ")", "Invalid project", JOptionPane.ERROR_MESSAGE);
//JOptionPane.showMessageDialog(WidgetMgr.MAIN_WINDOW, errorMessage, "Invalid project", JOptionPane.ERROR_MESSAGE);
}
} | 3 |
@Override
public HsvImage clone() {
HsvImage cloned = shallowClone();
for (int x = 0; x < getWidth(); x++) {
for (int y = 0; y < getHeight(); y++) {
cloned.setPixel(x, y, HUE, getPixel(x, y, HUE));
cloned.setPixel(x, y, SATURATION, getPixel(x, y, SATURATION));
cloned.setPixel(x, y, VALUE, getPixel(x, y, VALUE));
}
}
return cloned;
} | 2 |
public int fileLines(String fileDirectory, String exclusion) throws IOException{
BufferedReader fileReader = null;
try {
fileReader = new BufferedReader(
new InputStreamReader(getClass().getResourceAsStream(fileDirectory)));
} catch (NullPointerException propertiesReaderNPE) {
try {
fileReader = new BufferedReader(
new InputStreamReader(new FileInputStream(fileDirectory)));
} catch (NullPointerException propertiesReaderNPE2) {
System.err.print("\nThe directory: " + fileDirectory + " failed to load.\n\n");
propertiesReaderNPE2.printStackTrace();
}
}
String readIn = null;
int lineCount = 0;
do{
try {
readIn = fileReader.readLine();
if(readIn.startsWith(exclusion)
&& !exclusion.equals("")){
continue;
}
lineCount++;
} catch (NullPointerException fileReaderCounterNPE) {
break;
}
}while(!readIn.equals(null));
return lineCount;
} | 6 |
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource().equals(nextMonthButton)) {
GregorianCalendar cal = (GregorianCalendar)calendarModel.getCalendarClone();
int day = cal.get(Calendar.DATE);
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, 1);
if (day > cal.getActualMaximum(Calendar.DAY_OF_MONTH)) {
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
} else {
cal.set(Calendar.DATE, day);
}
calendarModel.setCalendar(cal.getTime());
} else if (arg0.getSource().equals(previousMonthButton)) {
GregorianCalendar cal = (GregorianCalendar)calendarModel.getCalendarClone();
int day = cal.get(Calendar.DATE);
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) - 1, 1);
if (day > cal.getActualMaximum(Calendar.DAY_OF_MONTH)) {
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
} else {
cal.set(Calendar.DATE, day);
}
calendarModel.setCalendar(cal.getTime());
} else {
for (int month = 0; month < monthPopupMenuItems.length; month++) {
if (arg0.getSource().equals(monthPopupMenuItems[month])) {
GregorianCalendar cal = (GregorianCalendar)calendarModel.getCalendarClone();
int day = cal.get(Calendar.DATE);
cal.set(cal.get(Calendar.YEAR), month, 1);
if (day > cal.getActualMaximum(Calendar.DAY_OF_MONTH)) {
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
} else {
cal.set(Calendar.DATE, day);
}
calendarModel.setCalendar(cal.getTime());
}
}
}
} | 7 |
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(onStart) {
switch(key) {
case KeyEvent.VK_ENTER:
onStart = false;
selectLocation = true;
}
}
else if(selectLocation) {
switch(key) {
case KeyEvent.VK_1:
Character.setLocation(LOCATION.LUMBRIDGE);
selectLocation = false; break;
case KeyEvent.VK_2:
Character.setLocation(LOCATION.VARROCK);
selectLocation = false; break;
case KeyEvent.VK_3:
Character.setLocation(LOCATION.FALADOR);
selectLocation = false; break;
case KeyEvent.VK_4:
Character.setLocation(LOCATION.WILDERNESS);
selectLocation = false; break;
}
}
} | 7 |
public void build(Object object, Container location, IXMLElement xml, Runnable onUpdate) throws GUIBuilderException{
if (!xml.getName().equals("parameters") && !xml.getName().equals("group")){
throw new GUIBuilderException("Top level tag if XML must be <controls>. Parse failed.");
}
Enumeration children = xml.enumerateChildren();
while (children.hasMoreElements()){
IXMLElement child = (IXMLElement) children.nextElement();
String childName = child.getName();
if (childName.equals("int")){
buildInt(object, location, child, onUpdate);
continue;
}
if (childName.equals("double")){
buildDouble(object, location, child, onUpdate);
continue;
}
if (childName.equals("boolean")){
buildBoolean(object, location, child, onUpdate);
continue;
}
if (childName.equals("option")){
buildOption(object, location, child, onUpdate);
continue;
}
if (childName.equals("push")){
buildPush(object, location, child, onUpdate);
continue;
}
if (childName.equals("group")){
buildGroup(object, location, child, onUpdate);
continue;
}
//unknown tag: skipping it
System.err.println("Unknown tag in a description:");
System.err.println(child);
}
} | 9 |
public static void main(String args[])
{
/* Set the Nimbus look and feel */
try
{
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName()))
{
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch (ClassNotFoundException ex)
{
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new GUI();
}
});
} | 6 |
public String undesiredQueries(String first, String second, String country, String query) {
String cheshireResult = null;
String countryQuery = "";
try
{
//**********************************************************************************************************
// Undesired Searching Mechanisms
// These should only be used if the above fail, and each one should taken individually. If one
// succeeds, the rest should NOT be done
//
// Also, these methods should have their confidence penalized heavily! They are NOT guaranteed to return
// what we want at ALL.
// Try a ranking name query by keyword
if (numResults == 0) {
out.println("find name @ '" + first + "' and admin1 @ '" + second + "'" + countryQuery);
cheshireResult = in.readLine();
addResult(cheshireResult);
if (GeoNamesHelper.debug) System.err.println("Query keyword Name w/ admin1.\t\tResults: " + this.numResults);
}
// Print out a message if DEBUG
if (GeoNamesHelper.debug && numResults == 0)
System.err.println("== Switching to NGRAMS Searching ==");
// Search Geonames name, admin, alt names for ngram matches. Cheshire does NOT do post processing to clean up the
// results, so these results must be post processed!
if (numResults == 0) {
out.println("find ngram_wadmin '" + query + "'");
cheshireResult = in.readLine();
addResult(cheshireResult);
if (GeoNamesHelper.debug) System.err.println("Query ngrams w/admin on entire string.\tResults: " + this.numResults);
}
/**
* The below searches are some ways to find better ngrams matches. These provided some help in getting better order
* out of Cheshire, which is why they were tried in a particular order. However, with post-processing of the search
* above, these become unnecessary as post-processing produces better results than any of these individually.
*/
/*
// Next, try a query on just ngrams in the name/admin code plus ranking of exact name (for bad state names)
if (numResults == 0) {
out.println("find ngram '" + first + "' and exactname @ '" + first + "'" + countryQuery);
cheshireResult = in.readLine();
addResult(cheshireResult);
}
// Next, try a looking for matching ngrams
if (numResults == 0) {
out.println("find ngram '" + first + "' and name_wadmin @ '" + query + "'" + countryQuery);
cheshireResult = in.readLine();
addResult(cheshireResult);
}
// Next, try looking for just ngrams and keyword name
if (numResults == 0) {
out.println("find ngram '" + first + "' and name @ '" + first + "'" + countryQuery);
cheshireResult = in.readLine();
addResult(cheshireResult);
}
// Finally, just check ngrams
if (numResults == 0) {
out.println("find ngram_all_wadmin '" + query + "'" + countryQuery);
cheshireResult = in.readLine();
addResult(cheshireResult);
}
*/
//**********************************************************************************************************
if (results.size() > 0)
return results.get(0);
return null;
} catch (Exception e) {
return null;
}
} | 8 |
public static void processT(String tempDir)
throws FileNotFoundException, NoSuchElementException, IOException, ProcessException
{
File trigramSortedInterDataFile = FileUtil.getFileInDirectoryWithSuffix(tempDir, TrigramExternalSort.DATA_SUFFIX);
File unigramDataFile = FileUtil.getFileInDirectoryWithSuffix(tempDir, UnigramPreprocess.DATA_SUFFIX);
String trigramDataFilePathname = tempDir + File.separator + FileUtil.getFilenameWithoutSuffix(trigramSortedInterDataFile) + '.' + DATA_SUFFIX;
String trigramCountFilePathname = tempDir + File.separator + FileUtil.getFilenameWithoutSuffix(trigramSortedInterDataFile) + '.' + COUNT_SUFFIX;
try (
BufferedReader trigramSortedInterData = new BufferedReader(new FileReader(trigramSortedInterDataFile));
BufferedWriter trigramData = new BufferedWriter(new FileWriter(trigramDataFilePathname));
BufferedWriter trigramCount = new BufferedWriter(new FileWriter(trigramCountFilePathname));
){
String unigramDataName = FileUtil.getFilenameWithoutSuffix(unigramDataFile.getCanonicalPath(), UnigramPreprocess.DATA_SUFFIX);
String trigramDataName = FileUtil.getFilenameWithoutSuffix(trigramDataFilePathname, TrigramCountSummation.DATA_SUFFIX);
// Add header to the files
IOUtil.writePreprocTrigramHeader(trigramData, new File(unigramDataName), new File(trigramDataName), "data");
IOUtil.writePreprocTrigramHeader(trigramCount, new File(unigramDataName), new File(trigramDataName), "count");
int gram1ID = 0, gram2ID = 0, prevGram1ID = 0, prevGram2ID = 0;
long freq = 0, count = 0;
boolean isFirstGram = true;
for (String inputLine; (inputLine = trigramSortedInterData.readLine()) != null; ) {
StringTokenizer line = new StringTokenizer(inputLine);
gram1ID = Integer.parseInt(line.nextToken());
gram2ID = Integer.parseInt(line.nextToken());
if (isFirstGram) {
prevGram1ID = gram1ID;
prevGram2ID = gram2ID;
freq = Long.parseLong(line.nextToken());
trigramData.write(Integer.toString(gram1ID));
isFirstGram = false;
} else if (gram1ID == prevGram1ID && gram2ID == prevGram2ID) {
freq += Long.parseLong(line.nextToken());
} else {
// Use frequency instead of relatedness.
if (freq > 0) {
trigramData.write("\t" + prevGram2ID + "\t" + freq);
count++;
}
if (prevGram1ID != gram1ID)
trigramData.write("\n" + Integer.toString(gram1ID));
prevGram1ID = gram1ID;
prevGram2ID = gram2ID;
freq = Long.parseLong(line.nextToken());
}
}
if (prevGram1ID != gram1ID)
trigramData.write("\n" + gram1ID);
// Use frequency instead of relatedness.
if (freq > 0) {
trigramData.write("\t" + prevGram2ID + "\t" + freq);
count++;
}
// Write cout to the cout file.
trigramCount.write(Long.toString(count));
}
} | 8 |
public static void main(String s[]) {
JFrame f = new JFrame("See Through Image");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
URL imageSrc = null;
try {
imageSrc = ((new File(imageFileName)).toURI()).toURL();
} catch (MalformedURLException e) {
}
SeeThroughImageApplet sta = new SeeThroughImageApplet(imageSrc);
sta.buildUI();
f.add("Center", sta);
f.pack();
f.setVisible(true);
} | 1 |
void ConstructProgramState(LoadType loadType, GUI parentGUI, String filterTag){
//mainGUI.isChangingState = true;
switch (loadType){
case Init:
Settings.setSettingAndSave("databaseFilePathAndName", getSetting("homeDir")+getSetting("databasePathExt")+getSetting("databaseFileName"));
InitDemoDB.initDB(Settings.getSetting("databaseFilePathAndName"));//Resets database
Settings.setSettingAndSave("databaseVersion", ImageDatabase.getDatabaseVersion());
case Load:
mainGUI.mainImageDB = new ImageDatabase(getSetting("databaseFileName"),getSetting("databaseFilePathAndName"));
checkDBVersion();
//no break as image list must still be passed from DB
case Refresh:
//Create image database by loading database
currentFilter = "-1";
imageIDs = mainGUI.mainImageDB.getAllImageIDs();
break;
case LoadLast:
mainGUI.mainImageDB = new ImageDatabase(getSetting("databaseFileName"),getSetting("databaseFilePathAndName"));
checkDBVersion();
//change currentI by maingGUI.settings.getSetting("LastCurrentI") but be careful of null, etc.
case Filter:
//Create image database by loading database
if(filterTag==null) {
log.print(LogType.Error,"Error: Tried to filter by tag without a filter.");
ConstructProgramState(LoadType.Load, parentGUI, "");
return;
} else if (filterTag.equals("-1")){
ConstructProgramState(LoadType.Refresh, parentGUI, filterTag);
return;
}
currentFilter = filterTag;
imageIDs = mainGUI.mainImageDB.getImageIDsFromTagIDChildren(filterTag); // Working on TagID not TagTitle
break;
}
Settings.setSettingAndSave("lastFilterUsed", currentFilter);
//if imageIDs.length==0
//then a file should be added first (Construct with Init&imports, then return;)
imageList = new ImageReference[imageIDs.length];
numberOfImages = imageList.length;
for(int i=0; i<imageIDs.length;i++){
imageList[i] = new ImageReference(mainGUI.mainImageDB.getImageFilename(imageIDs[i]));
}
lastIndex = (imageIDs.length - 1);
//mainGUI.isChangingState = false; //Set false before calling imageChanged thumbPanel.onResize() waits for this to be false
//Needed as GUI components not cfreated yet
//if((loadType!=LoadType.Init) && (loadType!=LoadType.Load)){
//imageChanged();//Will cause deadlock or bugs if uncommented. Call after constructing
//}
if(imageList.length<1){
log.print(LogType.DebugError,"Error: There are no images loaded under current search.\nEnsure filter has some images.");
imageIDs = new String[1];
imageIDs[0] = "-1";
imageList = new ImageReference[1];
imageList[0] = new ImageReference("NoExistingFiles:a:b:c:d:e:f:g:h.i.j.k.l.m.n:o:p:non.ex");
}
imageChanged();
} | 9 |
DeviceImpl (USB bus, String drivername, int a)
throws IOException, SecurityException
{
super (null, bus, a);
usb = bus;
path = drivername;//f.getPath ();
if(MacOSX.trace)
System.err.println("in usb.macosx.DeviceImpl()\n");
// should only fail if the device unplugged before
// we opened it, or permissions were bogus, or ...
long openstat = openNative (path);
if (openstat < 0) {
String message = "JUSB can't open device r/w, " + path;
throw new USBException (message, (int)(-openstat));
} else {
fd = (int)openstat; //openNative() returns a DLL device handle between 1 & 127 on success
}
int num_descriptor_retries = 0;
IOException descriptor_exception = null;
do {
// fd's open; NOW we can get the device descriptor
try {
byte buf [];
buf = ControlMessage.getStandardDescriptor (this,
Descriptor.TYPE_DEVICE, (byte) 0, 0, 18);
descriptor = new DeviceDescriptor (this, buf);
// ... and configuration descriptor
getConfiguration ();
if (MacOSX.trace)
System.err.println ("new: " + path);
return;
} catch (USBException ue) {
if (MacOSX.debug)
ue.printStackTrace ();
else if(MacOSX.trace)
System.err.println ("get dev descr fail: "
+ path
+ ", "
+ ue.getMessage ());
descriptor_exception = ue;
} catch (IOException e) {
if (MacOSX.debug)
System.err.println ("get dev descr fail: "
+ path
+ ", "
+ e.getMessage ());
throw e;
}
} while ( num_descriptor_retries++ < 4 );
throw descriptor_exception;
} | 9 |
public void setQualification(int qualification) {
this.qualification = (qualification > 0 && qualification < 5) ? qualification:
0;
} | 2 |
private void getStatsFile() throws Exception {
BufferedReader r = new BufferedReader(new FileReader("stats_"
+ nodeName + ".txt"));
String str;
while ((str = r.readLine()) != null) {
out.println(str);
}
r.close();
} | 1 |
DBPort get( boolean keep , ReadPreference readPref, ServerAddress hostNeeded ){
DBPort pinnedRequestPort = getPinnedRequestPortForThread();
if ( hostNeeded != null ) {
if (pinnedRequestPort != null && pinnedRequestPort.serverAddress().equals(hostNeeded)) {
return pinnedRequestPort;
}
// asked for a specific host
return getConnection(new ServerAddressSelector(hostNeeded));
}
if ( pinnedRequestPort != null ){
// we are within a request, and have a port, should stick to it
if ( portIsAPrimary(pinnedRequestPort) || !keep ) {
// if keep is false, it's a read, so we use port even if primary changed
return pinnedRequestPort;
}
// it's write and primary has changed
// we fall back on new primary and try to go on with request
// this may not be best behavior if spec of request is to stick with same server
pinnedRequestPort.getProvider().release(pinnedRequestPort);
setPinnedRequestPortForThread(null);
}
DBPort port = getConnection(createServerSelector(readPref));
// if within request, remember port to stick to same server
if (threadHasPinnedRequest()) {
setPinnedRequestPortForThread(port);
}
return port;
} | 7 |
public int NumShips(int playerID) {
int numShips = 0;
for (Planet p : planets) {
if (p.Owner() == playerID) {
numShips += p.NumShips();
}
}
for (Fleet f : fleets) {
if (f.Owner() == playerID) {
numShips += f.NumShips();
}
}
return numShips;
} | 4 |
private boolean alter() throws UnsupportedEncodingException
{
if(storeName == null || storeName.isEmpty())
return false ;
if(storeAddr == null || storeAddr.isEmpty())
return false ;
String tempName = new String(storeName.getBytes("ISO-8859-1"),"UTF-8") ;
Session se = HibernateSessionFactory.getSession() ;
Store tempS = (Store)se.load(Store.class, alterStoreId) ;
if(!tempS.getName().equals(tempName))
{
Criteria category_cri = se.createCriteria(Store.class) ;
category_cri.add(Restrictions.eq("name", tempName)) ;
if(!category_cri.list().isEmpty())
{
se.close() ;
return false ;
}
}
Transaction tran = se.beginTransaction() ;
tran.begin() ;
Store currStore = (Store)se.load(Store.class, alterStoreId) ;
currStore.setName(tempName) ;
String tempAddr = new String(storeAddr.getBytes("ISO-8859-1"),"UTF-8") ;
currStore.setAddress(tempAddr) ;
se.update(currStore) ;
tran.commit() ;
se.close() ;
return true ;
} | 6 |
private void treeButtonClick(java.awt.event.ActionEvent evt) {
GraphElement[] ges = graph.getMinimalSpanningTree();
if (ges == null) return;
for (int i = 0; i < ges.length; i++) {
ges[i].getComponent().setColor(TREEANDMINIMUMCOLOR);
}
} | 2 |
public static void main(String[] args) throws Throwable{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for(;;){
StringTokenizer st = new StringTokenizer(in.readLine().trim());
int N = parseInt(st.nextToken()), M = parseInt(st.nextToken());
if(M==0&&N==0)break;
int[] heads = new int[N], knights = new int[M];
for (int i = 0; i < N; i++) heads[i] = parseInt(in.readLine().trim());
for (int i = 0; i < M; i++) knights[i] = parseInt(in.readLine().trim());
long res = 0;
Arrays.sort(heads);
Arrays.sort(knights);
int k = 0;
for (int i = 0; i < knights.length && k < heads.length; i++)
if(knights[i]>=heads[k]){
res+=knights[i];
k++;
}
if(k < heads.length)System.out.println("Loowater is doomed!");
else System.out.println(res);
}
} | 9 |
private static GameField parseSquares(Scanner scanner)
throws MapLoaderException {
int width = scanner.nextInt();
int height = scanner.nextInt();
if (!scanner.next().equals("SQUARES")) {
throw new MapLoaderException("Squares section not found.");
}
Square[][] map = new Square[width][height];
char squareChar;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
squareChar = scanner.next().charAt(0);
SquareTag tag = SquareTag.getName(squareChar);
if (tag == null) {
throw new MapLoaderException(
String.format(
"Invalid character in SQUARES section at (%d, %d) position.",
i, j));
}
switch (tag) {
case GRASS:
map[i][j] = Square.GRASS;
break;
case MOUNTAIN:
map[i][j] = Square.MOUNTAIN;
break;
case WATER:
map[i][j] = Square.WATER;
break;
case TREE:
map[i][j] = Square.TREE;
break;
default:
throw new MapLoaderException(
String.format(
"Invalid character in SQUARES section at (%d, %d) position.",
i, j));
}
}
}
return new GameField(width, height, map);
} | 8 |
private static Set<String> writeMethods(TreeLogger logger,
GeneratorContext context, JClassType type, SourceWriter writer)
throws UnableToCompleteException {
Set<String> allUsedSelectionProperties = new HashSet<String>();
JMethod[] methods = type.getMethods();
for (JMethod method : methods) {
if (method.isStatic()) {
logger.log(Type.DEBUG,
"Ignoring static method " + method.getName());
continue;
}
if (!method.isPublic()) {
logger.log(Type.DEBUG,
"Ignoring non-public method " + method.getName());
continue;
}
Set<String> usedSeletionProperties = writeMethod(
logger.branch(
Type.DEBUG,
"Processing method "
+ method.getReadableDeclaration()),
context, method, writer);
if (usedSeletionProperties != null) {
allUsedSelectionProperties.addAll(usedSeletionProperties);
}
}
return allUsedSelectionProperties;
} | 4 |
public void testSetPeriod_8ints2() {
MutablePeriod test = new MutablePeriod(100L, PeriodType.millis());
try {
test.setPeriod(11, 12, 13, 14, 15, 16, 17, 18);
fail();
} catch (IllegalArgumentException ex) {}
assertEquals(0, test.getYears());
assertEquals(0, test.getMonths());
assertEquals(0, test.getWeeks());
assertEquals(0, test.getDays());
assertEquals(0, test.getHours());
assertEquals(0, test.getMinutes());
assertEquals(0, test.getSeconds());
assertEquals(100, test.getMillis());
} | 1 |
public static boolean isBalance(TreeNode root,ArrayList<Integer> depth){
if(root == null){
return true;
}
ArrayList<Integer> left = new ArrayList<Integer>();
left.add(0);
ArrayList<Integer> right = new ArrayList<Integer>();
right.add(0);
if(isBalance(root.left,left)&&isBalance(root.right,right)){
int dist = left.get(0) - right.get(0);
if(dist > 1 || dist < -1)
return false;
}
depth.add(0,Math.max(left.get(0), right.get(0)) + 1);
return true;
} | 5 |
private void checkForRepeatRun(Object n, ArrayList array, int[] arrayTotal){
if (array.isEmpty()) {
array.add(n);
} else {
if (array.contains(n)) {
array.add(n);
if (array.size() >= 7) {
array.clear();
arrayTotal[6]++;
} // if
} // if
else {
if (array.size() >= 2) {
arrayTotal[array.size()-1]++;
} // if
array.clear();
array.add(n);
} // else
} // if else
} | 4 |
@Override
protected void commandReceived(Object command) {
if (command instanceof Command) {
Command message = (Command)command;
String action = message.getCommand();
System.out.println("Command received: "+action);
if (action.equals("set_username")) {
// this.username = (String)message.getBaggage();
} else if (action.equals("select_card")) {
if (selectedCard == null &&
A2AServer.getInstance().getGameState() == WAIT_FOR_CARDS &&
A2AServer.getInstance().getCurrentHost() != this &&
message.getBaggage() instanceof RedCard &&
cards.contains(message.getBaggage())) {
this.selectedCard = (RedCard)message.getBaggage();
this.cards.remove(selectedCard);
sendCommand("select_card", selectedCard);
sendCommand("remove_card", selectedCard);
} else {
System.err.println("Cheating Client!");
kick();
}
} else {
System.err.println("unknown action: "+action);
}
} else {
System.err.println("Poorly Made Cheating Client!");
kick();
}
} | 8 |
@Override
public boolean isConnected() {
return connected;
} | 0 |
public model.Order getOrder() {
model.Order order = new model.Order();
DefaultTableModel tm = viewCustomer.getTmodel();
for (int i = 0; i < tm.getRowCount(); i++) {
Object t = tm.getValueAt(i, 4);
if (t == null)
continue;
int x = Integer.parseInt(t.toString());
if (x > 0) {
Product product = new Product(tm.getValueAt(i, 1).toString(),
Double.parseDouble(tm.getValueAt(i, 2).toString()), x,
Long.parseLong(tm.getValueAt(i, 0).toString()));
order.add(product);
}
}
return order;
} | 3 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Tuple)) return false;
Tuple tuple = (Tuple) o;
return !(key != null ? !key.equals(tuple.key) : tuple.key != null) && !(value != null ? !value.equals(tuple.value) : tuple.value != null);
} | 5 |
private static String getNextChild(String s)
{
int end;
int nest;
end = 0;
nest = 0;
while (s.charAt(end) != ')' || nest > 1)
{
if (s.charAt(end) == '(')
nest++;
else if (s.charAt(end) == ')')
nest--;
end++;
}
return (s.substring(0, end + 1));
} | 4 |
@Override
public String getCur() {return cur;} | 0 |
private void generateDummyHardwareAlternatives() {
if (cpuAlternatives.size() == 0)
cpuAlternatives.add(new HardwareAlternative("", ""));
if (hddAlternatives.size() == 0)
hddAlternatives.add(new HardwareAlternative("", ""));
if (memoryAlternatives.size() == 0)
memoryAlternatives.add(new HardwareAlternative("", ""));
if (networkAlternatives.size() == 0)
networkAlternatives.add(new HardwareAlternative("", ""));
if (platformAlternatives.size() == 0)
platformAlternatives.add(new HardwareAlternative("", ""));
if (otherAlternatives.size() == 0)
otherAlternatives.add(new HardwareAlternative("", ""));
} | 6 |
public void putAll( Map<? extends Double, ? extends Character> map ) {
Iterator<? extends Entry<? extends Double,? extends Character>> it =
map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends Double,? extends Character> e = it.next();
this.put( e.getKey(), e.getValue() );
}
} | 8 |
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking, tickID))
return false;
if(ticking instanceof MOB)
{
final MOB mob=(MOB)ticking;
if(mob != invoker())
{
if((invoker()!=null)&&(!CMLib.flags().isInTheGame(invoker(), true)))
{
unInvoke();
return false;
}
if(dirs.size()>0)
{
final int dir=dirs.remove(0).intValue();
CMLib.tracking().walk(mob, dir, false, false);
if(dirs.size()==0)
{
invoker().tell(L("\n\r^SThe eye has reached its destination and will soon close.^N^?"));
super.tickDown=6;
}
}
}
}
else
unInvoke();
return true;
} | 7 |
public boolean isWall(int x, int y, int direction) {
if (isBorder(x, y, direction))
return true;
switch (direction) {
case NORTH:
if( y<=0 )
return true;
else
return (columnWalls[x][y - 1]);
case SOUTH:
if( y>=(this.rows-1))
return true;
else
return (columnWalls[x][y]);
case EAST:
if(x>=(this.columns-1))
return true;
else
return (rowWalls[y][x]);
case WEST:
if(x<=0)
return true;
else
return (rowWalls[y][x - 1]);
}
return false;
} | 9 |
@Override
public HerbType type() {
if (empty()) {
return HerbType.HERB_PATCH;
}
if (dead()) {
return HerbType.DEAD;
}
final int bits = bits();
for (HerbType type : HerbType.values()) {
if (type.valid(bits)) {
return type;
}
}
throw new IllegalArgumentException("Unknown herb type! bits:" + bits);
} | 4 |
public AbstractSaveConvertor(Class<T> clazz, final String namespace,
final String localName, final Connection con,
final String sqlExists, final String sqlInsert,
final String sqlUpdate, final String sqlInsertNoGis,
final String sqlUpdateNoGis) throws SQLException {
this.clazz = clazz;
this.namespace = namespace;
this.localName = localName;
this.connection = con;
this.pstmExists =
sqlExists == null ? null : con.prepareStatement(sqlExists);
String sqlInsertAdj = Config.isNoGis() ? sqlInsertNoGis : sqlInsert;
String sqlUpdateAdj = Config.isNoGis() ? sqlUpdateNoGis : sqlUpdate;
if (Config.isMysqlDriver()) {
sqlInsertAdj = fixSql(sqlInsertAdj);
sqlUpdateAdj = fixSql(sqlUpdateAdj);
}
if (sqlInsertAdj != null) {
sqlInsertAdj = formatGeometry(sqlInsertAdj);
}
if (sqlUpdateAdj != null) {
sqlUpdateAdj = formatGeometry(sqlUpdateAdj);
}
this.pstmInsert = sqlInsertAdj == null
? null : con.prepareStatement(sqlInsertAdj);
this.pstmUpdate = sqlUpdateAdj == null
? null : con.prepareStatement(sqlUpdateAdj);
} | 8 |
public static void Command(CommandSender sender)
{
if(sender.hasPermission("gm.survival.all"))
{
for(Player player : Bukkit.getServer().getOnlinePlayers())
{
if (player.getGameMode() != GameMode.SURVIVAL)
{
player.setGameMode(GameMode.SURVIVAL);
if(sender instanceof Player)
{
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Changed Target GameMode").toString(), sender, (Player) sender, player, true, false, false, null);
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Player Changed Your GameMode").toString(), sender, (Player) sender, player, false, true, false, null);
}
else
{
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Changed Target GameMode").toString(), sender, null, player, true, false, false, null);
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Player Changed Your GameMode").toString(), sender, null, player, false, true, false, null);
}
}
else
{
if(sender instanceof Player)
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.Target Already in GameMode").toString(), sender, (Player) sender, player, true, false, false, null);
else
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.Target Already in GameMode").toString(), sender, null, player, true, false, false, null);
}
}
}
else
{
if(sender instanceof Player)
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.No Permission").toString(), sender, (Player) sender, null, true, false, false, null);
else
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.No Permission").toString(), sender, null, null, true, false, false, null);
}
} | 6 |
private int copyFieldsWithDeletions(final FieldsWriter fieldsWriter, final IndexReader reader,
final FieldsReader matchingFieldsReader)
throws IOException, MergeAbortedException, CorruptIndexException {
int docCount = 0;
final int maxDoc = reader.maxDoc();
if (matchingFieldsReader != null) {
// We can bulk-copy because the fieldInfos are "congruent"
for (int j = 0; j < maxDoc;) {
if (reader.isDeleted(j)) {
// skip deleted docs
++j;
continue;
}
// We can optimize this case (doing a bulk byte copy) since the field
// numbers are identical
int start = j, numDocs = 0;
do {
j++;
numDocs++;
if (j >= maxDoc) break;
if (reader.isDeleted(j)) {
j++;
break;
}
} while(numDocs < MAX_RAW_MERGE_DOCS);
IndexInput stream = matchingFieldsReader.rawDocs(rawDocLengths, start, numDocs);
fieldsWriter.addRawDocuments(stream, rawDocLengths, numDocs);
docCount += numDocs;
checkAbort.work(300 * numDocs);
}
} else {
for (int j = 0; j < maxDoc; j++) {
if (reader.isDeleted(j)) {
// skip deleted docs
continue;
}
// NOTE: it's very important to first assign to doc then pass it to
// termVectorsWriter.addAllDocVectors; see LUCENE-1282
Document doc = reader.document(j);
fieldsWriter.addDocument(doc);
docCount++;
checkAbort.work(300);
}
}
return docCount;
} | 8 |
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Enum<?> parseEnum(String s) {
String className = s.split(":")[0];
String value = s.split(":")[1];
for (Class<? extends Enum> c : enums_) {
if (c.getSimpleName().equals(className)) {
return Enum.valueOf(c, value);
}
}
return null;
} | 4 |
private void loadConfig(){
FileConfiguration config = new YamlConfiguration();
try{
config.load(this.getResource("config.yml"));
/**
* debug is initialized to true in case there is a problem reading the
* config itself, so that the error will print out.
*
* When reading however, it's defaulted to false if no value is specified.
*/
debug = config.getBoolean("debug", false);
}catch (IOException | InvalidConfigurationException ex){
LOG.severe("[Dungeons] An error occurred reading the config file.");
if(debug)
ex.printStackTrace();
}
} | 2 |
private static BigFraction parse(String s){
try{
if(s == null){
return null;
}
if(s.isEmpty()){
return null;
}
char[] c = s.toCharArray();
c = removeChar(c, (char) 32);
c = removeChar(c, (char) 43);
int l = c.length;
byte[] b = new byte[l];
b[0] = findFirst(c[0]);
int i = 1;
for(;i < l;i++){
b[i] = find(c[i]);
if(b[i] == -2){
break;
}
}
if(b[i] != -2){
throw new NumberFormatException();
}
i++;
b[i] = findFirst(c[i]);
i++;
for(;i < l; i++){
b[i] = findAfter(c[i]);
}
return fromByteArray(b);
}
catch(IllegalArgumentException e){
throw new NumberFormatException();
}
catch(ArrayIndexOutOfBoundsException e){
throw new NumberFormatException();
}
} | 8 |
public void talk() {
Printer.print("A person inexplicitly materalises in front of you purely for you to converse with."); // :P
TreeNode currentNode = dialogueTree.getRoot();
String input = null;// could be buggy with the space
do {
foundDialogue = false;
Printer.print(currentNode.getDialogue());
currentNode.setVisited(true);// probably don't need this
input = Printer.getInput();// could break here
Scanner inputScanner = new Scanner(input);
// checking if any of the words the player entered match any of the
// keywords for the children of the current node.
while (inputScanner.hasNext()) {
String currentWord = inputScanner.next();
TreeNode newNode = recursiveIterator(currentNode, currentWord);
if (newNode != null) {
currentNode = newNode;
}
for (TreeNode node : dialogueTree.getNodeArray()) {
node.setTempVisited(false);
}
}
inputScanner.close();
// goodbye should probably be in the text file too
if (!foundDialogue && input != null && !input.equals("goodbye")) {
// this string should possibly be in the textfile
Printer.print("Find something better to talk about or say \"goodbye\"");
}
} while (!input.equals("goodbye"));
} | 7 |
public int minimumTotal(List<List<Integer>> triangle) {
int[] min = new int[triangle.size()];
int[] preMin = new int[triangle.size()];
for (int i = 0; i < triangle.size(); i++) {
if (i == 0) {
min[0] = triangle.get(0).get(0);
}
else{
for (int k = 0; k < triangle.get(i).size(); k++) {
if (k == 0)
min[k] = preMin[k] + triangle.get(i).get(k);
else if (k == triangle.get(i).size() - 1)
min[k] = preMin[k - 1] + triangle.get(i).get(k);
else
min[k] = Math.min(preMin[k - 1], preMin[k])
+ triangle.get(i).get(k);
}
}
preMin = min.clone();
}
int result = Integer.MAX_VALUE;
for (int i = 0; i < min.length; i++) {
if (result > min[i])
result = min[i];
}
return result;
} | 7 |
@Override
public boolean blockActivated(EntityPlayer player) {
if (this instanceof ITrackReversable) {
ItemStack current = player.getCurrentEquippedItem();
if (current != null && current.getItem() instanceof IToolCrowbar) {
IToolCrowbar crowbar = (IToolCrowbar) current.getItem();
if (crowbar.canWhack(player, current, getX(), getY(), getZ())) {
ITrackReversable track = (ITrackReversable) this;
track.setReversed(!track.isReversed());
markBlockNeedsUpdate();
crowbar.onWhack(player, current, getX(), getY(), getZ());
return true;
}
}
}
return false;
} | 4 |
public NovacomInstallerView(SingleFrameApplication app) {
super(app);
initComponents();
String os = System.getProperty("os.name").toLowerCase();
if(os.contains("windows")) {
if(System.getenv("ProgramFiles(x86)")==null) {
jLabel2.setText("Windows 32bit");
} else {
jLabel2.setText("Windows 64bit");
}
} else if(os.contains("mac")) {
jLabel2.setText("Mac OS");
} else if(os.contains("linux")) {
if(!is64bitLinux()) {
jLabel2.setText("Linux 32bit");
} else {
jLabel2.setText("Linux 64bit");
}
} else {
jLabel2.setText("<unknown>");
}
} | 5 |
private void piirraTyonnin(Graphics g, Ruutu ruutu, int data) {
int x=ruutu.getX();
int y=ruutu.getY();
int seina=data%4;
List<Integer>lukuja=new ArrayList<>();
if (data<4) {
lukuja.add(2);
lukuja.add(4);
} else {
lukuja.add(1);
lukuja.add(3);
lukuja.add(5);
}
g.setColor(Color.black);
if (seina==3) {
g.fillRect((x)*ruudunkoko-7, koko-y*ruudunkoko+2, 5, 35);
g.drawLine((x)*ruudunkoko-7, koko-y*ruudunkoko+9, (x)*ruudunkoko, koko-y*ruudunkoko+9);
g.drawLine((x)*ruudunkoko-7, koko-y*ruudunkoko+30, (x)*ruudunkoko, koko-y*ruudunkoko+30);
int i=1;
for (Integer integer : lukuja) {
g.drawString(integer.toString(), (x-1)*ruudunkoko+4, koko-y*ruudunkoko+11*i);
i=i+1;
}
g.setColor(Color.yellow);
g.fillRect((x)*ruudunkoko-7, koko-y*ruudunkoko+9, 5, 7);
g.fillRect((x)*ruudunkoko-7, koko-y*ruudunkoko+23, 5, 7);
} else if (seina==1){
g.fillRect((x-1)*ruudunkoko+5, koko-y*ruudunkoko+2, 5, 35);
g.drawLine((x-1)*ruudunkoko+5, koko-y*ruudunkoko+9, (x-1)*ruudunkoko, koko-y*ruudunkoko+9);
g.drawLine((x-1)*ruudunkoko+7, koko-y*ruudunkoko+30, (x-1)*ruudunkoko, koko-y*ruudunkoko+30);
int i=1;
for (Integer integer : lukuja) {
g.drawString(integer.toString(), x*ruudunkoko-10, koko-y*ruudunkoko+11*i);
i++;
}
g.setColor(Color.yellow);
g.fillRect((x-1)*ruudunkoko+5, koko-y*ruudunkoko+9, 5, 7);
g.fillRect((x-1)*ruudunkoko+5, koko-y*ruudunkoko+23, 5, 7);
} else if (seina==2){
g.fillRect((x-1)*ruudunkoko+2, koko-y*ruudunkoko+7, 35, 5);
g.drawLine((x-1)*ruudunkoko+9, koko-y*ruudunkoko+7,(x-1)*ruudunkoko+9, koko-y*ruudunkoko);
g.drawLine((x-1)*ruudunkoko+30, koko-y*ruudunkoko+7,(x-1)*ruudunkoko+30, koko-y*ruudunkoko);
String luvut="";
for (Integer integer : lukuja) {
luvut=luvut+integer+" ";
}
g.drawString(luvut, (x-1)*ruudunkoko+2, koko-y*ruudunkoko+30);
g.setColor(Color.yellow);
g.fillRect((x-1)*ruudunkoko+9, koko-y*ruudunkoko+7, 7, 5);
g.fillRect((x-1)*ruudunkoko+23, koko-y*ruudunkoko+7, 7, 5);
} else {
g.fillRect((x-1)*ruudunkoko+2, koko-y*ruudunkoko+30, 35, 5);
g.drawLine((x-1)*ruudunkoko+9, koko-y*ruudunkoko+30,(x-1)*ruudunkoko+9, koko-y*ruudunkoko+40);
g.drawLine((x-1)*ruudunkoko+30, koko-y*ruudunkoko+30,(x-1)*ruudunkoko+30, koko-y*ruudunkoko+40);
String luvut="";
for (Integer integer : lukuja) {
luvut=luvut+integer+" ";
}
g.drawString(luvut, (x-1)*ruudunkoko+2, koko-y*ruudunkoko+12);
g.setColor(Color.yellow);
g.fillRect((x-1)*ruudunkoko+9, koko-y*ruudunkoko+30, 7, 5);
g.fillRect((x-1)*ruudunkoko+23, koko-y*ruudunkoko+30, 7, 5);
}
} | 8 |
private void addVertices(ArrayList<Vertex> vertices, int i, int j, float offset, boolean x, boolean y, boolean z, float[] texCoords)
{
if(x && z)
{
vertices.add(new Vertex(new Vector3f(i * SPOT_WIDTH, offset * SPOT_HEIGHT, j * SPOT_LENGTH), new Vector2f(texCoords[1],texCoords[3])));
vertices.add(new Vertex(new Vector3f((i + 1) * SPOT_WIDTH, offset * SPOT_HEIGHT, j * SPOT_LENGTH), new Vector2f(texCoords[0],texCoords[3])));
vertices.add(new Vertex(new Vector3f((i + 1) * SPOT_WIDTH, offset * SPOT_HEIGHT, (j + 1) * SPOT_LENGTH), new Vector2f(texCoords[0],texCoords[2])));
vertices.add(new Vertex(new Vector3f(i * SPOT_WIDTH, offset * SPOT_HEIGHT, (j + 1) * SPOT_LENGTH), new Vector2f(texCoords[1],texCoords[2])));
}
else if(x && y)
{
vertices.add(new Vertex(new Vector3f(i * SPOT_WIDTH, j * SPOT_HEIGHT, offset * SPOT_LENGTH), new Vector2f(texCoords[1],texCoords[3])));
vertices.add(new Vertex(new Vector3f((i + 1) * SPOT_WIDTH, j * SPOT_HEIGHT, offset * SPOT_LENGTH), new Vector2f(texCoords[0],texCoords[3])));
vertices.add(new Vertex(new Vector3f((i + 1) * SPOT_WIDTH, (j + 1) * SPOT_HEIGHT, offset * SPOT_LENGTH), new Vector2f(texCoords[0],texCoords[2])));
vertices.add(new Vertex(new Vector3f(i * SPOT_WIDTH, (j + 1) * SPOT_HEIGHT, offset * SPOT_LENGTH), new Vector2f(texCoords[1],texCoords[2])));
}
else if(y && z)
{
vertices.add(new Vertex(new Vector3f(offset * SPOT_WIDTH, i * SPOT_HEIGHT, j * SPOT_LENGTH), new Vector2f(texCoords[1],texCoords[3])));
vertices.add(new Vertex(new Vector3f(offset * SPOT_WIDTH, i * SPOT_HEIGHT, (j + 1) * SPOT_LENGTH), new Vector2f(texCoords[0],texCoords[3])));
vertices.add(new Vertex(new Vector3f(offset * SPOT_WIDTH, (i + 1) * SPOT_HEIGHT, (j + 1) * SPOT_LENGTH), new Vector2f(texCoords[0],texCoords[2])));
vertices.add(new Vertex(new Vector3f(offset * SPOT_WIDTH, (i + 1) * SPOT_HEIGHT, j * SPOT_LENGTH), new Vector2f(texCoords[1],texCoords[2])));
}
else
{
System.err.println("Invalid plane used in level generator");
new Exception().printStackTrace();
System.exit(1);
}
} | 6 |
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o == yeastTxt){
try {
myRecipe.getYeastObj().setCost(SBStringUtils.myNF.parse(yeastTxt.getText()).doubleValue());
} catch (ParseException e1) {
e1.printStackTrace();
}
displayCost();
}
if (o == otherTxt){
try {
myRecipe.setOtherCost(SBStringUtils.myNF.parse(otherTxt.getText()).doubleValue());
} catch (ParseException e1) {
e1.printStackTrace();
}
displayCost();
}
if (o == bottleSizeTxt){
try {
NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
Number number = format.parse(bottleSizeTxt.getText().trim());
myRecipe.setBottleSize(number.doubleValue());
} catch (NumberFormatException m) {
Debug.print("Could not parse bottleSizeTxt as a double");
bottleSizeTxt.setText(Double.toString(myRecipe.getBottleSize()));
} catch (ParseException m) {
Debug.print("Could not parse bottleSizeTxt as a double");
bottleSizeTxt.setText(Double.toString(myRecipe.getBottleSize()));
}
displayCost();
}
if (o == bottleSizeUCmb){
myRecipe.setBottleU(bottleSizeUCmbModel.getSelectedItem().toString());
displayCost();
}
} | 8 |
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -1;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 1;
}
if (key == KeyEvent.VK_UP) {
dy = -1;
}
if (key == KeyEvent.VK_DOWN) {
dy = 1;
}
} | 4 |
public void finDuJeu() {
int tailleTexte = 0;
if (Configurations.getGrilleX() < 20) {
tailleTexte = 0;
}
else if (Configurations.getGrilleX() < 30) {
tailleTexte = 4;
}
else if (Configurations.getGrilleX() < 40) {
tailleTexte = 8;
}
else if (Configurations.getGrilleX() <= 50) {
tailleTexte = 12;
}
contentpan = new JPanel();
contentpan.setBackground(Color.decode("#CC6600"));
JLabel fin = new JLabel("Fin du jeu ! Le monstre est mort...");
fin.setFont(new Font("Consolas",Font.BOLD , 12 + tailleTexte));
fin.setBackground(Color.WHITE);
contentpan.add(fin);
fen.setContentPane(contentpan);
fen.setVisible(true);
} | 4 |
public int majorityNumberTwo(ArrayList<Integer> nums, int k) {
int len = nums.size();
if (len < k) {
return -1;
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int x : nums) {
if (map.size() < k && !map.containsKey(x)) {
map.put(x, 1);
} else if (map.containsKey(x)) {
map.put(x, map.get(x) + 1);
} else {
Map<Integer, Integer> tmp = new HashMap<Integer, Integer>();
for (int key : map.keySet()) {
if (map.get(key) > 1) {
tmp.put(key, map.get(key)-1);
}
}
map = tmp;
}
}
int result = 0;
int count = 0;
for (int key : map.keySet()) {
if (map.get(key) > count) {
result = key;
count = map.get(key);
}
}
return result;
} | 9 |
public void run() {
while (true) {
try {
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
while (true){
String consoleInput = in.readLine();
String[] args = consoleInput.split(" ");
String cmd = args[0];
if (cmd.equals("stop")) {
System.out.println("Shutting down server.");
gVars.sendServerMessage("The server is going down for halt NOW!");
ircBot.writeToChannel("[NOTICE] The server is shutting down!");
ircBot.writeToServer("QUIT Shutdown");
Main.serverSocket.close();
System.exit(1);
} else if (cmd.equals("help")) {
System.out.println("stop: Saves data and shuts down the servers");
System.out.println("help: Shows this command help menu");
} else {
System.out.println("Unknown Command!");
System.out.println("Use 'help' for a list of commands.");
}
}
} catch (NullPointerException e) {
e.printStackTrace();
break;
} catch (IOException e) {
}
}
} | 6 |
public void handle() {
// Make sure the player is not already on the server; if so, ignore this packet:
if (World.getPlayers().length >= BBServer.getConfig().getPlayerCap()) {
BBServer.getSenderDaemon().outgoingPacketQueue.add(new Packet01AuthResponse(username, 0, address, port));
System.out.println("Player " + username + " failed to join: server is full");
return;
}
if (World.getPlayer(username) != null || BBServer.getPacketManager().hasAssociatedDeauthTask(username)) {
BBServer.getSenderDaemon().outgoingPacketQueue.add(new Packet01AuthResponse(username, 1, address, port));
System.out.println("Player " + username + " failed to join: username is taken");
return;
}
if (!BBServer.getConfig().getPassword().equals("") && !BBServer.getConfig().getPassword().equals(password)) {
BBServer.getSenderDaemon().outgoingPacketQueue.add(new Packet01AuthResponse(username, 2, address, port));
System.out.println("Player " + username + " failed to join: wrong password");
return;
}
BBServer.getSenderDaemon().outgoingPacketQueue.add(new Packet01AuthResponse(username, 3, address, port));
BBServer.getPacketManager().runDeauthTask(new DeauthTask(username, address, port, 5, 2000));
} | 5 |
private void backButtonAction() {
// check if it's ok
if(currentStepIndex<=1 || currentPanel==null)
return;
currentPanel.saveUserInput();
lastPressed = "back";
currentStepIndex--;
displaySteps();
// update button status
if(!nextButton.isEnabled())
nextButton.setEnabled(true);
if(finishButton.isEnabled())
finishButton.setEnabled(false);
if(currentStepIndex<=1)
backButton.setEnabled(false);
if ( currentStepIndex < stepsPanelList.size() && stepsPanelList.get(currentStepIndex) instanceof InstallPanel )
nextButton.setText("Install");
else
nextButton.setText("Next >");
} | 7 |
public String getStringValue() throws IOException {
if (type == INDIRECT) {
return dereference().getStringValue();
} else if (type == STRING || type == NAME || type == KEYWORD) {
return (String) value;
}
// wrong type
return null;
} | 4 |
private void doCommand(String cmd) {
if (cmd.startsWith("S")) {
doSleep(Integer.parseInt(cmd.substring(1)));
} else if (cmd.startsWith("X")) {
doShutdown();
} else if (cmd.equals("help")) {
doHelp();
} else if (cmd.equals("$DONE")) {
logger.info("DONE ALL OPERATIONS");
} else {
logger.info("Bad command: '{}'. Try 'help'", cmd);
}
} | 4 |
public static boolean isBestResult(int difficulty, long time) {
long[] times;
switch (difficulty) {
case Grid.DIFFICULTY_EASY: times = instance.easyTime; break;
case Grid.DIFFICULTY_MEDIUM: times = instance.mediumTime; break;
case Grid.DIFFICULTY_HARD: times = instance.hardTime; break;
case Grid.DIFFICULTY_EXTREME: times = instance.extremeTime; break;
default: return false;
}
for (long result : times) {
if (time < result) {
return true;
}
}
return false;
} | 6 |
private boolean invalidCall(Server server, long ID) {
for (Player p : server.players) {
if (p.getReaderThreadID() == ID)
return true;
}
return false;
} | 2 |
public void setVisible(boolean isVisible) {
super.setVisible(isVisible);
log.setVisible(isVisible);
} | 0 |
@Override
public String toString() {return String.valueOf(cur);} | 0 |
@Override
public BencodeTreeNode getChild ( Object parent, int index ) {
Value<?> vprt = ( (BencodeTreeNode) parent ).getValue();
if ( vprt instanceof ListValue ) {
return new BencodeTreeNode( ( (ListValue) vprt ).get( index ), vprt, index );
} else if ( vprt instanceof DictionaryValue ) {
Iterator<Map.Entry<String,Value<?>>> it = ( (DictionaryValue) vprt ).getValue().entrySet().iterator();
for ( int i = 0; i < index; i++ ) {
it.next();
}
Map.Entry<String,Value<?>> entry = it.next();
return new BencodeTreeNode( entry.getValue(), vprt, '"' + entry.getKey() + '"' );
}
return null;
} | 6 |
public static void downloadFile(File file, String location) {
BufferedInputStream input = null;
FileOutputStream output = null;
try {
URL url = new URL(location);
input = new BufferedInputStream(url.openStream());
output = new FileOutputStream(file);
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1)
output.write(data, 0, count);
} catch (IOException e) {
xAuthLog.severe("Failed to download file: " + file.getName(), e);
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {}
try {
if (output != null)
output.close();
} catch (IOException e) {}
}
} | 6 |
public String toString(String input) {
return "("+input+")^"+_power;
} | 0 |
public static void payFine(int fineId){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
conn.setAutoCommit(false);
PreparedStatement stmnt = conn.prepareStatement("UPDATE Fines set paid = 1 WHERE fine_id = ?");
stmnt.setInt(1, fineId);
stmnt.execute();
conn.commit();
conn.setAutoCommit(true);
}
catch(SQLException e){
System.out.println("Remove fail: " + e);
}
} | 4 |
public static Class getModelIdType(Class model) {
if (model.isAssignableFrom(Model.class))
throw new IllegalArgumentException(EXC_NOTAMODEL);
Method[] declareds = CommonStatic.getDeclaredGetters(model);
Class returnType = null;
boolean found = false;
for (Method m : declareds)
if (m.isAnnotationPresent(Id.class)) {
found = true;
returnType = m.getReturnType();
}
if (!found) {
List<Class> supers = CommonStatic.getSupers(model);
if (supers.size() > 1)
throw new MalformedModelRuntimeException("You have to define an" +
" Id for multiple inheritance.");
else if (supers.size() == 1)
returnType = getModelIdType(supers.get(0));
else returnType = Integer.TYPE; /* no inheritance */
}
return returnType;
} | 6 |
public PTrailer loadTrailer(long position) {
PTrailer trailer = null;
try {
if (m_SeekableInput != null) {
m_SeekableInput.beginThreadAccess();
long savedPosition = m_SeekableInput.getAbsolutePosition();
m_SeekableInput.seekAbsolute(position);
Parser parser = new Parser(m_SeekableInput);
Object obj = parser.getObject(library);
if (obj instanceof PObject)
obj = ((PObject) obj).getObject();
trailer = (PTrailer) obj;
if (trailer != null)
trailer.setPosition(position);
m_SeekableInput.seekAbsolute(savedPosition);
}
}
catch (Exception e) {
logger.log(Level.FINE,
"Error loading PTrailer instance: " + position, e);
}
finally {
if (m_SeekableInput != null)
m_SeekableInput.endThreadAccess();
}
return trailer;
} | 5 |
public static long find(String name) throws SQLException {
long catID = -1;
for(Category c : list())
if (c.getName().equals(name))
catID = c.getId();
return catID;
} | 2 |
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
} | 0 |
public int geocode(DataSetDescriptor dsd, String address) {
NominatimConnector nm = new NominatimConnector("http://nominatim.openstreetmap.org/search.php");
nm.setFormat("json");
boolean containColumn = address.contains("{");
int rowCont = 0;
if(!containColumn){
// In order to not contain a column name into the search, the geometry field is the same for all
nm.setQuery(address);
String geoColumnAddress = nm.getAddress();
System.out.println(geoColumnAddress);
// Update all fields with geoColumnAddress and geoColumnName
this.updateGeometryColumn(dsd, geoColumnAddress);
}else{
// Get the columns from address
List<String> col = new LinkedList<String>();
nm.getColumnsToGeom(col, address);
SqlRowSet columnsMap = this.getColumnsByList(dsd, col);
while(columnsMap.next()){
for(String c:col){
String dir = address;
String param = columnsMap.getString(c);
int pk = columnsMap.getInt(dsd.getNamePK());
dir = dir.replace("{" + c + "}", param);
nm.setQuery(dir);
String geoAddress = nm.getAddress();
if(geoAddress!=null){
String[] splitGeom = geoAddress.split(",");
Double lon = Double.valueOf(splitGeom[0]);
Double lat = Double.valueOf(splitGeom[1]);
String updateSQL = "UPDATE " + dsd.getTablename() +
" SET " + dsd.getGeoColumnName() + " = ST_GeomFromEWKT(:geom)" +
" WHERE " + dsd.getNamePK() + "=:pk";
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("pk", pk);
paramMap.put("geom", "SRID=4326;POINT("+lon+" "+lat+")");
this.namedJdbcTemplate.update(updateSQL, paramMap);
}else{
rowCont++;
}
}
}
}
return rowCont;
} | 4 |
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
java.security.cert.X509Certificate[] chain = null;
try {
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
KeyStore tks = KeyStore.getInstance("JKS");
tks.load(this.getClass().getClassLoader().getResourceAsStream("SSL/serverstore.jks"),
SERVER_KEY_STORE_PASSWORD.toCharArray());
tmf.init(tks);
chain = ((X509TrustManager) tmf.getTrustManagers()[0]).getAcceptedIssuers();
} catch (Exception e) {
throw new RuntimeException(e);
}
return chain;
} | 1 |
public Integer call() throws InterruptedException {
int sum = 0;
for (int i = 0; i < 100000; i++) {
sum += i;
}
System.out.println(numberOfThread);
return numberOfThread;
} | 1 |
@SuppressWarnings("unchecked")
public static float[][] restoreData(String findFromFile) {
float[][] dataSet = null;
try {
FileInputStream filein = new FileInputStream(findFromFile);
ObjectInputStream objin = new ObjectInputStream(filein);
try {
dataSet = ( float[][]) objin.readObject();
} catch (ClassCastException cce) {
cce.printStackTrace();
}
objin.close();
} catch (Exception ioe) {
ioe.printStackTrace();
System.out.println("NO resume: saver");
}
return dataSet;
} // /////////// //////////////////////////// | 2 |
public void addCacheItem( int cacheId, int cacheItem )
{
int insertIndex = 0;
for( BiffRec br : pivotCacheRecs.get( cacheId + 1 ) )
{
if( br.getOpcode() == SXFDB )
{
((SxFDB) br).setNCacheItems( ((SxFDB) br).getNCacheItems() + 1 );
}
else if( br.getOpcode() == EOF )
{
insertIndex = pivotCacheRecs.get( cacheId + 1 ).indexOf( br );
/**/
}
}
// add required SXDBB for non-summary-cache items
if( cacheItem > -1 )
{
/* SXDBB records only exist when put cache fields on a pivot table axis == cache item*/
SxDBB sxdbb = (SxDBB) SxDBB.getPrototype();
sxdbb.setCacheItemIndexes( new byte[]{
Integer.valueOf( cacheItem ).byteValue()
} ); //ByteTools.shortToLEBytes((short)cacheItem));
pivotCacheRecs.get( cacheId + 1 ).add( insertIndex, sxdbb );
}
updateCacheRecords( cacheId );
} | 4 |
public AnnotationVisitor visitAnnotation(final String desc,
final boolean visible) {
if (!ClassReader.ANNOTATIONS) {
return null;
}
ByteVector bv = new ByteVector();
// write type, and reserve space for values count
bv.putShort(cw.newUTF8(desc)).putShort(0);
AnnotationWriter aw = new AnnotationWriter(cw, true, bv, bv, 2);
if (visible) {
aw.next = anns;
anns = aw;
} else {
aw.next = ianns;
ianns = aw;
}
return aw;
} | 2 |
private void printIssueInfos() throws ParseException, IOException{
boolean cutoff_c = false;
boolean cutoff_n = false;
for (IssueInfo issueInfo : issueInfos) {
String issueInfoPrint = "";//TODO: issueInfo.printString(socialGraph);
String durationInfo = "";//TODO: issueInfo.printDurations();
if(!issueInfo.isConsensus()){
fopNonConsensus.write(issueInfoPrint.getBytes());
if(issueInfo.getComments().get(0).getDate().getTime() > cutoffDate.getTime() && !cutoff_n){
cutoff_n = true;
String temp = "-------------";
fopNonConsensus.write(temp.getBytes());
}
//fopAuthors.write(AuthorInfoPrint.getBytes());
fopNonConsensus.flush();
}else if(issueInfo.isConsensus()){
fopDurations.write(durationInfo.getBytes());
fopDurations.flush();
fopConsensus.write(issueInfoPrint.getBytes());
if(issueInfo.getComments().get(0).getDate().getTime() > cutoffDate.getTime() && !cutoff_c){
cutoff_c = true;
String temp = "-------------";
fopConsensus.write(temp.getBytes());
}
// fopConsensus.write(AuthorInfoPrint.getBytes());
fopConsensus.flush();
}else
System.out.println("issue: ");
}
} | 7 |
@Override
public String toString()
{
return "isAnnotation()";
} | 0 |
private boolean jj_3_29() {
if (jj_3R_46()) return true;
return false;
} | 1 |
public void setRegion(String region) {
this.region = region;
} | 0 |
private void emitKeyValues(String key, String... values) {
emitKey(key);
startArray();
for (String value : values) {
emitTabs();
mOut.print("<string>"); //$NON-NLS-1$
mOut.print(value);
mOut.println("</string>"); //$NON-NLS-1$
}
endArray();
} | 1 |
public void updateRightSideLabels() {
for (JLabel label : rolesList) {
label.setText("");
}
rolesList.clear();
// String roleToString = "";
//
// for (Role role : balance.getChosenRoles()) {
// roleToString = role.toString();
// if (role.getBalancevalue() > 0 && role.getAmount() >= 1) {
// roleToString = role.getAmount() + "x " + role.getName() + " (+" + role.getBalancevalue() + ")";
// }
// if (role.getAmount() >= 1 && role.getBalancevalue() <= 0) {
// roleToString = role.getAmount() + "x " + role.toString();
// }
// rolesList.add(new JLabel(roleToString));
// }
String roleToString = "";
for (Role role : balance.getChosenRoles()) {
roleToString = role.toString();
if (role.getBalancevalue() > 0) {
roleToString = role.getName() + " (+" + role.getBalancevalue() + ")";
}
rolesList.add(new JLabel(roleToString));
}
players.setText("Players: " + balance.howManyPlayers());
String balancevalue = "" + balance.determineTownVsAntitownBalance();
if (balance.determineTownVsAntitownBalance() > 0) {
balancevalue = "+" + balancevalue;
}
balanceLabel.setText("Balance: " + balancevalue);
String start;
if (balance.getDayStart() == true) {
start = "Day Start";
} else {
start = "Night Start";
}
dayLabel.setText("Day/Night Start: " + start);
double townOdds = Math.round(balance.getTeamVictoryOdds(1) * 10000.0) / 100.0;
double skOdds = Math.round(balance.getTeamVictoryOdds(2) * 10000.0) / 100.0;
double survOdds = Math.round(balance.getTeamVictoryOdds(3) * 10000.0) / 100.0;
double antitownSurvOdds = Math.round(balance.getTeamVictoryOdds(4) * 10000.0) / 100.0;
double assassinOdds = Math.round(balance.getTeamVictoryOdds(5) * 10000.0) / 100.0;
double mafiaOdds = Math.round(balance.getTeamVictoryOdds(6) * 10000.0) / 100.0;
townOddsLabel.setText("Town Victory Odds: " + townOdds + "%");
mafiaOddsLabel.setText("Mafia Victory Odds: " + mafiaOdds + "%");
skOddsLabel.setText("Single Serial Killer Victory Odds: " + skOdds + "%");
survOddsLabel.setText("Single Survivor Victory Odds: " + survOdds + "%");
aSurvOddsLabel.setText("Single Anti-Town Survivor Victory Odds: " + antitownSurvOdds + "%");
assassinOddsLabel.setText("Single Assassin Victory Odds: " + assassinOdds + "%");
fastestTownLabel.setText("Town: " + balance.determineFastestVictoryForTown());
fastestMafiaLabel.setText("Mafia (1 KP): " + balance.determineFastestVictoryForMafia(1));
fastestMafiaLabel2.setText("Mafia (2 KP): " + balance.determineFastestVictoryForMafia(2));
fastestMafiaLabel3.setText("Mafia (3 KP): " + balance.determineFastestVictoryForMafia(3));
for (JLabel label : rolesList) {
rightSideBox.add(label);
}
} | 6 |
@Override
public Object deponiUovo(String token, String idDinosauro) {
try {
if (myLogica.isMioTurno(token)) {
if ( myLogica.getPlayerByToken(token).getRazza().existsDinosauroWithId(idDinosauro)) {
String ret = myLogica.doDeponiUovo(token, idDinosauro);
if (ret != null) { return "@ok," + ret; }
}
return "@no,@idNonValido";
}
else return "@no,@nonIlTuoTurno";
}
catch (InvalidTokenException e) {
return returnInvalidToken();
}
catch (NonInPartitaException e) {
return "@no,@nonInPartita";
}
catch (GenericDinosauroException e) {
if (e.getMessage().equals("mortePerInedia")) return "@no,@mortePerInedia";
if (e.getMessage().equals("raggiuntaDimensioneMax")) return "@no,@raggiuntaDimensioneMax";
if (e.getMessage().equals("raggiuntoLimiteMosseDinosauro")) return "@no,@raggiuntoLimiteMosseDinosauro";
}
return "@no";
} | 9 |
public File saveGrammarDialog(final File cur) {
File dir = cur;
if(dir == null || !dir.exists()) {
dir = INI.getObject("last", "grammarDir", Converter.FILE_CONVERTER, HOME_STR);
}
final JFileChooser choose = new JFileChooser(dir);
choose.setMultiSelectionEnabled(false);
choose.setFileSelectionMode(JFileChooser.FILES_ONLY);
final boolean approved = choose.showSaveDialog(this) == JFileChooser.APPROVE_OPTION;
final File res = approved ? choose.getSelectedFile() : null;
if(res != null) {
INI.setObject("last", "grammarDir", res.getParentFile());
}
return res;
} | 4 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CardCombination other = (CardCombination) obj;
if (cardCombinationEnum != other.cardCombinationEnum)
return false;
if (cards == null) {
if (other.cards != null)
return false;
} else if (!cards.equals(other.cards))
return false;
return true;
} | 7 |
public synchronized void broadCast(String message,User user){
for(User client:users){
if(client==null)continue;
if(client != user)
client.getChatSocket().sendMessage(message);
}
} | 3 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Country other = (Country) obj;
if (country == null) {
if (other.country != null)
return false;
} else if (!country.equals(other.country))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
} | 9 |
private void flipHorizontal() {
switch(direction)
{
case NORTH:
case SOUTH:
break;
case EAST:
setDirection(Direction.WEST);
break;
case WEST:
setDirection(Direction.EAST);
break;
case NORTHEAST:
setDirection(Direction.NORTHWEST);
break;
case NORTHWEST:
setDirection(Direction.NORTHEAST);
break;
case SOUTHEAST:
setDirection(Direction.SOUTHWEST);
break;
case SOUTHWEST:
setDirection(Direction.SOUTHEAST);
break;
}
} | 8 |
private Long getExpiration(URLConnection connection, long baseTime) {
DateFormat PATTERN_RFC1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); //, Locale.US
String cacheControl = connection.getHeaderField("Cache-Control");
if (cacheControl != null) {
java.util.StringTokenizer tok = new java.util.StringTokenizer(cacheControl, ",");
while(tok.hasMoreTokens()) {
String token = tok.nextToken().trim().toLowerCase();
if ("must-revalidate".equals(token)) {
return new Long(0);
}
else if (token.startsWith("max-age")) {
int eqIdx = token.indexOf('=');
if (eqIdx != -1) {
String value = token.substring(eqIdx+1).trim();
int seconds;
try {
seconds = Integer.parseInt(value);
return new Long(baseTime + seconds * 1000);
}
catch(NumberFormatException nfe) {
System.err.println("getExpiration(): Bad Cache-Control max-age value: " + value);
// ignore
}
}
}
}
}
String expires = connection.getHeaderField("Expires");
if (expires != null) {
try {
synchronized(PATTERN_RFC1123) {
java.util.Date expDate = PATTERN_RFC1123.parse(expires);
return new Long(expDate.getTime());
}
}
catch(java.text.ParseException pe) {
int seconds;
try {
seconds = Integer.parseInt(expires);
return new Long(baseTime + seconds * 1000);
}
catch(NumberFormatException nfe) {
System.err.println("getExpiration(): Bad Expires header value: " + expires);
}
}
}
return null;
} | 9 |
@Override
public String toString () {
switch (operation) {
case 0: return "sync operation (" + toEnd + ") to " + startPosition;
case 1: return "insert " + data + "(" + toEnd + ")" + " to " + startPosition + " position";
case 2: return "delete " + "data" + " from " + startPosition + "-" + endPosition + " positions";
case 3: return "replace and set to " + data + " from " + startPosition + "-" + endPosition + " positions";
default: return "no operations";
}
} | 4 |
public void setStringAndReminder( String valueName, String s ) {
JTextField valueField = stringMap.get( valueName );
if ( valueField != null ) valueField.setText(s);
if ( remindersVisible ) setReminder( valueName, s );
} | 2 |
public void writeResultSetSlice(ResultSetSlice rss) throws IOException {
if (trace == API_TRACE_DETAILED) {
Log.current.println("writeResultSetSlice = " + rss);
}
ResultSet rs = rss.resultSet();
int first = rss.first();
int last = rss.last();
int columnCount = rss.columnCount();
write(CFASL_RESULT_SET_SLICE);
writeInt(rss.rowCount());
writeInt(rss.sliceRowCount());
writeInt(columnCount);
writeInt(first);
try {
rss.beforeFirst();
for (int row = first; row <= last; row++) {
rs.next();
for (int column = 1; column <= columnCount; column++) {
writeObject(rs.getObject(column));
}
}
}
catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
} | 4 |
private String process_HTTP_request(String text)
{
Pattern p = Pattern.compile("GET \\/([\\w\\.]*) HTTP");
Matcher m = p.matcher(text);
if (m.find())
{
String filename = m.group(1);
if (filename.matches("\\s*") || filename == null)
filename = "file.txt";
return read_file(filename);
}
else
{
//requisição mal formada!
return null;
}
} | 3 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
while ((line = in.readLine()) != null && line.length() != 0) {
int nCase = Integer.parseInt(line.trim());
for (int i = 0; i < nCase; i++) {
int[] a = readInts(in.readLine());
int ans = 0;
for (int j = 2; j < a.length; j++)
if (a[j - 1] < a[j])
ans++;
out.append((i + 1) + " " + ans + "\n");
}
}
System.out.print(out);
} | 5 |
public static void rooked(int i, int j, int cur) {
max = Math.max(max, cur);
for (int k = 0; k < size; k++) {
for (int l = 0; l < size; l++) {
if (m[k][l] == '.' && checkPos(k, l)) {
m[k][l] = 'o';
rooked(0, 0, cur + 1);
m[k][l] = '.';
}
}
}
} | 4 |
public boolean checkParams(Map<String, String> params) {
Iterator<ParamCons> it = nConstraint.iterator();
while(it.hasNext()) {
ParamCons cons = it.next();
if(!checkOneParam(cons, params.get(cons.name))) return false;
}
return true;
} | 2 |
public static void main(String[] args) throws Exception {
int ponder = 5;
if (args.length > 0)
ponder = Integer.parseInt(args[0]);
int size = 5;
if (args.length > 1)
size = Integer.parseInt(args[1]);
ExecutorService exec = Executors.newCachedThreadPool();
Chopstick[] stics = new Chopstick[size];
for (int i = 0; i < size; i++)
stics[i] = new Chopstick();
for (int i = 0; i < size; i++)
exec.execute(new Philosopher(stics[i], stics[(i+1) % size], i, ponder));
if (args.length == 3 && args[2].equals("timeout"))
TimeUnit.SECONDS.sleep(5);
else {
System.out.println("Press Enter to Exit");
System.in.read();
}
exec.shutdownNow();
} | 6 |
public void setVar(List<?> list)
{
for(PVar e : this._var_)
{
e.parent(null);
}
this._var_.clear();
for(Object obj_e : list)
{
PVar e = (PVar) obj_e;
if(e.parent() != null)
{
e.parent().removeChild(e);
}
e.parent(this);
this._var_.add(e);
}
} | 4 |
public static List<Cottage> getAllCottages(boolean refresh) throws SQLException
{
if (!refresh)
{
if (staticCottages != null)
return staticCottages;
}
List<Cottage> cottages = new ArrayList<Cottage>();
List<Zip> zips = ZipConnect.getAllZip(false);
List<CottageType> types = getAllCottageTypes();
String sql = "SELECT * FROM cottage order by id";
Connection conn = DBConnect.getConnection();
PreparedStatement p = conn.prepareStatement(sql);
ResultSet rs = p.executeQuery();
while (rs.next())
{
int id = rs.getInt(1);
String name = rs.getString(2);
String street = rs.getString(3);
String houseNumber = rs.getString(4);
int zipCode = rs.getInt(5);
int cottageType = rs.getInt(6);
Zip zip = null;
CottageType type = null;
for (Zip z : zips)
{
if (z.getZipCode() == zipCode)
{
zip = z;
}
}
for (CottageType t : types)
{
if (t.getCottageTypeId() == cottageType)
{
type = t;
}
}
Cottage cottage = new Cottage(id, type, name, street, houseNumber, zip);
cottages.add(cottage);
}
return cottages;
} | 7 |
public ArrayList<Customer> deleteCustomer(ArrayList<Customer> c)
{
boolean looking = true;
String proposedFirst = null;
String proposedLast = null;
while (looking)
{
boolean notFound = true;
System.out.println("Please enter the first name of the customer that you would like to delete.");
proposedFirst = input.next();
proposedFirst = proposedFirst.toLowerCase().trim();
System.out.println("Please enter the last name of the customer that you would like to delete.");
proposedLast = input.next();
proposedLast = proposedLast.toLowerCase().trim();
String proposedName = proposedFirst+proposedLast;
int counter = 0;
while (notFound && counter<c.size())
{
Customer currentCust = c.get(counter);
String custFirst = currentCust.getFirst().toLowerCase().trim();
String custLast = currentCust.getLast().toLowerCase().trim();
String custName = custFirst+custLast;
if (proposedName.equals(custName))
{
notFound = false;
looking = false;
c.remove(counter);
System.out.println("The customer has been deleted." );
continue;
}
counter++;
}
if (notFound)
{
looking = true;
System.out.println("The customer was not found. Please try again.");
}
}
return c;
} | 5 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.