mardi 31 mars 2015

If statement omits a condition

So I am trying to create a program in C that takes in any date and returns the zodiac sign.I have a function that is supposed to validate if the date is possible (day >0,month>0, if month ==x ,day <31 etc ) Thing is that on the part where it is supposed to validate the month and determine if it is a 30 month or a 31 month it only accepts one part of the conditions making it either a definite 30 day for all months or a 31 day for all months. the function name is fnValidacion()



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

/*
Programa : Signo Zodiaco.
Autor : Samir Fersobe 1063021
Fecha : Marzo 28, 2015
*/
const char *signo[12] = {"Aries","Tauro","Geminis","Cancer","Leo","Virgo","Libra","Escorpio",
"Sagitario","Capricornio","Acuario","Piscis"};//Arreglo de Signos Zodiacales


int Ano,Mes,Dia ;//Variables de Ano , Mes y Dia.
int aprovacion = 0;//Determina si la funcion sigue o no.
int bisiesto = 1 ;//determina si el año es bisiesto.
int type ;//determina la estacion.
//Funciones
void fnFecha() ;//Consigue la fecha
void fnBisiesto() ;//Define si el año es bisiesto.
void fnValidacion();//Determina si la fecha es valida.
void fnSigno() ;//Determina el signo zodiacal.
void fnDevuelta() ;//Devuelve la respuesta.
int main(int argc, char** argv)
{
fnFecha();
fnBisiesto();
fnValidacion();
fnSigno();
fnDevuelta();

}
void fnDevuelta()
{/*determinar si la funcion sigue o no, y devuelve el resultado al usuario */
switch (aprovacion){
case 1:
printf("El Signo Zodiacal es %s",signo[type]);
break;
default:
printf("\n Intente de nuevo con otra fecha.");
break;
}
}
void fnSigno()
{/*Determina el signo zodiacal*/
switch(Mes){
case 12:
if (Dia < 22)
type = 8;
else
type = 9;
break;
case 1:
if (Dia < 20)
type = 9;
else
type = 10;
break;
case 2:
if (Dia < 18)
type = 10;
else
type = 11;
break;
case 3:
if (Dia < 20)
type = 11;
else
type = 0;
break;
case 4:
if (Dia < 20)
type = 0;
else
type = 1;
break;
case 5:
if (Dia < 21)
type = 1;
else
type = 2;
break;

case 6:
if (Dia < 21)
type = 2;
else
type = 3;
break;
case 7:
if (Dia < 23)
type = 3;
else
type = 4;
break;
case 8:
if (Dia < 28)
type = 4;
else
type = 5;
break;
case 9:
if (Dia < 23)
type = 5;
else
type = 6;
break;
case 10:
if (Dia < 23)
type = 6;
else
type = 7;
break;
case 11:
if (Dia < 22)
type = 7;
else
type = 8;
break;

}
}
void fnBisiesto()
{/*determina si el ano es bisiesto */
if ((Ano%4 != 0) || ((Ano%100 == 0) && (Ano%400 != 0)))
bisiesto = 0;
}
void fnValidacion()
{/*Esta parte determina si la fecha es valida*/
if (
(Ano < 0) || (Dia <0) || (Mes < 1) || (Mes > 12) ||//Ano,Dia,Mes No negativo.Mes entre 1 y 12.
(Dia > 31) || ((Mes == 4,6,9,11) && (Dia > 30)) ||//Dia no mayor que 31.Si mes es de 30, Dia no mayor que 30.
((bisiesto == 0) && (Mes == 2) && (Dia > 28)) ||//Si no es bisiesto febrero no mayor que 28.
((bisiesto == 1) && (Mes == 2) && (Dia > 29)) //Si es bisiesto febrero no mayor que 29.
)
printf("Esta fecha no es Valida."); //Explica al usuario que fecha no es valida.
else
return aprovacion = 1;
}
void fnFecha()
{/*Adquiere la fecha del usuario */
printf("Inserte el Ano: ");
scanf("%d", &Ano);
printf("Inserte el Mes: ");
scanf("%d", &Mes);
printf("Inserte el Dia: ");
scanf("%d", &Dia);
return ;
}

Any idea to exit FOR and print a message


int liContador1, liContador2, liElse = 0;

for (liContador1 = 1; liContador1 <= liNumeroB; liContador1++)
{
for (liContador2 = liContador1 + 1; liContador2 <= liNumeroB; liContador2++)
{
if (NumerosAmigos(liContador1, liContador2))
printf("\n%d, %d", liContador1, liContador2);

else
liElse++; **or what can i do?**
}
}

if (liElse != 0)
printf("\nThe numbers are not friends.\n");


I'm making a program to search the previous amicable numbers to a given value. The program prints the pair of numbers found but need to display a message if no pair of amicable numbers.


The problem is that I can not think on way to do it. I tried with BREAK, continiue, ACCOUNTANTS ..


This is what i was trying:



else
liElse++;


Anyone have any ideas on how I can do to solve this ?.


Greetings and thank you all for helping !.


Can if statements be broken half way through?

I was just wondering if an 'if' statement that is halfway through running will stop running if the conditions it has to meet are no longer met. It is hard to explain with words, here is an example:





boolean flag = true;

if(flag){

//Some code execution here (code execution #1)

flag = false;

//Some more code execution here (code execution #2)


}



Will the "code execution #2" run in this case? Or will the the rest of the if statement be skipped when flag is set to false?


Unexpected token else, not a semicolon after if statement

Trying to write a rock paper scissors game, using codecademy to learn. I've seen a lot of people talking about this error and it being related to using a semicolon after an if statement but I don't know if I'm completely missing something or it's something different. Here's the code, it's a little weird to understand (and least to me), but hopefully you'll see what I didn't



var compare = function(choice1, choice2) {
if(choice1 === choice2) {
return "The result is a tie!";
}
else if(choice1 === "rock") {
if(choice2 === "scissors") {
return "rock wins";
}
else {
return "paper wins";
}
else if(choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
}
else {
return "scissors wins";
}
}
};
}

c# loop assignment for my programming class

i have the following question for one of my assignments for my programming class and was wondering if somebody could help and explain the answer for me. We just started with loops and the book for the class isnt too helpful... the question is:


Study the following block of code carefully. When you submit your lab, add a comment to your submission that answers the following questions about this code:



for (int j = 0; j < 3; j++)
{
for (int i = 0; i < 3; i++)
{
if ( block [i] > block [i+1])
swap (ref block [i], ref block [i + 1]);
}
}


(1) When the code above is executed, how many times is this statement executed?



if ( block [i] > block [i+1])

Java Nested If Help (The Logic is seemingly correct but always outputs the same thing)

I am trying to use nested if statements in order to determine the value of a variable and with this code, the correct results are not occurring. Please can someone help? I am using an array to hold values that are being compared to the input (using this in order to show "knowledge" of java). Then, I am calling the function testFlower() to initialize the logic. I am not able to identify where in my logic I went wrong. Every time anything is inputted, the result that is printed out by the print line is always "Roses". This returned String should change when different flower names are typed in but this does not occur. Does anybody have any ideas on the issue in the code?



import java.util.Scanner;

public class A {

public final double TAX = 1.127;
public final double s_basket = 10, m_basket = 20, l_basket = 30, s_elephant = 15, l_elephant = 30,
s_seal = 15, l_seal = 30, s_bear = 15, l_bear = 30, s_penguin = 15, l_penguin = 30,
mChocolate = 15, wChocolate = 20, dChocolate = 30;

public String flowers[] = {"ROSE", "TULIP", "DAISY", "DAFFODIL", "SUNFLOWER", "ORCHID"};

public Scanner s = new Scanner(System.in);

public String flowerType;


public void testFlower() {
if (!(flowerType.equals(flowers[1]))) {
if (!(flowerType.equals(flowers[2]))) {
if (!(flowerType.equals(flowers[3]))) {
if (!(flowerType.equals(flowers[4]))) {
if (!(flowerType.equals(flowers[5]))) {
flowerType = "Roses";
System.out.println(flowerType);
} else {
flowerType = "Orchids";
System.out.println(flowerType);
}
} else {
flowerType = "Sunflowers";
System.out.println(flowerType);
}
} else {
flowerType = "Daffodils";
System.out.println(flowerType);
}
} else {
flowerType = "Daises";
System.out.println(flowerType);
}
} else {
flowerType = "Tulips";
System.out.println(flowerType);
}
}

public static void main(String[] args) {
A a = new A();

System.out.println("Hello! Welcome to my flower shop! What type of flowers do you want? (rose, tulip, daisy, daffodil, sunflower, orchid)");
a.flowerType = a.s.nextLine();
a.flowerType.toUpperCase();

a.testFlower();

}
}

