samedi 28 février 2015

Only first and last GTK3 Combo Box Entry Working

I use C switch based on a variable I set according to which GTK Combo Box Text entry is selected ( variable = 3 <===> case 3: ... etc. ). There are 4 entries. My trouble is getting the 2nd and 3rd entries to actually do something.


Only the first and last entries seem to carry the variable value properly.


I have tested it repeatedly, seeing if I need to use if/else rather than a switch, to no avail. It is probably more than a coincidence, though, that the middle two entries are ignored in the program. Right now, I am using 4 if/else statements. There is the same behaviour, however, with switch (only the first and last entries cause the program to do something, which, in my case, is cause a dialog box to show and then, upon clicking, launch a terminal window showing progress).


Please, please, help is much appreciated.


Thanks.


P.S. I am using GTK3.


if in 'one file' and not in 'second file'

i've got a short question. I'm from Germany and I'm writing a library-management program. I've got a code, that asks if the entered username is in the user list and not in the list with locked persons (who haven't got the permissions to borrow books), but it doesn't works! Here's the code:



borrower=input("User ID: ")
userlist = open("userlist.txt", "r")
locked = open("locked.txt", "r")
if borrower in userlist and borrower not in locked:
#dosomething
elif borrrower in userlist and borrower in locked:
print("User",borrower,"isn't allowed to borrow books!")
else:
print("[ERROR] User",borrower,"doesn't exist!")


Please tell me what's wrong with this.


Why does one value keep appearing larger than the other?

So I'm trying to do this small program as a exercise for class and I honestly cannot figure out why the value for x keeps replacing w. Could someone explain to me why this is happening. I know ASCII-wise w has a smaller value than x so i genuinely don't understand.

import java.util.*;



public class SmallestIntMod
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a value for w: ");
int w = scan.nextInt();
int smallest = w;
System.out.println("Enter a value for x: ");
int x = scan.nextInt();
if (x < smallest);
{
smallest = x;
}
System.out.println("Enter a value for y: ");
int y = scan.nextInt();
if (y < smallest)
{
smallest = y;
}
System.out.println("Enter a value for z: ");
int z = scan.nextInt();
if (z < smallest)
{
smallest = z;
}
System.out.println("The smallest value is: " + smallest);
}
}

How to set up parameters in an if statement to allow me to move to a new page?

So I am trying to set up a username and password, then log in sort of deal. What I am having trouble figuring out is how to set up the if statement. So far I have it set up so if username and password are not correct, then a label displays "Username or password is incorrect." The problem is, when I click log in, no matter what it moves onto the next page. I need to stop it from moving to the next page unless the username and password are correct.



  • I am using storyboard to set it up, and I have a segue created to allow me to move to the next page. I am not using .XIB files.


Create a New Worksheet and Copying Rows from Original Worksheet

This script is supposed to:

1. Scroll down Column B where the Depts are located.

2. Next, select the entire Row of Data from Col A to Col F

3. Create a New Worksheet with the name of the Dept in Col B

4. Paste that Entire Row that was selected in the newly created worksheet

5. And then, move on to the Next Row until the End of the Data on the Original Data Sheet

6. If the Dept value is different from that of the previous row in Col B, then a New Worksheet is created and the routine begins again on the next Worksheet.


I suck and it fails at the IF Then Statement. Does AnyOne have an Idea, so I can move forward from this.


For some reason, the code is broken at the IF Then Statement



Sub Breakout()
Dim FinalRow As Long, I As Long
Dim valuenewsheet As String
Dim Sht As Object

FinalRow = Range("A" & Rows.count).End(xlUp).Row
MsgBox (FinalRow)

ActiveSheet.Range("B1").Select 'selects value in B1
valuenewsheet = (ActiveCell.Value) 'sets value as variable

Sheets.Add.Name = valuenewsheet 'creates new sheet
Worksheets("Sheet1").Select 'reselects original sheet where data is

Set Sht = ThisWorkbook.Sheets("Sheet1") 'sets org data sheet as sht

For I = 1 To FinalRow Step 1 'initiates a loop
Range(Sht.Cells(I, 6), Sht.Cells(I, 1).End(xlToLeft)).Select 'creates a range of data frm colA to colF one a single row
Selection.Copy 'copies this data
Sheets(valuenewsheet).Activate 'activates newly created sheet
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False 'pastes data frm slctd range
ActiveCell.Offset(1, 0).Select 'while on new sheet, select next row
Sht.Activate 'activate org. data sheet

If Sht.Cells(I, 2) <> Sht.Cells(I - 1, 2) Then
Sheets.Add.Name = Sht.Cells(I, 2).Value
Worksheets(Sht).Select
Else
End If
Next I
End Sub

Basic Monophonic synthesiser error Xcode


int main ()
{
int note, velocity;
int playingNote = -1;
float frequency;
printf("play the Axiom\n");

while(true)
{
note = aserveGetNote();
velocity = aserveGetVelocity();

if(velocity > 0)
{
frequency = 440 * pow(2, (note-69) / 12.0);
aserveOscillator(0, frequency, 1.0, 0);
playingNote = note;
}
else if(note == playingNote)
{
aserveOscillator(0, 0, 0, 0);
}

}
return 0;
}

if(velocity > 0)
{
frequency = 440 * pow(2,(note-69)/12.0);

printf("note = %d\n", note);
printf("frequency = %f\n", frequency);

aserveOscillator(0, frequency, 1.0, 0);

}

else if(note == playingNote)
{
aserveOscillator(0, 0, 0, 0);
}


This is supposed to run a simple monophonic synth. I get error messages on if(velocity >0) saying "expected unqualified - id" and on else if(note == playingNote) I get these error messages a lot in coding, can anyone help me out?


Strange bug in ( if, else ) Condition PHP

Dear All i am Really stucked at a Situation in a if, else Condition. The script behaves wrongly. For example, even if the Message is "Success" it goes to the second part(else) and mostly it executes the second part and then again executes the first part in any situation please help.



enter code here

if echo xxx -> echo xxx

This is my Code;


$output = curl_exec($ch); curl_close($ch); $temperatur = explode('T":', $output); echo substr($temperatur[1], 0, 4);


the echo substr gives me a number (e.g. 44). Is there a way in php to check if this number is under 50 and if yes, echo "blablaba".


I did something like this, but it wont work



$output = curl_exec($ch);
curl_close($ch);
$temperatur = explode('T":', $output);

$check = substr($temperatur[1], 0, 4);

if ($check < "50") {
echo "blabalabla";
}


Thank you for your help!


error on adding if else statement inside trigger mysql

I am new to triggers in mysql and found them really useful.I want a help regarding the trigger i am creating. First i created trigger on update event as follows:



CREATE TRIGGER `after_mytable_update` BEFORE UPDATE ON `my_table`
FOR EACH ROW SET NEW.total_pts=NEW.pts_1+NEW.pts_2+NEW.pts_3,
NEW.old_pts=OLD.total_pts


It worked fine now I need to add if/else inside my trigger so i dropped and recreated trigger as follows:



CREATE TRIGGER `after_mytable_update` BEFORE UPDATE ON `my_table`
FOR EACH ROW SET NEW.total_pts=NEW.pts_1+NEW.pts_2+NEW.pts_3,
NEW.old_pts=OLD.total_pts;
IF (NEW.total_pts>=0) THEN
UPDATE 'my_table' SET NEW.level='my_value';
END IF;


But it is giving error #1064. I need to set total_pts value outside if/else statement but I am new to triggers so can not figure out my mistake.


If Or Statement not working PHP

I am making a site where you can upload files. I just want people to upload Word, Powerpoint, Excel, PDF and JPG files. Therefore, I made this if-statement:



$target_dir = "files/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$filename = basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file selected
if (!isset($_FILES['fileToUpload']) || $_FILES['fileToUpload']['error'] == UPLOAD_ERR_NO_FILE) {
$msg = "No file selected. Try again.";
$uploadOk = 0;

} elseif (file_exists($target_file)) { // does file already exist?
$msg = "File already exists.";
$uploadOk = 0;

} elseif ($_FILES["fileToUpload"]["size"] > 10485760) { // filesize
$msg = "File too huge.";
$uploadOk = 0;

// THE PROBLEM IS IN THE FOLLOWING STATEMENT

} elseif ($fileType != "jpg" || $fileType != "doc" || $fileType != "docx" || $fileType != "ppt" || $fileType != "pptx" || $fileType != "xls" || $fileType != "xlsx" || $fileType != "pdf") {
$msg = "Filetype not allowed";
$uploadOk = 0;
}

if ($uploadOk != 0) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$msg = "File uploaded.";
} else {
$msg = "File not uploaded.";
}


However, when I upload a JPG,PDF,PHP or whatever, it always gives the error : Filetype not allowed. What am I doing wrong?


Error using simple IF statements, bolean variables and char marices

I'm writing a program that indicates if a maze, which is a matrix of chars, has a path. My first step is to verify that the first & last rows contain a specific char. the code is very simple yet it turns to work the opposite way. This is the code:


public static void main(String[] args) { // TODO Auto-generated method stub



final int ROWS = 5;
final int COLUMNS = 6;
int entryIndex = -1, exitIndex = -1, row;
boolean work = true;
boolean entryFound = false;
boolean exitFound = false;
char maze[][] = { {'a', '|', 'a', 'a', 'a', '|'},
{'a', 'a', 'a', 'a', 'a', '|'},
{'a', 'a', 'a', 'a', 'a', '|'},
{'a', 'a', 'a', 'a', 'a', '|'},
{'a', 'a', 'a', 'a', 'a', '|'} };

for (int col=0; col < COLUMNS; col++) {
if (maze[0][col] == '|') {
entryFound = true;
entryIndex = col;
}

for (int col2=0; col2 < COLUMNS; col2++) {
if (maze[ROWS-1][col2] == '|') {
exitFound = true;
exitIndex = col2;
}

if (entryFound == false || exitFound == false) {
//work = false;
System.out.println("No entry or exit for the maze had been found. Quitting");
return;
}


What I get at the end is the message that says "No entry or Exit had been found". How could this be? What could go wrong here?


IF statement in F90 errors

I have the code:



if i < n then
x = topsep(1)
y = topsep(2)
realvor(n,1) = x + dx
realvor(n,2) = x + dy
imvor(n,1) = (realvor(n,1)*(a**2))/((realvor(n,1))**2+(realvor(n,2))**2)
imvor(n,2) = (realvor(n,2)*(a**2))/((realvor(n,1))**2+(realvor(n,2))**2)
tf = .TRUE.
else
x = botsep(1)
y = botsep(2)
realvor(n,1) = x + dx
realvor(n,2) = y - dy
imvor(n,1) = (realvor(n,1)*(a**2))/((realvor(n,1))**2+(realvor(n,2))**2)
imvor(n,2) = (realvor(n,2)*(a**2))/((realvor(n,1))**2+(realvor(n,2))**2)
tf = .FALSE.
endif


Both i and n are defined as integers and I am inside a do loop for n = 1,100. This throws up the following errors:


Error: Unclassifiable statement at (1) at the 'if i< n then'


Error: Unexpected ELSE statement at (1) at the 'else'


Error: Expecting END DO statement at (1) at the 'endif'


I can't see where these errors are coming from, no matter how I write the if statement (.NE. etc.) it seems to throw up the same things.


Thanks


Frustraiting How are there too many arguments in this if statement


if [ $? -ne 0 ]; then
STATUS=$(cat $LOG.$i)
if [ $STATUS != "$i-DOWN!" ]; then
echo "$(date): ping failed, $i host is down!" |
mail -s "$(date) $i host is down!" $EMAIL
fi
echo "$(date) $i-DOWN!" > $LOG.$i
else
STATUS=$(cat $LOG.$i)
**------->>>**if [ $STATUS != "$i-UP!" ]; then
echo "$(date): ping OK, $i host is up!" |
mail -s "$(date) $i host is up!" $EMAIL
fi
echo "$(date) $i-UP!" > $LOG.$i
fi


I keep getting the error "Too many arguments" for that specific line with teh arrow pointing to it.. but I have the exact same line above it and do not get the error...


This is frustrating anyone have any idea why?


C programming language :if statements are not working correctly with characters

I'm trying to make this program say good but it says okay instead though I made the variable value the same of the if test value



#include <stdio.h>
#include <stdlib.h>

int main()
{
char history[200];
history == "NY school";

if(history == "NY school")
{
printf("good");
}
else{printf("okay");}
return 0;
}

Javascript if statement if (ball.style.left === '0px') {

I think the problem is really simple, but I'm not seeing it. I just want to move the "ball" to the left 132.5px when I click the "dice" and if the ball is 0px left.


I think the if statement is wrong!! Can someone help me?



var ball = document.getElementById('ball');
var dice = document.getElementById('dice');

function move() {
if (ball.style.left === '0px') {
ball.style.left = 132.5 + 'px';
}

}

dice.onclick = move;

vendredi 27 février 2015

Java if statement exception [on hold]

Define a List<Object> myList and put something in it so that its size is 1, and I print it out to make sure the size is actually 1.


Then for the following codes:



if(myList != null && myList.size() > 0){
print sth here
}


Then console shows nothing. Why? Since the size of myList is one.


But when I do this:



if (myList.size()>0){
print sth here
}


Then console do show something. What's the issue here?


IF ELSEIF fo array inside While loop PHP

I've get the value inside literal tag in this xml:



<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="/xml-to-html.xsl"?>
<sparql xmlns="http://ift.tt/1H8JDsT">
<head>
<variable name="Kategori"/>
</head>
<results>
<result>
<binding name="Kategori">
<literal datatype="http://ift.tt/QHQMAU">Gerak Kasar</literal>
</binding>
</result>
<result>
<binding name="Kategori">
<literal datatype="http://ift.tt/QHQMAU">Gerak Halus</literal>
</binding>
</result>
</results>
</sparql>


using this code:



$x = 0;
$kategori = array();
while ($x < count($hasilcek->results->result)) {
$kategori[$x]= $hasilcek->results->result[$x]->binding->literal;
$x++; }


But when I try to get the result by IF ELSEIF inside WHILE using this code:



$x = $x-1;
while ($x > -1){
if ($kategori[$x] = 'Gerak Kasar') {echo "Gerak Kasar";}
elseif ($kategori[$x] = 'Gerak Halus') {echo "Gerak Halus";}
else {echo "tidak ada";}
$x--;}


exactly the result should be:



Gerak Kasar Gerak Halus



but why i get :



Gerak KasarGerak Kasar



I think there is something wrong when I do IF selection for $kategori[] inside the WHILE. Can anyone explain? Thanks.


Plotting points in a grid formation

I'm trying to plot points on a graph given the X and Y coordinates of a single point. X and Y will both be integers between 1 and 9 (inclusive). And the graph should have each axis of size 9. I'm trying to do this using ASC11 characters, and i'm using the constants: width (X axis size) and height (Y axis size):


defineWIDTH9


defineHEIGHT9


I'm trying to get the graph to look like a 9x9 grid and it asks the user for input on which block they would like to plot a x on. So if they put 3,4 it would go 3 over (X) and 4 up (Y). How would I plot something like that using for loops and if statements?


Simple PHP string check not working

I hate to even post this question, but I can't seem to get this to work for me. I can echo $the_page directly before the if statement, but yet the if statement always comes up "else". Any ideas? Thank you in advance.



<?php if(is_page('sp')){$the_page = 1;} else { };

if($the_page === 1) { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#form-interest option:first:contains('---')").html('Área De Interés*:');
});
</script>
<?php } else { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#form-interest option:first:contains('---')").html('Area of Interest*:');
});
</script>
<?php } ?>

How can I pull a destination from a textbox? C#

I have a textbox that generates a code based on the selections made by the user. I would like each possible code to correlate with copying and moving a folder into another. The folder is chosen by another textbox that allows the user to manually select the path for the new files to be moved to. What I am looking to do is set up a string of if/else if statements for each of the possible codes from textbox1. Take a look at my code below and see wha tyou find. Everything seems to work except for my statements uder


Private void button1_click...



private void button1_Click(object sender, EventArgs e)
{
string destination = textBox1.Text;
if (textBox2.Text == "111")
String sourceFile = (@"C:\Program Files (x86)\OrganizerPro\TFSN Internal Advisor to SWAG PPW");

System.IO.File.Move(sourceFile, destination);
}

Excel vba how to repeat an if then else condition on rows

I want to repeat my 'if then else' condition on the 30 rows that follow. This is my code (I am new to this).



Dim score As Range, result As Double
If Range("A2") = "2a" Then
Range("C2") = 20

Else
If Range("A2") = "3c" Then
Range("C2") = 23


So at the moment when I enter 2a / 3c in cell A2, the number 20 / 23 comes up in cell C2. I would like the same thing to happen in row 3, 4, 5 ... 30. When I enter 2a / 3c in cell A5, the number 20 / 23 comes up in cell C5. Is it possible with a loop or another type of code? Or will I have to copy this over and over for each row?


Any help is really appreciated. Thanks!


Javascript else if statement error

I have to make a javacript code that satisfy the triangle inequality theorem, which the two smaller sides adds up to be bigger than the largest side. I have to use javascript and use a prompt for users to enter three numbers. I can not ask the user to enter the largest number i have to find it by code. So below is what i got so far, but i keep getting an error at the first else if statement and so i wont run. Any idea whats wrong with my code?



<script type="text/javascript">
<!--


var a = prompt("Enter the first side", "0");
a = Number(a);
var b = prompt("Enter the second side", "0");
b = Number(b);
var c = prompt("Enter the third side", "0");
c = Number(c);

if(a>=b, a>=c){
if (b+c>a) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality.1" );
}
else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality.1" );
}
else if(b>=c, b>=a) {
if (c+a>b) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality.2" );
}
else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality.2" );
}
}
else {
if (a+b>c) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality.3" );
}
else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality.3" );
}
}
}




// -->
</script>

Excel vba If And Then inputting numerical values and outputting non numerical

I am new at this and need some help - sorry if my question is a little unclear.


I want to create an If Then statement using a range of numbers (with one decimal place) as my Range, and for the output to be in non numerical form (a word or code)