Pass table variable to SELECT function

I have a getData() function, and a database with two tables: employers and members. I would like to pass a variable containing the table name, so inside an "if" I could execute the appropriate SELECT statement. My problem I believe that after the "if" the $stmt->bind_param(); doesn't know which $stmt to bind the take. Any ideas on how I could achieve this?


Thanks



public function getData($table)
{
if ($table == "employers")
{
$stmt = $this->link->prepare("SELECT * FROM employers ");
}
else
{
$stmt = $this->link->prepare("SELECT * FROM members ");
}

$stmt->bind_param();
if ($stmt->execute())
{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$row = array_map('stripslashes', $row);
$dataArray[] = $row;
}
}

return $dataArray;
}

IF Condition on Assembly not working

Hi guy's I have this code, on assembly using the assembler FASM (FlatAssembler)



;REQUEST THE VALUE (1 OR 2)
mov ah, 3Fh
mov bx, 0
mov cx, 1
mov dx, valor
int 21h

;THE NOT WORKING IF
cmp [size], '2'
jmp small
cmp [size], '1'
jmp e

;ONE OF THE LABELS TO WHERE THE IF MUST JUMP
small:
mov cx, 10
mov dx, 9
.....


;OTHER LABEL
e:
mov ah, 07h
int 21h


The program does not jump to the labels already tryed the cmp [size], 2 and subtracted 48 to get the decimal value but no luck


Any help?


IF AND SharePoint Calculated Field

I have been researching this and I have found several different iterations of the formula, but I just can't get mine to work. I am trying to create an if/and formula in a calculated field. I am trying to show data based on three criteria.



  1. If the create date is greater than month 2 and less than month 8 then "OCTOBER 1"

  2. If the account change type is "Immediate: Error or Business Case" then MONTH([CreateDate])+1 and 1.

  3. Otherwise "MARCH 1"


This is the formula I have: =IF(AND([Created]>2,[Created]<8),”OCTOBER 1",IF([Account Change Type]="Immediate: Error or Business Case"),”ASAP”,”MARCH 1”))


These are the forums I have looked at and still can't get it:


Stack Overflow


Social TechNet


StackExchange


How to use VBA to execute a macro based on an IF statement?

Completely new to VBA and almost completely new to macros, but I think it's the only way to do what I'm trying to do.


I want to run a macro (all it will do is delete specific cells within the same row and I've turned on relative reference so that I can apply the macro to all rows, if there's the appropriate "X") based on whether there is an X in a certain cell.


Here's what I've tried so far (the macro is just called "Biology"):


If Range("C22").Value = "X" Then Call macro_Biology End If


I should add that I'm writing this under VBA section "GetATPLabel". Like I said, total noob, but I think I'm close, so any help is appreciated.


Why does the code run a command, even if it's if statement isn't fulfilled?

When I run my code in debug mode, I can see, that for the value "ooy" another content is set(and it would be correct like this) than for the value "skii". But the code still starts the Activity "Game.class", and the Activity "Tutorial.class" too but only in background. how can I solve this?



@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn_start) {


startActivity(new Intent(this,Tutorial.class));


if (!ooy.equals(skii)){
startActivity(new Intent(this,Game.class));
}

}

Assigning variables within the ifelse function in r

I am pretty new to r and I am trying to get a better grasp of this language by solving problems from one of the books about r (I am not sure if I can put the title here to not advertise it). One of the problems is asking for conditional assigning values to variables, based on certain criteria. To be more precise, I am randomly choosing a number between 2 and 12 (throwing 2 dice) and dependently on the value I get, I have to assign values to variables status and points as follows:



  1. if score is 2,3, or 12 then status <- FALSE and points <- NA

  2. if score is 7 or 11 then status <- TRUE and points <- NA

  3. if score is 4-6,8-10 then status <- NA and points <- score