This is what I have, when I first tried it, it worked. I saved it but it now stopped working and after clicking on the command button, nothing happens.



Dim score As Double, result As String

If Range("E2") >= 18.6 And Range("E2") <= 21.5 Then
Range("F2") = "2a"

Else
If Range("E2") >= 21.6 And Range("E2") <= 24.5 Then
Range("F2") = "3c"

End If
End If


So If I enter a number between 18.6 and 21.5 in cell E2, I would like the code "2a" to appear in cell F2.


ifelse in data.table agregarte result

I have a question which really need your help:



set.seed(1111)
s<-rep(seq(1,4),5)
a<-runif(20,0.2,0.6)
b<-runif(20,0.4,0.7)
b[6:8]<-NA
c<-runif(20,4,7)
d<-data.table(s,a,b,c)
setkey(d,s)


The data is as following:



s a b c
1: 1 0.3862011 0.4493240 6.793058
2: 1 0.4955267 0.4187441 4.708561
3: 1 0.4185155 0.5916827 6.810053
4: 1 0.5003833 0.5403744 5.948629
5: 1 0.5667312 0.5634135 6.880848
6: 2 0.3651699 0.5263655 5.721908
7: 2 0.5905308 NA 6.863213
8: 2 0.2560464 0.4649180 5.745656
9: 2 0.4533625 0.5077432 5.958526
10: 2 0.4228027 0.4340407 5.115065
11: 3 0.5628013 0.6517352 6.252962
12: 3 0.5519840 NA 4.875669
13: 3 0.2006761 0.6418540 5.452210
14: 3 0.5472671 0.4503713 6.962282
15: 3 0.5601675 0.5195013 6.666593
16: 4 0.2548422 0.6962112 5.535579
17: 4 0.2467137 NA 6.680080
18: 4 0.4995830 0.6793684 6.334579
19: 4 0.2637452 0.4078512 6.076039
20: 4 0.5063548 0.4055017 5.287291


If I do a simple sum, using s as key, it will return a nice table summarize the result:



d[,sum(c),by=s]

s V1
1: 1 31.14115
2: 2 29.40437
3: 3 30.20972
4: 4 29.91357


However, if my data.table command contain ifelse statement, I will not get similar table:



d2<-d[,ifelse(a<b,"NA",sum(c)),by=s]
d2


s V1
1: 1 NA
2: 1 31.1411493057385
3: 1 NA
4: 1 NA
5: 1 31.1411493057385
6: 2 NA
7: 2 NA
8: 2 NA
9: 2 NA
10: 2 NA
11: 3 NA
12: 3 NA
13: 3 NA
14: 3 30.2097161230631
15: 3 30.2097161230631
16: 4 NA
17: 4 NA
18: 4 NA
19: 4 NA
20: 4 29.9135677714366


Is that possible to use the ifelse statement return a result just like the simple sum result table which return the unique non-na value under the each index value?


Thanks a lot!!!!!


Why isn't my if statement working?

I was working on a calculator that can operate in C. Suddenly, an error popped up saying it was expecting an expression. I wonder why the if statement isn't working. Here is the code that I typed in!



#include <stdio.h>

int main(int argc, const char * argv[]) {

int symbol;
int numberOne;
int numberTwo;

printf("+,-,/,*?");
symbol = scanf("%d", &symbol);

if (symbol==*)
{
printf("Please enter first number.");
numberOne = scanf("%d", &numberOne);
printf("%d %d = ?" , numberOne , symbol);
}
return 0;
}


It said that there was an error on the if statement. Please report my error. :D


How to give value of string to another string in matlab

I have a simple question. I want to calculate training heart rate.And I have some values. RHR means that resting heart rate. INTEN means fitnes level and I give values 0.55,0.65,0.8 for low, medium and high fitness level I wrote that code



Gender=input('Please input your gender: ');
Age=input('Please input your age: ');
RHR=input('Please enter your resting heart rate: ');
INTEN=input('Please enter your fitness level(low,medium or high): ');
male=Male;
female=Female;
low=0.55;
medium=0.65;
high=0.8;
if INTEN==0.55
INTENT=0.55;
elseif INTENT==medium
INTENT=0.65;
else
INTENT=0.8;
end
if Gender==Male
THR=((220-Age)-RHR)*INTEN+RHR;
elseif Gender==Female
THR=((206-0.88*Age)-RHR)*INTEN+RHR;
end
disp('The recommended training heart rate is ',num2str(THR))


But it gave error why?


Need help in building a logic in Javascript . Array Logic

Below is the hard coded page of a game Master Mind. The user


I know I need to




  1. use Array to store RBGY and some thing to do with indexOf(array name) I need to define a right answer (like RRBY hard coded for now) I need to check each letter in that Array the user typed and compare it with RRBY.




    1. I need show 2 things as answers visually on page so that users know which


      CLOSE : Right color in the wrong spot EXACT : Right Color in the Right Spot


      For example : 2 close and 1 exact




    2. Also I need the user to play this game only 10 times after that display you lost.




    3. Victory condition is the user gets the right combination RRBY then display Congrats






How do I set all of this up. New to JS. First Goal is to to make it working and then maybe get complex with display (close and exact).


Can some one help me the structure / function so that I can understand the logic and then I can try and write the syntax (I dont know if this makes sense :)


Any help would be appreciated.





window.onload = init;

function init(){
var button = document.getElementById("usrButton");
button.onclick = sayHello;
}

// my attempt at putting this logic
var colors = ["R", "B", "Y", "G"];
var correctAnswer = ["R", "Y", "Y", "G"];
// maybe i thought I need to define what is the right answer in an array first




if () {
// check if all the index in array CorrectAnswer are same as what user typed. maybe using every method
// display success message
}

else
// just display what the user types in on the page with display logic

else if {
// if the user leaves the text box blank . Alert him to enter some values
}


function sayHello(){
var usrTxt = document.getElementById("usrTxt");
var usrName = usrTxt.value;
var display = document.getElementById("displayHere");

var currentOutput = display.innerHTML;

display.innerHTML = currentOutput + usrName '<br>';

var div = document.getElementById("total");
div.appendChild(p);

//display.innerHTML = usrName;

//var p = document.createElement("p");
//p.innerHTML = "looks good";


}



body { color: black; background-color: #d0e4fe; margin-left: 45px; padding: 0;}
h1 { color: black; text-align: center; text-transform: uppercase;}
p { font-family: arial, verdana; font-size: 12px;}



<html>
<head></head>
<body>
<h1> Master Mind</h1>
<p> <b>Game Rules</b>
<ul>
<li>The user gets 10 chances to enter their guess of 4 colors from RGBY. After which you lose</li>
<li>Right Answer is - Correct Color in the Right Spot </li>
<li>Close Answer is - Correct Color but in the wrong Spot</li>

<li></li>
</ul>

Enter your name and click Submit.</p>
<input type="text" id="usrTxt">
<input type="button" onclick="" id="usrButton" value="Submit">
<div id="total">
<p id="displayHere"></p>
</div>
</body>
</html>



Bash: syntax error near unexpected token `else', grep termin using ssh

I'm new to bash, so this could be a simple fix. I'm trying to write a piece of code that allows me to check when jobs have completed on different servers. This is the current block of Code that I've got.



#!/bin/bash

boxes=(dm virgil alpha kolp law be corn zira)
Cyan='\033[0;36m'
NC='\033[0m' # No Color
for box in "${boxes[@]}"; do
echo ""
echo -e "${Cyan}${box}${NC}"
ssh "${box}" "ls -ltr | tail -n 11 | tr -s ' ' | cut -d ' ' -f 6- "
done

echo "------------------------------------------------------------------------------"


This works ok, and gives the following output.



dm
Jan 13 08:47 Model_SNAr_smallbasisset_TCM.chk
Jan 14 09:57 Phoscat_SS_regioazid_subopt.com
Jan 14 09:57 Phoscat_SS_regioazid_subopt.log
Jan 14 09:57 Phoscat_SS_regioazid_subopt.csh
Jan 14 09:57 nohup.out
Feb 4 17:57 Model_SNAr_smallbasisset_wb97xd_sm.com
Feb 4 17:57 Model_SNAr_smallbasisset_b3lyp_sm.com
Feb 4 17:57 Model_SNAr_medbasisset_b3lyp_sm.com
Feb 4 17:58 Model_SNAr_smallbasisset_wb97xd_fp.com
Feb 4 17:58 Model_SNAr_smallbasisset_b3lyp_fp.com
Feb 4 17:58 Model_SNAr_medbasisset_b3lyp_fp.com


As you can see, this shows all files, whereas I would like to narrow it down to just certain file extensions, and effectively "grep termin [filename]" in order to determine whether the job has completed normally. Currently my script will show any files that have been created, but not necessarily completed.


By changing



"ls -ltr | ..."


to



"ls -ltr *.log *.out |"


I can selectively search file extensions, but where I haven't got any files of that extension in a directory, I get the following which looks messy and I'd like to get rid of.



zira
ls: cannot access *.log: No such file or directory
ls: cannot access *.out: No such file or directory


To tidy this up, I tried to use an if..else statement, but got the following error.



#!/bin/bash

DIR="/$HOME"
boxes=(dm virgil alpha kolp law be corn zira)
Cyan='\033[0;36m'
NC='\033[0m' # No Color
for box in "${boxes[@]}"; do
ssh "${box}"
if [ "$(ls -A $DIR)" ]; then
for box in "${boxes[@]}"; do
echo ""
echo -e "${Cyan}${box}${NC}"
ssh "${box}" "ls -ltr *.log *.out | tail -n 11 | tr -s ' ' | cut -d ' ' -f 6-"
else
echo ""
fi

done

echo "------------------------------------------------------------------------------"


line 14: syntax error near unexpected token `else'
line 14: ` else'


Am I missing something easy, and how would I go about incorporating a "grep termin" style command?


Thanks,


Cal


Indenting Visual Studio if tests for readability with auto-formating on paste on

I have a habit of indenting my if tests to make them more readable. I have not seen anyone else do it in quite this way. In general I like the Auto-format on paste option on. Unfortunately if cut and paste:



if ( ( (!CurrentObject.IsInitialized)
&& CurrentAction == Action.Initializing
)
|| ( (!CurrentObject.IsInstalled)
&& CurrentAction == Action.Installing
)
)
{
// Do something.
}


It becomes:



if (((!CurrentObject.IsInitialized)
&& CurrentAction == Action.Initializing
)
||((!CurrentObject.IsInstalled)
&& CurrentAction == Action.Installing
)
)
{
// Do something.
}


Then I need to re-edit it to put the spacing back in. What is odd is that the indenting is not even consistent.


If tests indented in this style allow you to have more complicated if tests that are still readable and understandable. Allowing you to easily see what clause is being ored or anded with which.


I would advocate indented if tests as being more readable and get them added as an optional auto-formating option. For the time being I think I will have to live with auto-formating on paste off.


If people like the idea how does one propose this sort of change to microsoft? I would like to know how many people having seen this think it is a good idea.


For people who think it takes too many lines there is shorter variant that puts all closing brackets on the last line of a clause.



if ( ( (!CurrentObject.IsInitialized)
&& CurrentAction == Action.Initializing)
|| ( (!CurrentObject.IsInstalled)
&& CurrentAction == Action.Installing))
{
// Do something.
}

Java if Stuff in joptionpane

after a long time i came back to java and i try to write a short game about random numbers


The game should look like that:



  1. A Text box appears which asks for the difficulty (Done)

  2. A random number appears according to the difficulty (Stuck)

  3. A Textbox says "You Won, roll Again?" or "You Lose, roll Again" in both cases a loop is needed thats starts at 2. (no clue...)


Im currently stuck at 2. i can generate a random number but after i choose the difficulty nothing happens


here's the code :



package randomnumbergame;

import java.awt.Component;
import javax.swing.JOptionPane;

public class RandomNumberGame {

double n;
double e;
double h;
Component frame = null;
String answer = null;

public static void main(String[] args) {

String[] options = new String[] {"Easy", "Normal", "Hard"};
JOptionPane.showOptionDialog(null, "What Difficulty do you want ?", "Difficulty",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
Object answer = null; }
{
if ("Hard".equals(answer)) {
n = Math.random();
long n3 = Math.round(Math.random()*99999);
System.out.println (n3);
JOptionPane.showMessageDialog(frame, n3 ,"Your randomly generated Number is:" , JOptionPane.PLAIN_MESSAGE) ;

}else if ("Normal".equals(answer)) {
h = Math.random();
long n4 = Math.round(Math.random()*9999);
System.out.println (n4);
JOptionPane.showMessageDialog(frame, n4 ,"Your randomly generated Number is:" , JOptionPane.PLAIN_MESSAGE) ;

}else if ("Easy".equals(answer)) {
e = Math.random();
long e4 = Math.round(Math.random()*999);
System.out.println (e4);
JOptionPane.showMessageDialog(frame, e4 ,"Your randomly generated Number is:" , JOptionPane.PLAIN_MESSAGE) ;
}
}
}


what is wrong with it ? I looked trought several Questions here but i couldn't figure it out.


Use an IF STATEMENT with INSERT IGNORE

I have a voting system, which users can use to vote on posts. Thing is, they can't vote twice on the same post. Which is good. I did that like this:



$query = "INSERT IGNORE INTO vote_id (vote, postid, userid)
VALUES ('1', '{$postid}', '{$userid}')";
$result = mysqli_query($db, $query);
header('Location: index.php');


(The $db is my variable that connects to the database).

They can still click on the vote, even if it doesn't insert into the table.

My problem is:

When it is "IGNORE" they shouldn't be able to click.



My question is:

How do I separate the INSERT and IGNORE, so I can use the IGNORE in an IF statement? Or in any other way, that can change the layout of the page.



Thanks in advance! Really struggling with this one.


Javascript why my if-statement is not working

I'm having trouble getting this if-statement below to properly do what I want it to.


This "Baddie" being mentioned in here is a cartoon which is moving around in a box by pressing the arrowkeys that is 400px width, 300px height.


This is a function that is suppose to prevent him from moving outside this box.



var isBaddieMovable = function(moveLeft, moveTop) {
var movable, newLeft, newTop, max;
console.log("Checking if baddie collided with the content walls");
movable = true;
// Get baddie's new position if moved
newLeft = left + moveLeft*step;
newTop = top + moveTop*step;
console.log("Checking collision at", newLeft, newTop);

// Left wall collide check - check if newLeft outside content
var condition = false;
if(newLeft < 0) {
movable = false;
console.log("Baddie collided with left wall");
}
condition = false;
// Top wall collide check - check if newTop is outside content
if(newTop < 0) {
movable = false;
console.log("Baddie collided with top wall");
}
// Right wall collide check
max = 400;
if(newLeft + baddie.offsetWidth > max) {
movable = false;
console.log("Baddie collided with right wall");
}
// Bottom wall collide check
max = 300;
if(newTop + baddie.offsetHeight > max) {
movable = false;
console.log("Baddie collided with bottom wall");
}

// Return if baddie collided
return movable;
};


I can see in the console that the function is finding out the Baddie collided with the wall, but he's still going through the walls even with the movable = false is set.



Console:
Baddie will step 50 pixels each move
Baddie starts at 0,0
37 was pressed
Checking if baddie collided with the content walls
Checking collision at -50 0
Baddie collided with left wall


Is this enough information to help me out? I'm sorry I dont have the entire site uploaded anywhere.


Edit: As someone mentioned, I have added the function for the movement here:



var moveBaddie = function(moveLeft, moveTop) {

left += moveLeft*step;
top += moveTop*step;

baddie.style.left = left + "px";
baddie.style.top = top + "px";
};

jeudi 26 février 2015

How to make a 'If Then' Loop in vba

I am a beginner in vba. I have a situation in which I would like to say if i=9, k=1 and if i=10, k=2 and if i=11, k=3 and it goes on and on


As i increases by one, k should increase by one too. But how do I say if i=1000, k=992. I cant type each one of the statement until i=1000.


So I was just wondering if there are any loops in which I can create here to make it easy. Any help would be deeply appreciated! Thanks


IF and AND in combination

I have problems with the IF function. I want to combine the AND function with it. What I did was:



If(and((C2:G2)>5,5);"Gehaald";"Niet gehaald")


I know you can do it all manually this way:



And(C2>5,5;D2>5,5...)


Is there any way to write this formula shorter?


c# Ternary operator

I am working on a an application that has no documentation (although the code is quite clear and well-written) and I am trying to write some useful technical documentation for the next guy who comes along after I am in a mental hospital.


In the web-service method, if the call to the web-service returns an error, then the Catch code runs to increment the number of retries for the message and set the MessageStatus to "New" (so that it is retried if less than 5) or "Error" (for unknown errors), but there is one line I am not completely sure of and I need to document this process properly:



catch (Exception ex)
{
int NoRetries = (int)dRow[(int)Common.OutboundSQLFields.Message_Retries];
string messageStatus = (NoRetries < 5) ? Common.MessageStatus(ex) : "Expired";
...


Does this mean that if the NoRetries is greater than 4, then the MessageStatus will be set to Expired, else the method Common.MessageStatus will be called to reset the string MessageStatus based on the value of (ex) ?


So to make it more self-describing, could I rewrite that Ternary operator code as:



string MessageStatus="";
If (NoRetries > 4)
{
MessageStatus = "Expired";
}
else
{
MessageStatus = Common.MessageStatus(ex);
}

kendo if else when null

I would like to have a template that always shows what is in odata table except null values, for example, in this example, I tried to make a condition which will check if UnitOfMeasure is null, if it is, it should display only Quantity value, if it is not, Quantity+UnitOfMeasure. Here is what I tried. Thanks



template: "#if(UnitOfMeasure == null) {#= kendo.toString(Quantity, "n2")#} else{#= kendo.toString(Quantity, "n2")# #=UnitOfMeasure#}#"

PHP PDF file uploader, IF staement cutting out early

I am trying to create a PDF file uploader, however my if statement is cutting out early and else statements are producing syntax errors. Is there way of making this IF to work?


error:



if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error " . $_FILES['file']['error']);
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['file']['tmp_name']);
$ok = false;
switch ($mime) {
case 'image/jpeg':
case 'application/pdf':
$ok = true;
default:
die("Unknown/not permitted file type");
}

else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

if (file_exists("../pdf/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists: ";
echo "<p>Image URL: <strong>" . $preferences->PREF_SHOPURL . "/pdf/" . $_FILES["file"]["name"] . "</strong></p>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../pdf/" . $_FILES["file"]["name"]);
echo "Stored in: " . "pdf/" . $_FILES["file"]["name"];
echo "<p>&nbsp;</p>";
echo "<p>PDF URL: <strong>" . $preferences->PREF_SHOPURL . "/pdf/" . $_FILES["file"]["name"] . "</strong></p>";
}
}

else
{
echo "Invalid file";
}
?>

How do I make things appear after an "if" statement in python?

This is my "game" that is about being a square, picking up the yellow "blips" and avoiding the blue enemies. My problem is that the enemies appear before the if statement, even though they shouldn't. I don't know if blitting is the best way of doing it, but since I am a beginner I do not know, and it's been working well for me so far. I also want to cover up or remove the "ball" but can't find a way to do that, since blitting in an "if" statement does not work and covers it immidiately. If there is any help or tips you can come with I will gladly accept, as well as how to improve and/or cleaning up my code. Thanks in advance!



import sys, pygame
from random import randint

pygame.init()

size = width, height = 800, 600
speed = [2, 2]
green = 0,255,0
black = 1, 1, 1
screen = pygame.display.set_mode((size))
pygame.display.set_caption('Pick up the squares!')
UP='up'
DOWN='down'
LEFT='left'
RIGHT='right'

ballx = 400
bally = 300
ballpos = (ballx, bally)
ball = pygame.image.load("ball.png")
ballrect = ball.get_rect(topleft = (ballx, bally))

endBlipx = 0
endBlipy = 0


blipx = randint(1,800)
blipy = randint(1,600)

blippos = (blipx, blipy)
blip = pygame.image.load("blip.png")
bliprect = blip.get_rect(topleft = (blipx, blipy))


enemy1x = randint(1,800)
enemy1y = randint(1,600)
enemy1pos = (enemy1x, enemy1y)
enemy1 = pygame.image.load("enemy.png")
enemy1rect = blip.get_rect(topleft = (enemy1x, enemy1y))

enemy2x = randint(1,800)
enemy2y = randint(1,600)
enemy2pos = (enemy2x, enemy2y)
enemy2 = pygame.image.load("enemy.png")
enemy2rect = blip.get_rect(topleft = (enemy2x, enemy2y))

enemy1changex = 5
enemy1changey = 5

enemy2changex = 5
enemy2changey = 5


newPosx = randint(1,795)
newPosy = randint(1,595)

background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))



scoreNum = 0


font = pygame.font.Font(None, 36)
text = font.render("{}{}".format("Score: ", scoreNum),8,(250,0,0))
textpos = text.get_rect()
textpos.centerx = background.get_rect().centerx
background.blit(text, textpos)




clock = pygame.time.Clock()

while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()


keys = pygame.key.get_pressed()

if keys[pygame.K_LEFT]:
ballx -= 5
ballrect.x -=5
if keys[pygame.K_RIGHT]:
ballx += 5
ballrect.x += 5
if keys[pygame.K_UP]:
bally -= 5
ballrect.y -= 5
if keys[pygame.K_DOWN]:
bally +=5
ballrect.y += 5

if ballrect.colliderect(bliprect):
blipx = randint(1,795)
blipy = randint(1,595)
bliprect = blip.get_rect(topleft = (blipx, blipy))

scoreNum = int(scoreNum)
scoreNum = scoreNum + 1
scoreNum = str(scoreNum)
text = font.render("{}{}".format("Score: ", scoreNum),8,(250,0,0))
scoreNum = int(scoreNum)


if ballx >= 765:
ballx -= 5
ballrect.x -= 5
if bally <= -5:
bally += 5
ballrect.y += 5
if ballx <=-5:
ballx +=5
ballrect.x +=5
if bally >=565:
bally -=5
ballrect.y -=5

if scoreNum >= 5:
screen.blit(enemy1, (enemy1x, enemy1y))
screen.blit(enemy1, (enemy1rect))

enemy1x += enemy1changex
enemy1y += enemy1changey
enemy1rect.x += enemy1changex
enemy1rect.y += enemy1changey

if enemy1x > 795 or enemy1x < 5:
enemy1changex = enemy1changex * -1
if enemy1y > 595 or enemy1y < 5:
enemy1changey = enemy1changey * -1

if scoreNum >= 6:

screen.blit(enemy2, (enemy2x, enemy2y))
screen.blit(enemy2, (enemy2rect))

enemy2x += enemy2changex
enemy2y += enemy2changey
enemy2rect.x += enemy2changex
enemy2rect.y += enemy2changey

if enemy2x > 795 or enemy2x < 5:
enemy2changex = enemy2changex *-1
if enemy2y > 595 or enemy2y < 5:
enemy2changey = enemy2changey * -1




if ballrect.colliderect(enemy1rect):
screen.fill(black)
pygame.draw.rect(screen, black, (ballrect.x, ballrect.y, 20, 20))
text = font.render("{}".format("You lose!!"), 8, (250,0,0))
scoreNum = 0

if ballrect.colliderect(enemy2rect):
screen.fill(black)
pygame.draw.rect(screen, black, (ballrect.x, ballrect.y, 20, 20))
text = font.render("{}".format("You lose!!"), 8, (250,0,0))
scoreNum = 0


if scoreNum == 6:
text = font.render("{}".format("You win!"), 8, (250,0,0))






screen.fill(black)
screen.blit(ball,(ballrect))
screen.blit(ball, (ballx, bally))
screen.blit(blip,(bliprect))
screen.blit(blip, (blipx, blipy))
screen.blit(enemy1, (enemy1x, enemy1y))
screen.blit(enemy1, (enemy1rect))
screen.blit(enemy2, (enemy2x, enemy2y))
screen.blit(enemy2, (enemy2rect))
screen.blit(text, textpos)
pygame.display.update()
clock.tick(40)

how to handle an empty list, python3

I have a function that creates a list of aminoacids (aaCandidates), but this list can even be empty. If this list is empty I would like to jump the step and continue with the following one.


My code is:



def magicfunction(referenceDistance,referenceAA):

amminoacids = ('A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V')
aaCandidates = list()
for aa in amminoacids:
if distance(aa,referenceAA) == referenceDistance:
aaCandidates.append(aa)
if not aaCandidates:
break

luckyAA = choice(aaCandidates)

return(luckyAA)


I call this function in another file as follow:



for i in range(lenghtPairs):
r1 = randrange(20)
r2 = randrange(20)
coppie.append([aminoacidi[r1], aminoacidi[r2]])

for i in range(lenghtPairs):
dictionary = dict()
frequenze = dict()

if i == 0:
a = randrange(20)
b = randrange(20)
pairs[0] = [aminoacids[a], aminoacids[b]]
else:
c = randrange(20)
pairs[i][0] = aminoacids[c]
distanceNeighbours = distance(pairs[i][0],pairs[i-1][0])
aaChosen = magicfunction(distanceNeighbours,pairs[i-1][1])
pairs[i][1] = aaChosen

print(i + 1)


I tried the condition => if not aaCandidates: break but it didn't work.


Type Mismatch Error IF statement

I am trying to make a 'Sales Page' where the user can enter in details of a sale for each day. I am using a user form for it and i am trying to make it that when you enter the day, if it is incorrect then display a message box and don't run the rest of the function. Anyway, i keep getting the type mismatch error on this part of the code and i don't know why


If salday <> "Monday" _ Or "Tuesday" _ Or "Wednesday" _ Or "Thursday" _ Or "Friday" _ Or "Saturday" _ Or "Sunday" Then MsgBox "Incorrect Day. Please make sure you are using capitals!" Else


If anyone could help that would be great :D


Checking if statement for Array String in android

In my app I want two search between my saved records in SQLite database and in my table I have three fields: [ID] INTEGER NOT NULL PRIMARY KEY ON CONFLICT ABORT AUTOINCREMENT, [text] TEXT, [detail] text.


And from record 1 through 60 I open the data in first activity(ShowText) and from 60 through 120 in second activity(ShowPand).


Now in search class I have a list view for showing result and everything work well but when I click list item I don't know how to move to correct activity.


here my search class:



import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

public class search extends ListActivity {
private database db;
private String[] Name;
private String[] Id;

private EditText edt_searchbox;
private RadioButton rdo_search_name;
private TextView status;
private Button btn_searching;
private RadioButton rdo_search_text;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);

db = new database(this);

edt_searchbox = (EditText) findViewById(R.id.edt_searchbox);
rdo_search_name = (RadioButton) findViewById(R.id.rdo_search_name);
rdo_search_text = (RadioButton) findViewById(R.id.rdo_search_text);
btn_searching = (Button) findViewById(R.id.btn_searching);
status = (TextView) findViewById(R.id.txt_status);
edt_searchbox.setTypeface(MainActivity.font);
status.setTypeface(MainActivity.font);

refresh(edt_searchbox.getText().toString(), "text");
btn_searching.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if (rdo_search_name.isChecked()) {
refresh(edt_searchbox.getText().toString(), "text");

} else if (rdo_search_text.isChecked()) {
refresh(edt_searchbox.getText().toString(), "detail");

}

}
});
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
if(Id[position].equals("2")){
Intent in = new Intent(search.this, ShowText.class);

in.putExtra("name", Name[position]);
in.putExtra("page", Id[position]);
search.this.startActivity(in);
}else{
Intent in = new Intent(search.this, ShowPand.class);

in.putExtra("name", Name[position]);
in.putExtra("page", Id[position]);
search.this.startActivity(in);
}

}

class AA extends ArrayAdapter<String> {
public AA() {
super(search.this, R.layout.raw_seasone, Name);
}

@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater in = getLayoutInflater();
View row = in.inflate(R.layout.raw_seasonforsearch, parent, false);
// ----------------------------------------------------------
TextView name = (TextView) row.findViewById(R.id.name_season);
name.setText(Name[position]);
name.setTypeface(MainActivity.font);
// ----------------------------------------------------------------
return (row);
}
}

private void refresh(String text1, String field) {

db.open();
int s = db.count_search(text1, field);
if (edt_searchbox.getText().toString().equals("")) {
s = 0;
status.setText(" Please write your search word");

} else {
status.setText(" Your search have a " + s + " result ");

}
Name = new String[s];
Id = new String[s];
for (int i = 0; i < s; i++) {
if (field.equals("text")) {
Name[i] = db.search(i, 1, text1, field);

} else {
Name[i] = db.search(i, 2, text1, field);
}
Id[i] = db.search(i, 0, text1, field);
}
setListAdapter(new AA());
db.close();
}
}


In onListItemClick() method how tell that if Id[position]<=60 then open first activity and else open another one?


Checking if statement for Array String in android

In my app I want two search between my saved records in SQLite database and in my table I have three fields: [ID] INTEGER NOT NULL PRIMARY KEY ON CONFLICT ABORT AUTOINCREMENT, [text] TEXT, [detail] text.


And from record 1 through 60 I open the data in first activity(ShowText) and from 60 through 120 in second activity(ShowPand).


Now in search class I have a list view for showing result and everything work well but when I click list item I don't know how to move to correct activity.


here my search class:



import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

public class search extends ListActivity {
private database db;
private String[] Name;
private String[] Id;

private EditText edt_searchbox;
private RadioButton rdo_search_name;
private TextView status;
private Button btn_searching;
private RadioButton rdo_search_text;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);

db = new database(this);

edt_searchbox = (EditText) findViewById(R.id.edt_searchbox);
rdo_search_name = (RadioButton) findViewById(R.id.rdo_search_name);
rdo_search_text = (RadioButton) findViewById(R.id.rdo_search_text);
btn_searching = (Button) findViewById(R.id.btn_searching);
status = (TextView) findViewById(R.id.txt_status);
edt_searchbox.setTypeface(MainActivity.font);
status.setTypeface(MainActivity.font);

refresh(edt_searchbox.getText().toString(), "text");
btn_searching.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if (rdo_search_name.isChecked()) {
refresh(edt_searchbox.getText().toString(), "text");

} else if (rdo_search_text.isChecked()) {
refresh(edt_searchbox.getText().toString(), "detail");

}

}
});
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
if(Id[position].equals("2")){
Intent in = new Intent(search.this, ShowText.class);

in.putExtra("name", Name[position]);
in.putExtra("page", Id[position]);
search.this.startActivity(in);
}else{
Intent in = new Intent(search.this, ShowPand.class);

in.putExtra("name", Name[position]);
in.putExtra("page", Id[position]);
search.this.startActivity(in);
}

}

class AA extends ArrayAdapter<String> {
public AA() {
super(search.this, R.layout.raw_seasone, Name);
}

@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater in = getLayoutInflater();
View row = in.inflate(R.layout.raw_seasonforsearch, parent, false);
// ----------------------------------------------------------
TextView name = (TextView) row.findViewById(R.id.name_season);
name.setText(Name[position]);
name.setTypeface(MainActivity.font);
// ----------------------------------------------------------------
return (row);
}
}

private void refresh(String text1, String field) {

db.open();
int s = db.count_search(text1, field);
if (edt_searchbox.getText().toString().equals("")) {
s = 0;
status.setText(" Please write your search word");

} else {
status.setText(" Your search have a " + s + " result ");

}
Name = new String[s];
Id = new String[s];
for (int i = 0; i < s; i++) {
if (field.equals("text")) {
Name[i] = db.search(i, 1, text1, field);

} else {
Name[i] = db.search(i, 2, text1, field);
}
Id[i] = db.search(i, 0, text1, field);
}
setListAdapter(new AA());
db.close();
}
}


In onListItemClick() method how tell that if Id[position]<=60 then open first activity and else open another one?


mercredi 25 février 2015

the 'if...else' is not checking any other conditions, directly skipping to last 'else' statement

i,m calling a JavaScript function to change an image by using if..else statement to change its source. but it directly skips to last else statement, so the image only keeps swapping between first & last image


JavaScript function:



function myfunction2() {
var image = document.getElementById("image");
//iterartion 1
if (image.src == "img1.jpg") {
image.src = "img2.jpg";
} else if (image.src == "img2.jpg") {
image.src = "img3.jpg";
} else if (image.src == "img3.jpg") {
image.src = "img4.jpg";
} else if (image.src == "img4.jpg") {
image.src = "img5.jpg";
} else if (image.src == "img5.jpg") {
image.src = "img1.jpg";
} else {
image.src = "img2.jpg";
}
}


html code:



<div id="image-slider">
<img src="img1.jpg" id="image">

<div id="left-holder">
<img onclick="myfunction2()" src="arrow-left.png" height="49px" width="49px" class="left"/>
</div>

<div id="right-holder">
<img onclick="myfunction2()" src="arrow-right.png" height="49px" width="49px" class="right"/>
</div>
</div>


what am i doin wrong here? plz help.


Python too short if condition

I want this condition to be short if it's possible, I don't want every time or



if not wall.twitter_access_token or not wall.twitter_access_token_secret or not wall.auth_user:
raise Exception("Cannot open without verify with twitter account")

Can I use an if statement inside of a switch in php?

Heres what I want to do:


I have a variable named $user, where the information is being POSTED from a form. If the form data is empty I want to do one thing, if the form data is just a comma or symbol I want to do another thing, and if the form data is correct I want to do a third thing. This is how I have it set up, will this work? If not, what can I do to make it work?



switch($user){
case 1:
if(empty($user)){
echo "<h2>"."<strong>"."You entered NOTHING, PLEASE Re-Enter"."</strong>"."</h2>";
}
case 2:
if($user == ",") {
echo "<h2>"."<strong>"."You did not enter any valid names/abbreviations to search, PLEASE Re-Enter"."</strong>"."</h2>";
}
default:


print "==========================================="."<br />";
tester($company, $user);


print "==========================================="."<br />";
print "========The following were NOT found====="."<br />";
notFound($company, $user);

print "==========================================="."<br />";

}


Right now it is automatically going to default. It runs, but I want integrate the two qualifiers, how would I go about doing that?


if statements in while loops

I am new to programming, and I am trying to practice various functions with a simple "Pick a Number" application. However I have ran into a problem.



Random rnd = new Random();
int deNumero = rnd.Next(1,100001);
while (true)
{
Console.WriteLine("Pick a number 1 - 100000");
string input = Console.ReadLine();
int numero = Int32.Parse(input);
if(numero < deNumero)
{
Console.WriteLine("Lower");
}
else if(numero > deNumero)
{
Console.WriteLine("Higher");
}
else if(numero == deNumero)
{
Console.WriteLine("Well done!");
Console.ReadKey();
}
else
{
Console.WriteLine("What?");
}
}


Let's say I pick a number that is greater than deNumero and it prints "Lower". Where I am seeing a problem is when I pick the number 1, it will print "Lower" again. it keeps going to the same if statement even when it shouldn't. What am I doing wrong?


Javascript date object day subtraction not working with comparison if statement

I can't get the "&& partyDate >= pastParty)" section of the comparison statement to work. I think the problem lies within the "pastParty" variable, but I'm not sure what to do. It should be that if the partyDate is only 30 days or less past the curDate the third "if" will trigger. So if the partyDate is (2015, 2, 14) and the curDate is (2015, 2, 15) the party is over by one day.



<body>
<p id="theDate"></p><br>
<p id="theParty"></p><br>
<p id="quote"></p>
</body>

<script>
var curDate = new Date();
var partyDate = new Date();
curDate.setFullYear(2015, 2, 15);
partyDate.setFullYear(2015, 2, 14);

document.getElementById("theDate").innerHTML = "The current date is " + curDate;
document.getElementById("theParty").innerHTML = "The party is " + partyDate;

function getQuote() {
var futureParty = curDate.setDate(curDate.getDate() + 30);
var pastParty = curDate.setDate(curDate.getDate() - 30);
var daysTill = (partyDate - curDate) / (1000 * 60 * 60 * 24);
var daysPast = (curDate - partyDate) / (1000 * 60 * 60 * 24);
daysTill = Math.round(daysTill);
daysPast = Math.round(daysPast);

if (partyDate <= futureParty && partyDate > curDate) {
document.getElementById("quote").innerHTML = "The party will be here in " + daysTill + " days, let's pre-party!";
} else if (partyDate > futureParty) {
document.getElementById("quote").innerHTML = "The party is more than " + daysTill + " days from now!";
} else if (partyDate < curDate && partyDate >= pastParty) {
document.getElementById("quote").innerHTML = "The party is over for the year, but you only missed it by " + daysPast + " days.";
} else if (partyDate < pastParty) {
document.getElementById("quote").innerHTML = "The party was more than " + daysPast + " days ago!";
}
}
getQuote();

C++ if/else statements not properly outputting

currently, I am having an issue with this if/else statement. this is the source here:



#include "stdafx.h"
#include "iostream>*
#include iomanip>* //had to remove the < for the #include libraries to show

using namespace std;

int main()
{
string firstname, secondname;
const int A_SCORE = 90;
const int B_SCORE = 80;
const int C_SCORE = 70;
const int D_SCORE = 60;

int testscore1;
int testscore2;
int testscore3;
int testscore4;
int testscore5;
int testscore6;
int testscore7;
int testscore8;
int testscore9;
int testscore10;

cout << "Enter your 10 scores and I will average\n"
<< "the total score, and assign letter grades" << endl;

cin >> testscore1;
cin.ignore();
cin >> testscore2;
cin.ignore();
cin >> testscore3;
cin.ignore();
cin >> testscore4;
cin.ignore();
cin >> testscore5;
cin.ignore();
cin >> testscore6;
cin.ignore();
cin >> testscore7;
cin.ignore();
cin >> testscore8;
cin.ignore();
cin >> testscore9;
cin.ignore();
cin >> testscore10;
cin.ignore();

int sum = testscore1 + testscore2 + testscore3 + testscore4 + testscore5 + testscore6 + testscore7 + testscore8 + testscore9 + testscore10;
int average = sum / 10;

if (average == 90);
{
cout << "your average is an A.";
}

else if (average == 80);
{
cout << "you have an average of a B.";
}

else if (average == 70);
{
cout << "you have an average of a C.";
}

else (average == 60);
{
cout << "your average is a D.":
}

system("pause");

return 0;
}


what the goal of this homework assignment is, is to input 10 numerical grades and have an average print out to screen with a letter grade based on average of the 10 grades. I no matter what I input, I always get 'your grade is an A. I have went over my notes ad well as looking to goodle/StackOverflow for what could be wrong. I also get compile errors too, which I cannot figure out. If someone could give me any ideas on what could be causing the issue, I would greatly appreciate it!


Computer Guessing Game Java

How would I go about creating a guessing game, where the computer guesses and I tell it to go higher or lower/ I would like to do this using simply if and else statements.


PHP if/else to change background color based on input

I am trying to make a simple php page where you input a number and submit it and if it is even it makes the background blue and if odd it makes it red.


Breaking out of nested if

I have a bit of code that contains nested if statements:



if(numberOfNeighbors == 1){

//go through comparison again, add Pixel(i,j) to current linked list -> complist[numberOfComponents]
// break out of large check ??

if(ji.getPixelColor(i, j) == (ji.getPixelColor(i-1,j-1))){ //compare to top left
complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
}
if(ji.getPixelColor(i, j) == (ji.getPixelColor(i,j-1))){ // compare to top
complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
}

if(ji.getPixelColor(i, j) == (ji.getPixelColor(i+1,j-1))){ // compare to top right
complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
}
if(ji.getPixelColor(i, j) == (ji.getPixelColor(i-1,j))){ // compare to left
complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
}
} // end of if(numberOfNeighbors == 1)


Basically what I would like to do, however inefficient this may be, is compare a something 4 times, but if it turns out it is a match, break out of the set of the 4 nested if statements, as well as the outer if statement.


Will this work? or will it just break out of the nested if its currently at and continue to the next until its gone through all 4?


Java Break a while loop with enter button

the thing is that I'm making a JFrame with text shown almost lik an visual novel. And when the text in the JLabel is done, a blinking arrow symbol ">" is shown at the bottom. I get this far, but how to I make the 'while' loop break if I press the enter key. Allmost all answers on the web was about JTextField and Console...



public static void nextSymbol(boolean blink) {
ImageIcon nextIcon = null;
boolean blinked = false;
if(blink) {
nextIcon = new ImageIcon("res/image/next.gif");
while(blink){
if (/* When ENTER is pressed */){
System.out.println("Disabled");
blink = false;
}
pause(0.01);
}
blinked = true;
}
if(!blink && blinked)
vnGame.nextSymbolIcon.setIcon(null);
else
;
blinked = false;
}

Multiple OR conditions in Java

Why doesn't this current multiple conditional if-statement work to create a new string without the vowels?



public class Disemvowel {
public static void main(String[] args) {
System.out.println("Please enter a word: ");
Scanner stdin = new Scanner(System.in);
String word = stdin.next();
int wordLength = word.length();
String disemvoweledWord = "";
for (int i=0;i<=(wordLength-1);i++){
char currentLetter = word.charAt(i);
System.out.println(currentLetter);
if (currentLetter!='a' || currentLetter!='e' || currentLetter!='i' || currentLetter!='o' || currentLetter!='u'){
disemvoweledWord += currentLetter;
}
}
System.out.println(disemvoweledWord);
}
}

PHP - If/Else... statement - Syntax Differences

PHP noob here. A company I do work for has an if/else statement set up like this:



{if product_type != ""} {product_type} {if:else}No Product Type{/if}


Other research I do though provides a format such as the following:



<?php if ($bodyID==='home') { ?>
<h1>I am home!</h1>
<?php } else { ?>
<p>I'm not home!</p>
<?php } ?>


Is there a specific reason for the differences in syntax, or is that just how the previous developer wrote it?


how to append a FOR loop value into a list

Hello I am trying to append a value into a list and although there are various examples of this on here this is different I am using a FOR loop to go through all of the values into a list and if the right name is found in "each" I want to append "each" into a new list. Here is an example



for each in lines:
if names in each:
print(names)
print(each)
if len(newnames)<=3:
newnames.append((each))

elif len(newnames)>3:
newnames = newnames[:2]
print(newnames)


lines looks like this


['alex|7', 'jake|10', 'jake|2', 'jake|5', 'josh|3', 'josh|5', 'josh|7', 'megan|6', 'megan|8', 'megan|9']


Names is just a list with only one copy of each of these names. Hope this is enough information for you to be able to work out an answer because it has me completely stumped.


Cheers.


Using Index in If statement for SlecetedIndexChanged Event VB.NET

I have a dropdown list with 4 values. I'm trying to add an If statement in the event that a value is selected from the dropdown list. Each value in the dropdown list enables another dropdown list later on in the form. I have no syntax errors when I run the code, but it still doesn't work. No mater what value I select the rest of the form stays disabled.


Code below:



Protected Sub FunctionPerformedDD_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles FunctionPerformedDD.SelectedIndexChanged

If (FunctionPerformedDD.SelectedIndex.Equals(0)) Then

ElseIf (FunctionPerformedDD.SelectedIndex.Equals(1)) Then

ReportDD.Enabled = True

ElseIf (FunctionPerformedDD.SelectedIndex.Equals(2)) Then

FormDD.Enabled = True

Else
FormDD.Enabled = True

End If

End Sub

Is there an easier way to do this if statement?

I'm working on a java program that takes grades inputted gives the total number inputted and the average however I'm having trouble figuring out how to do the highest grade entered currently I"m using a ton of nested else if statements, but there has to be an easy way to do this rather than typing 100 else if statements heres my code. I put a comment where the else if statements begin that determine the highest grade



//Jonathan Towell
//This program will take grade inputs and then display the amount of A's B's C's D's and F's
import javax.swing.JOptionPane;


public class Grades
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "Welcome to Jonathan's Gradebook");
int A = 0, B = 0, C = 0, D = 0, F = 0;
int totalGrades = 0, grade = 0, averageGrade = 0, highestGrade = 0;
while (grade >= 0)
{
grade = Integer.parseInt(JOptionPane.showInputDialog("Enter one grade followed by the enter key\n when finished enter -1"));
if (grade <= 100 && grade >= 90)
{
A = A + 1;
totalGrades = totalGrades + 1;
averageGrade = averageGrade + grade;
if (grade == 100) // Determines highest grade
{
highestGrade = 100;
}
else if (grade == 99)
{
highestGrade = 99;
}
else if (grade == 98)
{
highestGrade = 98;
}
else if (grade == 97)
{
highestGrade = 97;
}
else if (grade == 96)
{
highestGrade = 96;
}
else if (grade == 95)
{
highestGrade = 95;
}
else if (grade == 94);
{
highestGrade = 94;
}
}

else if (grade > 100)
{
JOptionPane.showMessageDialog(null, "No extra credit for this assignment\n please enter a value less than 100");
}
else if (grade <= 89 && grade >= 80)
{
B = B + 1;
totalGrades = totalGrades + 1;
averageGrade = averageGrade + grade;
}
else if (grade <= 79 && grade >= 70)
{
C = C + 1;
totalGrades = totalGrades + 1;
averageGrade = averageGrade + grade;
}
else if (grade <= 69 && grade >= 60)
{
D = D + 1;
totalGrades = totalGrades + 1;
averageGrade = averageGrade + grade;
}
else if (grade <= 59 && grade >= 0)
{
F = F + 1;
totalGrades = totalGrades + 1;
averageGrade = averageGrade + grade;
}
}
averageGrade = (averageGrade / totalGrades);
JOptionPane.showMessageDialog(null, "Total number of grades entered was " + totalGrades + "\n The average grade was: " + averageGrade + " percent." + "\nA's: " + A + "\nB's: " + B + "\nC's: " + C + "\nD's: " + D + "\nF's: " + F + "\nThe highest grade earned was: " + highestGrade + " percent.");
System.exit(0);
}


}

Compare text between cell pairs and conditionally write to other cells

I have an Excel sheet as follows:



A B C D A1 B1 C1
1 Edd Eddie Edd Edd
2 Tom Hill Hill Tom
3 Gilly Trom Hill Hill
4 Abd Chikku Apple Chikku
5 Rear Back Back Back


I want to compare D1 with A, B, C and write the results as 10 in A1, B1, C1 respectively.


I tried =IF(NOT(E20=H20),"OK","NOT") but it didn't work.


Expected Result Table



A B C D A1 B1 C1
1 Edd Eddie Edd Edd 10 0 10
2 Tom Hill Hill Tom 10 0 0
3 Gilly Trom Hill Hill 0 0 10
4 Abd Chikku Apple Chikku 0 10 0
5 Rear Back Back Back 0 10 10

If-else clause in Python Statement

I am trying to check the output of few functions and if there is no error I move to next function. So I have added a while loop and few if statements to handle the errors:



success = True
while success:
err, msg = function1()
if not err:
err, msg = function2()
if not err:
err, msg = function3()
if not err:
err, msg = function4()
else:
print msg
success = False
else:
print "function2 fails"
sucess = False
else:
print "function1 fails"
success = False


Is it a better way to avoid if,else , how can I redesign the code for this purpose?


Array count logic error

I am trying to take my array char[][] mazeValue (which has a boarder of X's around my actual values I am comparing) and compare each element inside that array to the element to the left,right,top,bottom, and diagonals to see if there are two O's in a row, and if so I add one to the openfactor. I have walked through my logic all morning, I do not see where I'm going wrong. An extra set of eyes always helps!


Output:



TOTAL OPENESS: 0

cout: 1

cout: 1

cout: 1

cout: 2

cout: 2

cout: 2

TOTAL OPENESS: 2

cout: 2

TOTAL OPENESS: 2

cout: 2

TOTAL OPENESS: 2




public static void openfactor(char[][] mazeValue, int n)
{
int count=0;
int totalOpeness=0;

for(int i = 1; i<mazeValue.length-1; i++){
for(int j=1;j<mazeValue[i].length-1;j++){

if(mazeValue[i][j]=='X'){
System.out.println("cout: "+count);
}

else if(mazeValue[i][j-1]=='O'){
count++;
System.out.println("cout: "+count);
if(mazeValue[i-1][j-1]=='O')
count++;
System.out.println("cout: "+count);
if(mazeValue[i-1][j]=='O')
count++;
System.out.println("cout: "+count);
if(mazeValue[i][j+1]=='O')
count++;
System.out.println("cout: "+count);
if(mazeValue[i+1][j+1]=='O')
count++;
if(mazeValue[i+1][j]=='O')
count++;
System.out.println("cout: "+count);
if(mazeValue[i+1][j-1]=='O')
count++;
System.out.println("cout: "+count);

totalOpeness = totalOpeness +count;

}
System.out.println("TOTAL OPENESS: "+totalOpeness);
}
}
}
public static void printMaze(char mazeValue[][]) {
System.out.println("MAZE");
for (int i = 1; i < mazeValue.length; i++) {
for (int j = 1; j < mazeValue[i].length; j++) {
System.out.printf("%5c", mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void main(String[] args) {
// TODO code application logic here
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n + 1][n + 1];
System.out.println("ENTER A PATH: ");
for (int i = 0; i < mazeValue.length; i++) {
for (int j = 0; j < mazeValue[i].length; j++) {
if (i == 0 || j == 0 || i == n + 1 || j == n + 1)
mazeValue[i][j] = 'X';
else {
mazeValue[i][j] = kbd.next().charAt(0);
}
}
}
printMaze(mazeValue);
openfactor(mazeValue, n);
}

If Statement Contains Only "True"

I am converting a vb6 app into c# and I've come across something I don't quite understand. I've never seen an if statement structure where the expression being evaluated is literally "true" or "false".



private bool InitializeForProgramming() //OK
{
if (J1939.getReplyStatus() == modJ1939.dmOpFailed) //or OpComplete (dmBusy auto cycles)
{
//check the Pointer value to see if engineRunning, or already in Mode
if (true) //let it proceed *** ??
{
//nothing to do
}
else
{
lblCommun.Text = "ProgramMode Failed!";
lblCommun.ForeColor = Color.Red;

//could report more detailed reasons! (engineRunning, etc.)
return true; //FAILED!
}

}


What is being evaluated here with the expression if(true)? If what is true?


Here is the original vb6 code:



Private Function InitializeForProgramming() As Boolean 'OK
If getReplyStatus = dmOpFailed Then 'or OpComplete (dmBusy auto cycles)
'check the Pointer value to see if engineRunning, or already in Mode
If (True) Then 'let it proceed *** ??
'nothing to do
Else
txtCommun.Text = "ProgramMode Failed!"
txtCommun.ForeColor = vbRed

'could report more detailed reasons! (engineRunning, etc.)
InitializeForProgramming = True 'FAILED!
Exit Function
End If
End If


Please let me know if you need me to include anything else to help me get an answer.


Using IF with curly brackets within IF without

I have some code where i'm trying to use the different ifs within each other, but i ran into a problem.. I've made this testcode that will show the issue:



<?php
$test = 'lol';
if ($test == 'wat') :
if (!empty($_GET['wat'])) {
echo 'well';
}
elseif ($test == 'lol') :
echo 'loool';
endif;
die();
?>


This will return this error:


Parse error: syntax error, unexpected ':' in /var/www/http://ift.tt/1DpmD3Q on line 7


But that's only after i'm adding the if (!empty($_GET['wat'])) { }


The question is, am i doing something wrong, or isn't it possible to use a if with curly brackets within one without ?


R: which apply function for conditioned iteration?

I'm new to R and I'm wondering which the fastest and most elegant way to do the iteration I'm going to describe. I have a big dataframe formatted like this:



date_time value1 value2
01-02-1986 00:00 100.120 200.150
01-02-1986 00:01 100.125 201.120
...
01-02-1986 23:59 100.950 190.130
02-02-1986 00:00 103.110 108.200
...


so there are one date and two numeric columns and the rows go on minute by minute.


For each day I need to take df$value1 at given times (say 10:00, 11:00, 15:00), for each pass ceil it to its first decimal, find out the highest value above this in the next Y minutes and put it in a matrix so that I will end up with something like:



<dd-mm-yy> <highest at time 1> <highest at time 2> <highest at time 3>
...
<dd-mm-yy> <highest at time 1> <highest at time 2> <highest at time 3>


I have a vector of the HH:MM I need and a subset of df that contains only the pertinent hours (10:00 to 10:59, 11:00 to 11:59 and 15:00 to 15:59) but now I'm stuck on the iteration.


Is there a way to do this without a for/if cycle rolling the whole array?


Thank you for your help.


PHP 'if" statement not working

I am trying to make a register-login system, and I'm trying to make the registraton succes code, but the PHP code is not working, It shows the "else" only.



<HTML>
<BODY>
<?php
if (isset($_POST["user1"]) && isset($_POST["fullname"]) && isset($_POST["pass1"])) {
if (strlen($_POST["user1"]) != 8) {
echo 'A Felhasználónévnek 8 karakternek kell lennie!';
}
if ((str_word_count($_POST["fullname"])) != 2) {
echo 'A nevének 2 szóból kell állnia!';
}
if (strlen($_POST["pass1"]) != 6) {
echo'A Jelszónak legalább 6 karakterből kell állnia!';
}
if (isset($_POST["select"]) != true) {
echo 'Kérem, válassza ki, hogy diák, vagy tanár felhasználó-e!';
}
if ($_POST["kod"] == "DUSZA") {
}
else { ?>
<h1>Sikeres Regisztráció! A Főmenübe való belépéshez kattintson a gombra!</h1>
<form action="index.php" method="post">
<input type="submit" value="Kattints ide!" width="300" height="300">
</form>
<?php
session_start();

$user2 = $_POST["user1"];
$pass2 = $_POST["pass1"];
$diaktanar = $_POST["select"];
echo $diaktanar;
}
}
?>
</BODY>