It is quite simple problem and I know that the following code works (`score is :



score <- sample(2:12,1)
if(score %in% c(2,3,12)){
status <- FALSE
points <- NA
} else if(score %in% c(7,11)){
status <- FALSE
points <- NA
} else {
status <- FALSE
points <- NA
}


I was also trying to solve this problem using the ifelse function but I get an error when I try to assign variables. Here is what I did (I know that what I get right now is a character vector but that was the only way I could make it work).



ifelse(any(score == c(2,3,12)), "game_status = FALSE, point = NA",
ifelse(any(score == c(7,11)), "game_status = TRUE, point = NA",
paste("game_status = NA, point = ", score)))


Is there a way to assign values within the ifelse function? Also, can it be done with the switch function? I am trying to figure out if there is more than just one way to solve this simple problem so that I know how to proceed with more complicated ones.


Thank you!


Rename A Sub-Directory the parent folder name if NOT called "info"

Is it possible to make a batch file that will rename a folder if does not have a specific name?



EG: Example Directory

- - - > info

- - - > pictures


Make a batch file that would so something like

IF (Folder name) IS NOT (info) THEN REN ... ect ? Thanks in advance for your time if you are able to help.


how to add logical operators?

I have been trying to work this issue of on Codecademy all day. Nothing I do seems to work.


Instructions: "Add some if/else statements to your cases that check to see whether one condition and another condition are true, as well as whether one condition or another condition are true. Use && and || at least one time each."


This is the code I previously entered:



var user = prompt("What is your name?").toUpperCase();

switch(user) {
case 'Sam':
console.log("Hi, Sam");
break;
case 'John':
console.log("Hi, John");
break;
case 'Mary':
console.log("Hi, Mary");
break;
default:
console.log("I don't know you. What is your name?");
}

Else does not work in prepared selection of $row

I want to check if user has set his gender. If not, it will display the 1st echo. If yes, it'll display the echo of his gender. Problem is that the page shows only the 1st echo even though there IS set gender in database... I really don't know why it is not working... My code:



<?php


$username = $_SESSION['username'];

$sql = "
SELECT gender FROM members WHERE username = ?";
$stmt->bind_param('s', $username);

$stmt->execute();
$stmt->bind_result($username);
while ($stmt->fetch()){
if($row['gender'] == ""){
echo "You have not selected your gender yet."; // This is the 1st echo and this is the only one that is displayed
} else {
echo "You selected that you are {$row['gender']}."; // This is not displayed no matter what...
}
}
?>


What I have wrong? *Sorry for wrong title


Python: loop in elif condition

I'm running Python 3.


Is it possible to put a loop in the condition for elif? Here's the basic idea I'm trying to achieve. The number of items in the list is not constant.



if some_condition:
do this
elif [ x.method() for x in list ]:
do this to x
else:
do something else


Now, this comes to my mind:



if some_condition:
do this
for x in list:
if x.method():
do this to x
break


But I'm trying to avoid running all the if statements, there's a lot of stuff going on in them. And I would like to get it in the elif part specifically and not in else.


Is there a way to achieve the first code example in Python without using e.g. boolean helper variables:



if some_condition:
do this
first_thing_happened = True
if not first_thing_happened:
for x in list:
if x.method():
do this to x
break

gets.chomp find a string in a list

Is it possible to find a string in a list for a gets.chomp for if, elsif?



def number_problem()

puts "Please enter a number 1-100 for a phrase or word back!"
number = gets.chomp

mult_of_three = ["3", "6", "9", "12", "15", "18", "21", "24", "27", "30", "33", "36", "39", "42", "45", "48", "51", "54", "57", "60", "63", "66", "69", "72", "75", "78", "81", "84", "87", "90", "93", "96", "99"]
mult_of_five = ["5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"]
mult_of_both = ["15", "30", "45", "60", "75", "90"]

if number == mult_of_three
puts "Bit"

Programm that converts a character capitalization

I'm making a programm that, if the user inputs a lowercase character, the programm generates it's character in uppercase, and the opposite too. I'm using a function in order convert the character into lowercase or uppercase based on ASCII table. Lowercase to uppercase is being converted correctly, but uppercase to lowercase is not. I dunno if I'm messing it up:



char changeCapitalization(char n)
{
//uppercase to lowercase
if(n>=65 && n<=90)
n=n+32;
//lowercase to uppercase
if(n>= 97 && n<=122)
n=n-32;
return n;
}

Building an IIF statement with a Yes/No Field

I'm trying to do a calculation to refer back to a field if another field =Yes and I keep getting the #Type! error. The fields are [Written] which contains a currency total, [LR Test] which is the Yes or No field and [Written totals]. So basically what I want my expression to do is IF LR Test = Yes I want Written Totals to show the amount from the [Written] field, IF it's a No, then it could be Null or 0.


This is the calculation I have tried that returns with #Type! IIf(([LR Test]=Yes),[Written],Null)


Any help or advice is greatly appreciated. I'm very new to access so it has been quite a struggle.


Using Ternary Operator without the Else statement PHP

Can you use the Ternary Operator in PHP without the closing 'else' statement? I've tried it and it's returning errors. Google search isn't yielding anything, so I think the answer is probably no. I just wanted to double check here. For instance:



if ( isset($testing) {
$new_variable = $testing;
}


Will only set $new_variable if $testing exists. Now I can do



$new_variable = (isset($testing) ? $testing : "");


but that returns an empty variable for $new_variable if $testing isn't set. I don't want an empty variable if it's not set, I want the $new_variable to not be created.


I tried



$new_variable = (isset($testing) ? $testing);


and it returned errors. I also tried



$new_variable = (isset($testing) ? $testing : );


and it also returned errors. Is there a way to use the Ternary Operator without the attached else statement, or am I stuck writing it out longhand?


How do I check if the user is connected to a certain network or not?

Hi i am coding a student registration application and want to limit the user to only be able to sign in if they are connected to the university network, is there a 'if' statement that i can do that with?


PowerShell and creating groups based on results





This should be simple, but I guess my brain is fried? :-)



I have a task that takes a list of devices, does a ping check on them and to be super duper sure something is wrong I want to do another check on ONLY the devices which fail the ping test in the previous step.



The ping part I've done, however when I pass on in my IF statement to do the next check the value $s passes all of the devices I initially mentioned and not just the failed ones.



Could anyone shed some light on how I can sort this?



Thanks all,


Compare to multiple values in an if statement.

im going to need multiple if statements comparing to the same couple elements, and was wondering if there was something along these lines i could do to make the code cleaner and easier.


Example would be that this function.



def test(num):

a = [1, 2, 3]

if num == a :
return True

else :
return False


would return



>>>test(1)
True
>>>test(2)
True
>>>test(5)
False


Instead of having to write the separate if statements for 1, 2, and 3.


SAS Assign variable if it meets any of multiple string requirements


if find(upcase(owner,in('ADMIN'|'ASSOC'|'BANK'|'CHRIST'|'CHURCH'|'CITY'|)))
THEN NameFlag = 1;
ELSE NameFlag = 0;
IF NameFlag > 0 then NameExclusion=1;
else NameExclusion=0;


I want this if statement to search variable OWNER for any string featured in the in statement and assign a flag if it hits. Ideally I'd like to point this string at a separate data-set that I can just update on the fly, but I'm not quite sure I know how to do that yet. Any help would be appreciated.


Thanks!


loop returns 0 when trying to count points between limits

I am trying to return the number of points of a set of continuous time series data using nCode glyphworks, the variable points_IL returns 0, I need it to return the number of points between the lower and upper limit, the application specific code is correct, could someone look at this code and suggest some improvement/fix



i=0
while i<Point_Count:

Point_Val = tsin.GetValue(Single_TAL_Index,i)

es.JournalOut(str(Point_Val))
if Lower_Limits[locate_chan]<=Point_Val<=Upper_Limits[locate_chan]:
Points_IL+=1
i+=1

es.JournalOut('number of points in the limits')
es.JournalOut(str(Points_IL))

Compressing multiple conditions in Python

Suppose I have a list of numbers mylist and that I would like execute some code if all the elements of mylist are greater than 10. I might try



if mylist[0] > 10 and mylist[1] > 10 and ... :
do something


but this is obviously this is a very cumbersome. I was wondering if Python has a way of compressing multiple conditions in an if statement. I tried



if mylist[i] > 10 for i in range(len(mylist)):
do something


but this returned an error.


I am using Python 3.4.


c# quiz application running score

I am developing a quiz application that keeps a running score for example an incorrect answer gives -1 and a correct answer gives +1. It works fine but i am having trouble with the final question i would like my "next" button to change to a "results" button on the form and then on click display a message box displaying a message containing the score and a message. How could i implement this button change only when the answer has been submitted on the last question as i am catching an exception at the minute


here is my code:



int score = 0;
int i = -1;
int a = 0;

string[] questions = new string[]
{
"Question 1?",
"Question 2",
"Question 3",
"Question 4",
};


string[] answers = new string[]
{
"incorrect","correct","incorrect","incorrect",
"correct","incorrect","incorrect","incorrect",
"incorrect","incorrect","incorrect","correct",
"incorrect","incorrect","correct","incorrect"



};

string[] quizAnswers = new string[] { "correct", "correct", "correct", "correct" };


public FrmQuestion2()
{
InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Tutorial3 t3 = new Tutorial3();
t3.Show();
}

private void FrmQuestion2_Load(object sender, EventArgs e)
{

}

private void Sbutton_Click(object sender, EventArgs e)
{
try
{

if (i < questions.Length)
i++;
txtQuestion.Text = questions[i];

RadA.Text = answers[a];
a++;
RadB.Text = answers[a];
a++;
RadC.Text = answers[a];
a++;
RadD.Text = answers[a];
a++;
Sbutton.Visible = true;
Sbutton.Enabled = true;
Sbutton.Text = "Submit";
// Subutton.Visible = true;
// Subutton.Enabled = true;

}
catch (Exception ex)
{
MessageBox.Show("Only 4 questions available: Your Score is: " + score + " You need at least a score of 3 to progress");


}
if (score >= 3)
{
nxtbutton.Visible = true;
nxtbutton.Enabled = true;

}
else if (score < 3)
{
nxtbutton.Visible = false;
nxtbutton.Enabled = false;
RetryButton.Visible = true;
RetryButton.Enabled = true;

}

}

private void Subutton_Click(object sender, EventArgs e)
{


try
{


if (getSelected().Equals(quizAnswers[i]))
{
MessageBox.Show("Correct");
score++;

txtScore.Text = Convert.ToString("Score:" + score);
Subutton.Enabled = false;
Subutton.Visible = false;
Sbutton.Visible = true;
Sbutton.Enabled = true;
Sbutton.Text = "Next";

}

else
{
MessageBox.Show("Incorrect");
score--;

txtScore.Text = Convert.ToString("Score:" + score);
Subutton.Enabled = false;
Subutton.Visible = false;
Sbutton.Visible = true;
Sbutton.Enabled = true;
Sbutton.Text = "Next";

}

}
catch (Exception ex)
{
MessageBox.Show("Please start the quiz");

}
}



string getSelected()
{
if (RadA.Checked)
return RadA.Text.ToString();
if (RadB.Checked)
return RadB.Text.ToString();
if (RadC.Checked)
return RadC.Text.ToString();
if (RadD.Checked)
return RadD.Text.ToString();
return "";

}

private void RetryButton_Click(object sender, EventArgs e)
{
this.Hide();
FrmQuestion2 q2 = new FrmQuestion2();
q2.Show();
}


thanks for your help


Java If-else function not working correctly

I'm new to Java and MySQL and I'm currently trying to finish my assignment, although I'm having a problem with the IF function. I'm wanting to print the query results from MySQL to the console based on Customer ID and display an error message if the Customer ID doesn't exist.


The data displays if the ID is found in the database, but if the ID does not exist, nothing happens. Any help would be greatly appreciated!



package cos106_assignment_april2015;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.sql.*;
import javax.swing.border.*;


public class ProductSearch {

JFrame f = new JFrame("Ray Sport Inc. | Product Search");
JTextField custIDF;

public ProductSearch() {
JLabel search1, customer, empty;
search1 = new JLabel("Enter Customer ID number to search for a customer's product records. Results print to console.");
customer = new JLabel("Customer ID:");
empty = new JLabel("");

custIDF = new JTextField();

JButton search, back;
search = new JButton("Search");
back = new JButton("Back to Menu");

search.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e){

String custID = custIDF.getText();

try {
System.out.println("Establishing connection to the MySQL Database...");
Connection conn = null;
Statement stmt =null;
String url = "jdbc:mysql://localhost:3306/raysportdb";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url,userName,password);
stmt = conn.createStatement();
System.out.println("Connection established. Connected to the customer and item records.");

String sql = "select a.Customer_ID, c.Order_ID, b.Product_ID, \n" +
"b.Product_Name, b.Product_Type, c.Order_Quantity \n" +
"from customer a, product b, orders c \n" +
"where a.Customer_ID = '"+custID+"' and b.Product_ID = c.Product_ID \n" +
"and b.Product_Type = c.Product_Type_FK and a.Customer_ID = c.Customer_ID \n" +
"group by c.Order_ID order by a.Customer_ID";

ResultSet result = stmt.executeQuery(sql);
while(result.next()){
String cid = result.getString("a.Customer_ID");
if (custID.equals (cid)) {

String f2 = result.getString("c.Order_ID");
String f3= result.getString("b.Product_ID");
String f4 = result.getString("b.Product_Name");
String f5 = result.getString("b.Product_Type");
String f6 = result.getString("c.Order_Quantity");

System.out.println("");
System.out.println("Customer ID\t:"+ cid);
System.out.println("Order ID\t:" + f2);
System.out.println("Product ID\t:" + f3);
System.out.println("Product Name\t:" + f4);
System.out.println("Product Type\t:" + f5);
System.out.println("Order Quantity\t:" + f6);
System.out.println("");
}
else {
JOptionPane.showMessageDialog(null, "Customer ID does not exist!", "Error", JOptionPane.ERROR_MESSAGE);
System.out.println("Customer ID does not exist in the database.");
}
}
conn.close();
}

catch (Exception err) {
System.err.println("Error:"+ err.getMessage());
}}});


back.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e){
new Menu();
f.setVisible(false);}});

JPanel p = new JPanel();
p.setLayout(new GridLayout(6,2));
p.setBorder(new TitledBorder("Product Search"));
p.add(search1);
p.add(empty);
p.add(customer);
p.add(custIDF);
p.add(search);
p.add(back);

f.getContentPane().add(p);
f.pack();
f.setSize(585,284);
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);



}

public static void main(String ar[]){

new ProductSearch();
}
}

Multiple if statement returning css value depending on URL

The script works but their seems to be a bug causing the first and last if statement to implement the style no matter what page it is on. The middle if statement does not display.


I have also tried a break and return after each if statement but that completely brakes the script and does not display anything on the page.



window.onload = function()
{
var ThisStyle = "background-color: #4C4C4C; color: #fff; -webkit-border-top-right-radius: 15px; -webkit-border-bottom-right-radius: 15px; -moz-border-radius-topright: 15px; -moz-border-radius-bottomright: 15px; border-top-right-radius: 15px; border-bottom-right-radius: 15px;"

if (document.URL.indexOf("index.php"))
{
document.getElementById("home-nav").style.cssText = ThisStyle;
}

else if (document.URL.indexOf("about.php"))
{
document.getElementById("about-nav").style.cssText = ThisStyle;
}

else (document.URL.indexOf("products.php"))
{
document.getElementById("products-nav").style.cssText = ThisStyle;
}
}


Anyone have any idea what I am doing wrong?


Using JS if statement to change div class with button (what am I doing wrong)?




function navtoggle(elementRef) {
if (document.getElementById('nav').className = 'closed') {
document.getElementById('nav').className = 'open'
} else if (document.getElementById('nav').className = 'open') {
document.getElementById('nav').className = 'closed'
};

}



.closed {
display: none;
}
.open {
display: block;
}
#navget {
width: 100px;
height: 100px;
box-shadow: 0px 0px 15px black;
}



<html>

<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>HTML Library</title>
</head>

<body>
<div id="nav" class="closed">
<ul>
<li><a href="index.html"><h1>HOME</h1></a>
</li>
</ul>
</div>
<button onclick="JavaScript: navtoggle(this);" id="navget">NAV</button>
</body>

</html>



Here is the Html:



<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>HTML Library</title>
</head>
<body>
<div id="nav" class="closed">
<ul>
<li><a href="index.html"><h1>HOME</h1></a></li>
</ul>
</div>
<button onclick="JavaScript: navtoggle(this);" id="navget">NAV</button>
</body>
</html>


The JS:



function navtoggle(elementRef){
if (document.getElementById('nav').className = 'closed')
{document.getElementById('nav').className = 'open'}

else if (document.getElementById('nav').className = 'open')
{document.getElementById('nav').className = 'closed'};

}


And the CSS:



.closed {
display: none;
}

.open {
display: block;
}

#navget {
width: 100px; height: 100px;
}


I know that it would be easier to just use a checkbox, and I do know how to do that. However, I want it to just be a button so that I can make it look better and such. I'm rather new to JS so please do not be too harsh for the dumb question. Thank you.


Swift nested "if let" seems like madness - is it?

I have been advised to use if lets when examining optional variables. This makes sense, but I have ended up with the following code. It works, but it looks like utter madness! Please tell me that there is a better way.



( users: [ JSONValue ]? ) in

if let jsonValue: JSONValue = users?[ 0 ]
{
if let json: Dictionary< String, JSONValue > = jsonValue.object
{
if let userIDValue: JSONValue = json[ "id" ]
{
let userID: String = String( Int( userIDValue.double! ) )
println( userID )
}
}
}

How to run 2 sql queries in one php if statement?

This is the code i have so far



if (isset($_POST['button1']))
{
$sql = "DELETE FROM UpcomingRota";
$E1 = $_POST["MondayAMFirstEmployee"]; $E2 = $_POST["MondayAMSecondEmployee"]; $E3 = $_POST["MondayAMThirdEmployee"];
$sql = "INSERT INTO UpcomingRota (DayAndTime, FirstEmployee, SecondEmployee, ThirdEmployee) VALUES ('MondayAM', '$E1', '$E2', '$E3')";

}


Both the $sql statements work perfectly on there own but when i have both in the if statement it seems to bypass the first one and just run the last $sql statement.


How can i get it to run as many $sql statements as i need it to.... going to have around 15 - 20 in there.


Thanks in advance.


sql server trigger IF condition on other table

In SQL Server, is possible trigger an event based on a SELECT condition in another table?


Let's imaging this trigger in TABLE_1:



FOR INSERT AS
BEGIN
INSERT INTO TABLE_2 (ID, COD_CAT) SELECT COD_ART,'X3' FROM INSERTED


This trigger works fine and always.


I would like trigger that insert event only if INSERTED.COD_ART is not already existing in TABLE_2.


Any idea?


lundi 30 mars 2015

find missing numbers inside lots of files

I have a big list of ordered files with names like this


file_1.txt file_2.txt file_3.txt file_6.txt file_7.txt file_8.txt file_10.txt


In this case it is easy to see that files: file_4.txt,file_5.txt and file_9.txt are missing, but if i have a big list how can i find the missing files? i am just learning bash so i just know some simple examples. like this



for i in $(seq 1 1000) ;

do
if [i not in *.txt]; then
echo $i;

done


but this doesnt even work unless i erase the "if [i not in *.txt];then" line so it just writes all the numbers between 1 and 1000 i hope you can help me thanks in advanced Ce


Using several operators in a jquery if statement

I'm trying to pull out specific xml nodes if they match a set of criteria.


I'm looking to write an if statement that queries:



  • if the xml series node text is equal to the current value of the seriesAlpha array and the xml issue number node text is equal to the current value of the issueOrder array and the xml special edition node is empty


-OR-



  • if the xml series node text is equal to the current value of the seriesAlpha array and the xml edition name node text is equal to the current value of the issueOrder array.


My current code is as follows:



if($(this).find('series').text() == seriesAlpha[i] && $(this).find('number').text() == issueOrder[j] || $(this).find('edName').text() == issueOrder[j])


I don't know how to add in the check to see if the special edition node is empty, or if it's even possible to have that level of specificity.


Error in mysql trigger and update

I have the next trigger:



CREATE
TRIGGER t_call_status
AFTER INSERT
ON tblcdr FOR EACH ROW
BEGIN

DECLARE lastid integer;
DECLARE nseg integer;

SET lastid = LAST_INSERT_ID();
SET nseg = 120;

IF ((origen = 'ANSWERED' && destino = 'ANSWERED') && (billsec_origen >= nseg && disposition_destino >= nseg)) THEN
update tblcdr set call_status = 3 where id = lastid;
ELSE IF (origen = 'ANSWERED' && destino = 'ANSWERED') THEN
update tblcdr set call_status = 2 where id = lastid;
ELSE IF (origen = 'ANSWERED' && destino <> 'ANSWERED') THEN
update tblcdr set call_status = 1 where id = lastid;
ELSE IF (origen <> 'ANSWERED' && destino <> 'ANSWERED') THEN
update tblcdr set call_status = 0 where id = lastid;
ELSE
update tblcdr set call_status = 0 where id = lastid;
END IF;

END;


But, i got the next error:



1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use


near '' at line 7



How can I fix it?


Greetings.


Tableau: Creating Dynamic Filter to exclude names

I have been working on this for the better part of the day and would like to crowd source as I must just be missing something simple.


I would like to use a parameter control to create a dynamic filter that would exclude the names of individuals that have already participated in an event. For example in the following list of two fields:


Name-Event Name


Carl-Agriculture


Carl-Agriculture


Carl-Agriculture


Jodie-Business


Jodie-Agriculture


Jodie-Agriculture


Pam-Business


Pam-Business


Pam-Business


if the parameter was set to Agriculture, only Pam would show up on the list, and if it was set to Business only Carl would show up. This list will help stakeholders send invitations to potentially interested parties.


I have tried so many calculations including the parameter itself in IF statements, IIF statements, CASE statements, etc. I've also tried creating a second calculation to work off of the first but am still striking out.


Any ideas?


Efficiency in C++ Function Logic

I have some code that implements the illusion of a side-scroller. I'm trying to make it more efficient in that I'm repeating a few lines over and over again and I know when I do that there is always a better way. Ideas?


The code is as follows:



void sideScroll(MegaMan* mega, Block** blockArray, int numBlocks)
{


//Compare Megaman's position to screen width
if(mega->getPosX() >= ((SCREEN_WIDTH/2)-MM_SPRITE_WIDTH)&& mega->getState()==RUN_RIGHT)
{
for(int i=0; i<numBlocks; i++)
{
//if Greater, move blocks by Megamans movement speed
blockArray[i]->setPosX(blockArray[i]->getPosX()-MM_RUN_SPEED);
}
}

//Uncomment for further functionality

if(mega->getPosX() <= 0 && mega->getState()==RUN_LEFT)
{
for(int i=0; i<numBlocks; i++)
{
//move blocks by Megamans movement speed
blockArray[i]->setPosX(blockArray[i]->getPosX()+MM_RUN_SPEED);
}
}
if (mega->getPosY() >= SCREEN_HEIGHT-MM_SPRITE_HEIGHT && mega->getState()==CLIMB)
{
for(int i=0; i<numBlocks; i++)
{
//move blocks by Megamans climb speed
blockArray[i]->setPosY(blockArray[i]->getPosY()-MM_CLIMB_SPEED);
}
}
if (mega->getPosY() <= 0 && mega->getState()==CLIMB)
{
for(int i=0; i<numBlocks; i++)
{
//move blocks by Megamans climb speed
blockArray[i]->setPosY(blockArray[i]->getPosY()+MM_CLIMB_SPEED);
}
}

}

Is there a function that will ignore capital letters in javascript?

i have a chatbot that answers questions only if i write them the same way as in the code Ex: If i wrote the tag "Hello" it will not answer if i say in the chatbot "hello" . I have to write it with a capital letter like in the code. Is there a function that will ignore that and answer it even if i write it "HeLlO"?



if (message.indexOf("Bye")>=0 || message.indexOf("bye")>=0 || message.indexOf("Goodbye")>=0 || message.indexOf("Goodbye")>=0 ){
send_message("You're welcome.");
}

Javascript - Parsing toDateString Month from a text string to number string using "IF(){}" vs "SWITCH(){}

I have what is probably a very simple question about using IF statements vs SWITCH in Javascript. I am attempting to add the current date to my page in the format "Month/Day/Year" where "Month" is a number like so "03/30/2015". I have been able to solve this problem using the code below: http://ift.tt/1HYeHez



var d = new Date();
var dd = d.toDateString();
var ddd = dd.split(' ');
ddd.shift();
var mon = ddd[0];
var da = ddd[1];
var yr =ddd[2];
if (mon == "Jan"){monb = 1;}
if (mon == "Feb"){monb = 2;}
if (mon == "Mar"){monb = 3;}
if (mon == "Apr"){monb = 4;}
if (mon == "May"){monb = 5;}
if (mon == "Jun"){monb = 6;}
if (mon == "Jul"){monb = 7;}
if (mon == "Aug"){monb = 8;}
if (mon == "Sep"){monb = 9;}
if (mon == "Oct"){monb = 10;}
if (mon == "Nov"){monb = 11;}
if (mon == "Dec"){monb = 12;}
slashDate = monb + "/" + da + "/" + yr;
document.getElementById('titleDate').innerHTML = slashDate;


However, my understanding is that it would be better to use a SWITCH statement here. So I have replaced the lengthy IF statements with a SWITCH statement as shown here: http://ift.tt/1HYeJ6f



var d = new Date();
var dd = d.toDateString();
var ddd = dd.split(' ');
ddd.shift();
var mon = ddd[0];
var da = ddd[1];
var yr =ddd[2];
switch(mon){
case "Jan": monb = 01;
case "Feb": monb = 02;
case "Mar": monb = 03;
case "Apr": monb = 04;
case "May": monb = 05;
case "Jun": monb = 06;
case "Jul": monb = 07;
case "Aug": monb = 08;
case "Sep": monb = 09;
case "Oct": monb = 10;
case "Nov": monb = 11;
case "Dec": monb = 12;
}
slashDate = monb + "/" + da + "/" + yr;
document.getElementById('titleDate').innerHTML = slashDate;


The problem is that the date produced by the SWITCH statement is wrong!?!? Can anyone help explain why the date produced by the IF statements is correct and the date produced by the SWITCH statement is incorrect? Any help would be much appreciated! Thanks


DOS For if statement to look for file in multiple directories

I'm trying to use the below DOS statement to look for 1st level folders that do not have important.txt.


for /d %X in (M:*) do if not exist important.txt echo %X


This statement runs, but the if portion does not run properly, always returning that the file is missing even when it exists. What am I doing wrong? Please assist. Thanks.


Java getting into both if and else for no reason?


for (int i = 0; i < players.length; i++) {
for (int j = 0; j < 2; j++) {
if (j == 0) {
System.out.println("Player " + (i + 1) + "'s first card is:");
}
else {
System.out.println("Player " + (i + 1) + "'s second card is:");
}

players[i][j] = sc.nextLine();
}
}


That's a very simple piece of code I'm writing right now. For some extremely odd reason, though, for the first player it gets into both if and else at once. It works fine except for player 1. I've been reading my code over and over again for the past 30 minutes and it doesn't make ANY sense to me. So why is that happening and how can I fix it?


how to create if/else statement with value change after click on button?

There are two variables



var bokser = [];
var userChoice;
var randBokser;


plus the info



bokser[0] = {
name:"bokser1",
life:100,
kick:5,
fight:7,
kill:9
};

bokser[1] = {
name:"bokser2",
life:100,
kick:7,
fight:10,
kill:4

};

bokser[2] = {
name:"bokser3",
life:100,
kick:9,
fight:4,
kill:4


};


how to create an if/else statemt



if(userChoice click on button1){
value of bokser randBokser changes
}
if(userChoice click on button2){
value of bokser randBokser changes
}
else(userChoice click on button3){
value of bokserRandbokser changes
}


the value of the life has to be changed. example: userChoice is bokser1, randBokser is bokser2 user click on button1 life of randBokser 100-5(kick) = 95(randBokser lif)


Ruby mulitple conditional statment write to same file twice?

I am trying to create a find and replace script in ruby. But I cannot figure out how to write to the same file twice when there are two conditions matched (2 different regex patterns are found and need to be replaced in the same file) I can get it either to provide 2 copyes of the file concatonated with only changes made from one condition in each.


Here is my code (Specifically pattern3 and pattern4):



print "What extension do you want to modify? "
ext = gets.chomp

if ext == "py"
print("Enter password: " )
pass = gets.chomp

elsif ext == "bat"
print "Enter drive letter: "
drive = gets.chomp
print "Enter IP address and Port: "
ipport = gets.chomp
end

pattern1 = /'Admin', '.+'/
pattern2 = /password='.+'/
pattern3 = /[a-zA-Z]:\\(?i:dir1\\dir2)/
pattern4 = /http:\/\/.+:\d\d\d\d\//


Dir.glob("**/*."+ext).each do |file|
data = File.read(file)
File.open(file, "w") do |f|
if data.match(pattern1)
match = data.match(pattern1)
replace = data.gsub(pattern1, '\''+pass+'\'')
f.write(replace)
puts "File " + file + " modified " + match.to_s
elsif data.match(pattern2)
match = data.match(pattern2)
replace = data.gsub(pattern2, 'password=\''+pass+'\'')
f.write(replace)
puts "File " + file + " modified " + match.to_s
end

if data.match(pattern3)
match = data.match(pattern3)
replace = data.gsub(pattern3, drive+':\dir1\dir2')
f.write(replace)
puts "File " + file + " modified " + match.to_s
if data.match(pattern4)
match = data.match(pattern4)
replace = data.gsub(pattern4, 'http://' + ipport + '/')
f.write(replace)
puts "File " + file + " modified " + match.to_s
end
end
end
end


f.truncate(0) makes things better but truncates the first line since it concatonates from the end of the 1st modified portion of the file.


If statement based on time of day to document write an .js from the web

`We have a webpage that displays the wait time of an ER. The java script will change the content based on the time of day. If the time is from 10am to 10pm the http://ift.tt/1bJNOhd should display the wait time. If not then say closed. I have tried everything i know which is not much first time coding javascript and i have tried google searching even looked in innerhtml. If anyone could please help i would appericate it


The problem is that i cannot get the .js to run in the if statement. I have tried with out document write. i have tried this format





document.write('<script src="http://ift.tt/1bJNOhd"><\/script>');





<script language="JavaScript">
var objDate = new Date();
var hours = objDate.getHours();
if(hours >= 10 && hours <= 22){
document.write('<src="http://ift.tt/1bJNO0q;');
}
else
{
document.write('CLOSED');
}

</script>



full code found here





<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ift.tt/kkyg93">
<html xmlns="http://ift.tt/lH0Osb" xml:lang="en"
lang="en">
<head>
<title>Shannon Medical Center | San Angelo, Texas | Shannon
Medical Center</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
<meta name="Distribution" content="Global" />
<meta name="Author" content="Ashley Aguilar" />
<meta http-equiv="refresh" content="300" />
<link rel="stylesheet" href="style.css"
type="text/css" />
</head>
<body>
<div id="container">
<div id="content"><!-- CONTENT START -->
<p style="text-align: center;"><img src="UCT.png" /></p>
<p
style="text-align: center; font-family: tahoma,sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 25px; line-height: normal; font-size-adjust: none; font-stretch: normal;">If
the wait time is more than 45 minutes, you can call ahead.</p>
<h1><img src="UCN.png" /></h1>
<table>
<tbody>
<tr>
<td width="410">
<blockquote>
<script language="JavaScript">
var objDate = new Date();
var hours = objDate.getHours();
if(hours >= 10 && hours <= 22){
document.write('<src="http://ift.tt/1bJNO0q;');
}
else
{
document.write('CLOSED');
}

</script>
</blockquote>
</td>
<td width="300">
<p
style="font-family: tahoma,sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 18px; line-height: normal; font-size-adjust: none; font-stretch: normal;">32626
N. Bryant<br />
San Angelo, TX 76903<br />
No Appointment Required<br />
325.481.2271</p>
</td>
<td width="300">
<p
style="font-family: tahoma,sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 20px; line-height: normal; font-size-adjust: none; font-stretch: normal;">Hours
Open<br />
7am - 8pm Daily</p>
</td>
</tr>
</tbody>
</table>
<h2><img src="UCS.png" /></h2>
<table>
<tbody>
<tr>
<td width="410">
<blockquote>
<script
src="http://ift.tt/1bJNOhd"></script>
mins.
</blockquote>
</td>
<td width="300">
<p
style="font-family: tahoma,sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 18px; line-height: normal; font-size-adjust: none; font-stretch: normal;">3502
Knickerbocker Rd.<br />
San Angelo, TX 76904<br />
No Appointment Required<br />
325.481.2222</p>
</td>
<td width="300">
<p
style="font-family: tahoma,sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 20px; line-height: normal; font-size-adjust: none; font-stretch: normal;">Hours
Open<br />
7am - 10pm Daily</p>
</td>
</tr>
</tbody>
</table>
<h2><img src="UCW.png" /></h2>
<table>
<tbody>
<tr>
<td width="410">
<blockquote>
<script
src="http://ift.tt/1bJNOxr"></script>
mins.
</blockquote>
</td>
<td width="300">
<p
style="font-family: tahoma,sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 18px; line-height: normal; font-size-adjust: none; font-stretch: normal;">4251
Sunset Dr.<br />
San Angelo, TX 76904<br />
No Appointment Required<br />
325.481.2226</p>
</td>
<td width="300">
<p
style="font-family: tahoma,sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 20px; line-height: normal; font-size-adjust: none; font-stretch: normal;">Hours
Open<br />
7am - 10pm Daily</p>
</td>
</tr>
</tbody>
</table>
<!-- CONTENT END -->
</div>
<div><!-- CONTAINER END -->
</div>
</div>
</body>
</html>



Excel If function to return a value 2 rows below

I need an if statement in cell "P1" to output the value "A" in cell "P3" if the value of N1 is "Y"


Cell "N1" has this formula =IF(A1="Defect Description :","Y","") so the value of "N1" is "Y" in this case.


Any ideas??


loop giving wrong output

I have an ex. to do. First I have to set wd, then create 100 files (i.txt). Each one of these files receives a random letter. Then I have to rename the files using the letters that were assigned to them (ex: 1.txt received letter C, thus it must be renamed as 1C.txt). I have then to create a new file (named "0.dat"), that appends the letters of each file. If they were appended as a character of length 1, I have to change to a character of length 100 and vice versa. However, the output of my code is wrong. If I do line by line it works, but when I run the entire code the answer is wrong. My code is:



# set wd

ROOT <- setwd("/Users/rebecadoctors/Documents/teste")

# confirm existance of dir, else create new

if (file.exists(paste(ROOT,"exercicio03", sep = "/"))){

stop("dir already exists")


} else{

dir.create(paste(ROOT,"exercicio03",sep="/"))
setwd("/Users/rebecadoctors/Documents/teste/exercicio03")

# create files (1:100)

for (i in 1:100){

# assign random LETTER to files

file.create(paste(i,"txt",sep="."))
AZ <- sample(LETTERS,1)
cat(AZ,file = paste0(ROOT,"/exercicio03/",i,".txt"))

# rename files, and create new file "ROOT/exericio03/0.dta" with append of LETTERS

name <- scan(file=paste0(ROOT,"/exercicio03/",paste(i,"txt",sep=".")),what = "character")
file.rename(paste0(ROOT,"/exercicio03/",paste(i,"txt",sep=".")), paste0(ROOT,"/exercicio03/",paste0(i),name,".txt"))
cat(name,file=paste0(ROOT,"/exercicio03/",0,".dat"),append = T)
NewFile <- scan(file=paste0(ROOT,"/exercicio03/",0,".dat"),what="character")
print(NewFile)

# if length(character)==1 change to length(character)==100

if (length(NewFile == 1)){

cat(name,file=paste0(ROOT,"/exercicio03/",1,".dat"),fill=T,append = T)
file.remove(paste0(ROOT,"/exercicio03/",0,".dat"))
file.rename(paste0(ROOT,"/exercicio03/",1,".dat"),paste0(ROOT,"/exercicio03/",0,".dat"))

}else {

#nothing

}
}

}


The output is :



[1] "R" "M"


when I was expecting to have:



[1] "F" "A" "R" "C" "C" "U" "S" "C" "A" "L" "Z" "Q" "G" "J" "T" "F" "A"
"B" "P" "P" "Z" "A" "W"
[24] "E" "R" "L" "I" "E" "L" "L" "Z" "U" "I" "N" "H" "O" "G" "Y" "D" "L"
"R" "P" "O" "A" "W" "N"
[47] "R" "F" "C" "C" "J" "V" "O" "M" "Z" "V" "D" "E" "K" "A" "U" "O" "G"
"V" "I" "Z" "G" "V" "A"
[70] "W" "A" "G" "L" "Q" "C" "I" "O" "R" "U" "D" "G" "J" "L" "B" "G" "N"
"N" "R" "F" "N" "G" "G"
[93] "U" "K" "G" "B" "V" "K" "P" "A"


Do you have any idea why it is happening? Thank you!


python if-statement with IndentationError

I have wrote a function to get commands in my database and now I am trying to write a function with more specify detail to enter to my database.But there is an error when I add a elif statement


Before:(Success)(ps :user is going to input function of the command first, if user input "switch" in the device buttom , he will get commands from my switch table, else he will get commands from router"):



def readciscodevice(function, device):
conn = sqlite3.connect('server.db')
cur = conn.cursor()
if device == "switch":
cur.execute(
"SELECT DISTINCT command FROM switch WHERE function =? or function='configure terminal' or function='enable' ORDER BY key ASC",
(function,))
read = cur.fetchall()
return read
elif device == "router":
cur.execute(
"SELECT DISTINCT command FROM router WHERE function =? or function='configure terminal' or function='enable' ORDER BY key ASC",
(function,))
read = cur.fetchall()
return read;
a = input("function:")
b = input("device:")
for result in readciscodevice(a,b):
print(result[0])


Then, I am trying to create a table called "showcommand" as show commands do not need to press "configure terminal" so I will make one more if statement but it seems not working...


After I add a if statement:



def readciscodevice(function, device):
conn = sqlite3.connect('server.db')
cur = conn.cursor()
if device == "switch":
cur.execute(
"SELECT DISTINCT command FROM switch WHERE function =? or function='configure terminal' or function='enable' ORDER BY key ASC",
(function,))
read = cur.fetchall()
return read
elif device == "router":
cur.execute(
"SELECT DISTINCT command FROM router WHERE function =? or function='configure terminal' or function='enable' ORDER BY key ASC",
(function,))
read = cur.fetchall()
return read;
elif device == "showcommand":
cur.execute(
"SELECT DISTINCT command FROM showcommand WHERE function =? or function='enable' ORDER BY key ASC",
(function,))
read = cur.fetchall()
return read;


a = input("function:")
b = input("device:")
for result in readciscodevice(a,b):
print(result[0])


The main error(which is int my last elif-statement[showcommand]) :



read = cur.fetchall()
IndentationError: unindent does not match any outer indentation level


and return read;



Trailing semicolon in the statement less... (Ctrl+F1)
This inspection detects trailing semicolons in statements.


I dun know what is going on? It looks no any problem in my mind but the problem is real. Thank you for helping!


What's a more elegant way to check for null value in the following scenario?

I'm using Groovy. What's a more elegant way to do the following?



if (!token) {
token = this.getToken(key, callback)

if(!token) {
return params = null
}

}


So if a token is already present when a user comes into this flow, that token should be used. However, if the token isn't present, we should try to generate one. The service we're using to get the token doesn't throw an exception if none is created, it just returns null. If the token isn't successfully created (is still null) we want to set the params to null.


Is there a cleaner way to do what I'm doing? The null check within a null check seems ugly to me.


Rails4 - GET vs POST in logic that includes paths

and thank you for your time in advance. To make a long story short: I need a certain layout from some pages, and a different layout for other pages. 2 layouts in total, and these layouts only apply to the navbar and footer links in my app. Instead of making a new application_controller with a new layout, I opted for logic in the application.html.erb file, using logic. Here is what the logic looks like:



<% if current_page?(about_path) ||
current_page?(terms_path) ||
current_page?(faq_path) ||
current_page?(signup_path) ||
current_page?(signin_path) ||
current_page?(root_path) %>

<Code for one layout>

<% else %>

<Code for the second layout>

<% end %>


I understand that this isn't the ideal way to make this work, but it was the path I chose, and was curious about, so I would like to figure out how to finish with this method. The problem lies within the authentication and registration pages which should have the old layout. Everything is fine until I make a POST request (hit submit without valid info), at which point it tries to render the new layout. As I understand it, the paths in the logic above are all GET requests, so my question is this:


How can I include paths that handle POST requests? I only have two paths that fall under that category. I would love to know if this is possible, and or the syntax for it, as I will be sticking with this 'experiment' of sorts. Thanks, and have a nice day.


How to convert switch statement to if else statement

a and b are both int variables.



switch (a) {
case 0: b ++; break;
case 1:
case -2: b *= 2; break;
case 4: b = 10 * a;
default: b *= a;
}


How would I write this as a if else statement in as simple of a manner as possible?


Set image source in if statements

In Android Studio I have a double variable called "zahl" that increases every second. I want a certain picture to be shown (and a text set) when zahl is in specific areas. Between these areas I want no picture to be shown. I tried it with only one area and everything worked out good:



if (zahl >= 1 && zahl <= 1.5) {
imageViewEarning.setImageResource(R.drawable.ice);
textViewEarning.setText(getString(R.string.textViewEarning_Eis));
}
else if (zahl >= 1.5) {
imageViewEarning.setImageResource(0);
textViewEarning.setText("");


}


Now I have it with multiple areas but the app always crashed when it reaches the first area where a picture should be shown:



if (zahl >= 1 && zahl <= 1.5) {
imageViewEarning.setImageResource(R.drawable.ice);
textViewEarning.setText(getString(R.string.textViewEarning_Eis));
}
else if (zahl >= 3.5 && zahl <= 4) {
imageViewEarning.setImageResource(R.drawable.hotel);
textViewEarning.setText(getString(R.string.textViewEarning_Kebab));
}
//and so on
else {
imageViewEarning.setImageResource(0);
textViewEarning.setText("");
}


I see no reason for this, has anyone an idea


Store checkbox value of every input and

Once I check all the checkbox, only one checkbox value is stored inside my database. I want to get the value of the checkbox of each student added every input of the admin. One more thing is that I want to copy the data of the first name and section inside the table //see comment to "attendance" database. The database of the value inside the table is "student". Thanks in advance.



<html>
<body>
<form method = "POST"><strong>
Set the date:
</strong>
<input type = "date" name = "set_date"></br></br>
<table width="800" border="3" cellpadding="1" cellspacing="1">
<tr>
<th><center>First name</center></th>
<th><center>Section</center></th>
<th><center>Status</center></th>
</tr>
<?php
$con = mysql_connect("localhost", "root", "avtt123");
mysql_select_db("arvintarrega",$con);

$query = mysql_query("SELECT * FROM student");
echo "<form action = attendance.php method = POST>";
while($student=mysql_fetch_array($query))
{
echo "<tr>";
echo "<td><center>".$student['fname']."</center></td>"; // the 'fname' and the 'section'
echo "<td><center>".$student['section']."</center></td>";
echo '<td><center><input type = "checkbox" name = "status" value = "Present">Present </input>';
echo '<input type = "checkbox" name = "status" value = "Absent">Absent </input>';
echo '<input type = "checkbox" name = "status" value = "Excused">Excused </center></input></td>';
}
echo "</form>";
echo "</table>";

if(isset($_POST['save']))
{
if(filter_input(INPUT_POST, 'set_date') && filter_input(INPUT_POST, 'status'))
{
if(isset($_POST['set_date']) && ($_REQUEST['status']=="Present"))
{
$sql = "INSERT INTO attendance(date, status) VALUES('$_POST[set_date]', '$_REQUEST[status]')";
echo '<span style="color:green;"><strong></br>Attendance Complete!<strong></span>';
}
else if(isset($_POST['set_date']) && ($_REQUEST['status']=="Absent"))
{
$sql = "INSERT INTO attendance(date, status) VALUES('$_POST[set_date]', '$_REQUEST[status]')";
echo '<span style="color:green;"><strong></br>Attendance Complete!<strong></span>';
}
mysql_query($sql, $con);
}
else
echo '<span style="color:red;"><strong></br>All fields are required</strong></span>';
}
?>
</br></br>
<input type = "submit" name = "save" value = "Submit>
</form>
</body>
</html>

Change background color if div has specific Child

I am trying to change the background (and other styles) of a div if it has a specific child. I am using .length to check if the specific child exists but even if it doesn't the div is taking the styles from the jquery if statement. My HTML:



<div class="full-text-panel">
<div class="main-wrap">
<h1 class="home-h1">This is a header</h1>
<a class="body-button">This is a button</a>
</div><!--end main-wrap-->
</div><!--end full-text-panel-->


And my jQuery:



var fullText = $('.full-text-panel');
var bodyButton = $('.body-button');

if ( $(".full-text-panel .body-button").length > 0 ) {
fullText.css("background", "red");
} else {
fullText.css("background", "blue");
}


I thought this would work, but both fullText panels are taking the background red style. What am I doing wrong?


I want to get element value of current page in php


<input type="hidden" id="id" name="id" value="100">
<? $id = '100'; ?>
<? $getid = echo '<script>document.getElementById("id");</script>'; ?>
<? if( $id == $getid ): ?>
<? echo 'id equal getid'; ?>
<? endif; ?>


I want to get a value using getElementById of current page in php.


but I can't get value.


document.getElementById("id");'; ?> code can't page load.


How can I fix it?


Validation of data with char

I'm looking for a valid condition to check if the user is writing a char or not. I was trying with (n!=char), but this is clearly not possible in C right?


this is what I have:



char n;
do
{
printf("Introduce a caracter\n");
scanf("%c", &n);
if(n!=char)
printf("Error! The caracter you introduced is not valid.\n");
}
while(n!=char);

return n;

If li contains text : apply change to specific div in the same li not all

I have a list, each with a button, and a price. I am able to find the button that says "choose options", and then apply a change to another div, however, it changes that div for all LIs, and not just the one where the button text occurs. How do I contain the change to only the relevant LI?



<ul>
<li>
<em class="p-price">$1.95</em>
<div class="ProductActionAdd">
<a href="" class="btn">Add To Cart</a>
</div>
</li>
<li>
<em class="p-price">$4.95</em>
<div class="ProductActionAdd">
<a href="" class="btn">Choose Options</a>
</div>
</li>
<li>
<em class="p-price">$5.95</em>
<div class="ProductActionAdd">
<a href="" class="btn">Add To Cart</a>
</div>
</li>
</ul>

<script>
if ($('ul li:contains("Choose Options")')) {
$(".p-price").prepend("STARTING AT: ");
}
</script>


The Script above does find the "choose options" text. But then it adds "Starting At: " to all .p-price instances. How do I have it only change the .p-price in the same LI? So that the LIs that have "add to cart" button, don't get the text insert before the price?


I've read about .each(), return false, and looping, but not sure If I'm barking up the correct tree, as I've tried various code iterations that fail horribly, but when it comes to this specific if contains, change another div, I cannot find anything that comes close.


I would greatly appreciate any advice on how to do something like this, but keep it isolated to the current li. Thank you tremendously!


Scanning a file and matching strings Java ( Looking for a better way )

I am creating a simple java program which scans through a file and looks for specific strings, i have it working to some degree but i am sure that there is a much more efficient and better way of doing it, i am using an IF contains method to compare for many different strings however i feel that it is a bad way of practicing and was wondering if anyone could give me an idea of what else i could try?



while (sc.hasNextLine()) {

readLine = new Scanner(sc.nextLine());
x = readLine.nextLine();
numberOfLines++;


if (x.contains("a")) {
numberOfConsonants++;
}
if (x.contains("A")) {
numberOfConsonants++;
}
if (x.contains("e")) {
numberOfConsonants++;
}
if (x.contains("E")) {
numberOfConsonants++;
}
if (x.contains("i")) {
numberOfConsonants++;
}
if (x.contains("I")) {
numberOfConsonants++;
}
if (x.contains("o")) {
numberOfConsonants++;
}
if (x.contains("O")) {
numberOfConsonants++;
}
if (x.contains("u")) {
numberOfConsonants++;
}
if (x.contains("U")) {
numberOfConsonants++;
}
}

How to write javascript on phpcode in HTML


<? if( $pi->id == echo "<script>document.getElementById('id');</script>" ): ?>


I want to get HTML element on PHPCODE in HTML like above code.


but It doesn't work.


how can i fix it?


Please Help me.


Problems with PHP if statment

I have been trying to setup a plugin using php. The php file just registers the plugin. The problem is that there are some image files that I want to include in the plugin but the plugin is not picking it up.. I do not get any error messages, its just that when the plugin is installed I do not see the image files, I actully do not know php this is just one file i need to compile for larger project.



<?php

class Plugin_Theme extends DPlugin
{

public function init()
{
DTheme::register($this, $this->getMeta('theme1', 'theme1'));
DTheme::register($this, $this->getMeta('theme2', 'theme2'));
DTheme::register($this, $this->getMeta('theme3', 'theme3'));
DTheme::register($this, $this->getMeta('theme4', 'theme4'));
}

private function getMeta($sub_id, $sub_name, $extends = 'default')
{
$meta = array (
'id' => 'maintheme-' . $sub_id,
'title' => 'maintheme-' . $sub_name,
'extends' => $extends,
);
if ($sub_id != 'theme1') {
$meta['assets'] = array(
0 => 'image1.jpg',
1 => 'image1.jpg',);
}
if ($sub_id != 'theme2') {
$meta['assets'] = array(
0 =>'image2.jpg',
1 =>'image2.jpg',);
}
if ($sub_id != 'theme3') {
$meta['assets'] = array(
0 => 'image3.jpg',
1 => 'image3.jpg',);
}
if ($sub_id != 'theme4') {
$meta['assets'] = array(
0 => 'image4.jpg',
1 => 'image4.jpg',);
}

return $meta;
}
}

Comparing issues with values php

I have a problem with comparing 2 values and let 1 value change within the if statement. But ofcourse when I reload the page it picks up the first value again. I'm using this code to set some information in a database when a machine is turned on or off.



$urlMachineON = 'http://ift.tt/1GbRIuI';

// get content
$contentMachineON = file_get_contents($urlMachineON);

//remove first 2 characters
$truncate = substr($contentMachineON, 2);

//remove last 5 characters
$MachineOn = substr($truncate, 0, -5);
//MachineON can only be 1 or 0

$currentState = 2;

if ($MachineOn != $currentState)
{
$stmt = $conn->prepare("INSERT INTO machineactiviteit (Time, MachineStatus) VALUES(NOW(), ?)");

$stmt->bind_param('s', $MachineOn);

if ($stmt->execute() === TRUE)
{
$currentState = $MachineOn;
echo 'success';
}
else
{
echo $conn->error;
}

$stmt->close();
}
elseif($MachineOn == $currentState)
{
echo 'do nothing';
}


So when I do this he will always use the if statement since the $currentState and $MachineOn are always different from each other. In C# you have something like initalize component to set the value one time to a specific value. But I haven't found anything about that in php. So my question is can I set a value only once? Or should I solve this another way?


This is how it should work:

first attempt before: currentState = 2; MachineOn = 0; after: currentState= 0; MachineOn = 0;

second attempt before: currentState= 0; MachineOn = 0; after: currentState= 0; MachineOn = 0;

third attempt before: currentState= 0; MachineOn = 1; after: currentState= 1; MachineOn = 1;

(I can change the MachineOn value with a button).


Receiving "Control may reach end of non-void function"

The output should allow the user to enter his/her taxable income then choose a filing status then receive his/her tax due. When I try to run, I receive "control may reach end of non-void function" at the end bracket of each function such as float single's end bracket.



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

void taxableincome (float *TI)
{
printf("Enter your taxable income ");
scanf("%f", &*TI);
}

float single (float TI)
{
if (TI > 0 && TI <=24000)
return .15 * TI;
if (TI > 24000 && TI <= 58150)
return 3600 + .28 * (TI - 24000);
if (TI > 58150 && TI <= 121300)
return 13162.00 + .31 * (TI - 58150);
if (TI > 121300 && TI <= 263750)
return 32738.50 + .36 * (TI - 121300);
if (TI < 263750)
return 84020.50 + .396 * (TI - 263750);
}

float marriedfilingjointly (float TI)
{
if (TI > 0 && TI <= 40100)
return .15 * TI;
if (TI > 40100 && TI <= 96900)
return 6015 + .28 * (TI - 40100);
if (TI > 96900 && TI <= 147700)
return 21919.00 + .31 * (TI - 96900);
if (TI > 147700 && TI <= 263750)
return 37667.00 + .36 * (TI - 14770);
if (TI > 263750)
return 79445.00 + .396 * (TI - 263750);
}

float marriedfilingseperately (float TI)
{
if (TI > 0 && TI <=20050)
return .15 + TI;
if (TI > 20050 && TI <= 48450)
return 3007.50 + .28 * (TI - 20050);
if (TI > 48450 && TI <= 73850)
return 10959.50 + .31 * (TI - 48450);
if (TI > 73850 && TI <= 131875)
return 18833.50 + .36 * (TI - 73850);
if (TI > 131875)
return 39722.50 + .396 * (TI - 131875);
}

float headofhouse (float TI)
{
if (TI > 0 && TI <=32150)
return .15 + TI;
if (TI > 32150 && TI <= 83050)
return 4822.50 + .28 * (TI - 23150);
if (TI > 83050 && TI <= 134500)
return 19074.50 + .31 * (TI - 83050);
if (TI > 134500 && TI <= 263750)
return 35024.00 + .36 * (TI - 134500);
if (TI > 263750)
return 81554.00 + .396 * (TI - 263750);
}

void menu (float TI)
{
int filingstatus;
printf("Enter filing status\n");
printf("1. Single\n");
printf("2. Married Filing Jointly\n");
printf("3. Married Filing Seperately\n");
printf("4. Head of House\n");
scanf("&d", &filingstatus);

switch (filingstatus)
{
case 1: printf("Total due tax for single filing: %f\n", single(TI));
break;
case 2: printf("Total due tax for married and filing jointly: %f\n", marriedfilingjointly(TI));
break;
case 3: printf("Total due tax for married but filing seperatedly : %f\n", marriedfilingseperately(TI));
break;
case 4: printf("Total due tax for head of house filing: %f\n", headofhouse(TI));
break;
default:printf("Invalid\n");
}
}

void main ()
{
int filingstatus;
float TI;
taxableincome (&TI);
menu (TI);
}

Powershell nested IF statements





I am trying to do the following:



1.Check for a file in src

1.A If that file is there copy it to dst

1.B If that file is exists in the dst continue

1.C If that file isn't in the dst do something

2.Continue on but do something else

3.Finish off and do something else



However I'm struggling to understand how nested IF statements should be structured, does anyone have any wisdom they pass on to me?



I've Googled a fair bit but nothing helps me understand the way it is done.Ta.


dimanche 29 mars 2015

better way to write if else statement

First time writing Javascript. I just would like know if there is a shorter way of writing this:



<p id="demo"></p>

<script>
function myFunction() {
var letter = document.getElementById("myInput").value;
var text;

if (letter === "5544") {
text = "Abar, Marlon 1,800";

} else if (letter === "5545") {
text = "Pia, Darla 1,800";

} else if (letter === "5546") {
text = "Salazar, Alex 1,500";

//etc...

} else {
text = "Incorrect Account Number";
}
document.getElementById("demo").innerHTML = text;
}
</script>


Tried map but I couldn't get it to work.