vendredi 30 novembre 2018

Compare 2 arrays and distinguish same values in same position and same values in different positions in Java

I have hit a wall and need assistance. I am very new to Java so need to keep this basic to remain at my skill level. I have two Color[] arrays that contain 3 random colors. I am trying to identify colors in the same position and colors that are the same but in different positions in the array. This is the same logic for those familiar with the scoring of Mastermind. Example: answerColors[]{Color.Red, Color.Blue, Color.Blue} userColors[]{Color.Yellow,Color.Blue,Color.Red}

Results should display: same color/position = 1 (this would be the Blue at [1]) same color/ different position = 1 (this would be the Red) NOTE: since the Blue is in the same position([1]) in answerColors and userColors, the Blue[1] in userColors should not be considered when searching if the answerColor Blue at position [2] has a fellow Blue in userColor[] but just in a different position.

Example 2: answerColors[]{Color.Yellow, Color.Green, Color.Blue} userColors[]{Color.Yellow,Color.Blue,Color.Red} Results should display: same color/position = 1 (this would be the Yellow at [0]) same color/ different position = 1 (this would be the Blue)

I have seen a lot of posts that answer the same position questions but none that address the same color but different position when comparing two arrays NEEDING to take into account both (same color/ same position and same color/different position) in the same query so that a color doesn't get compared more than once (i.e. example#1 when the blue in the same position as another blue should not be considered when checking to see if the second blue in answerColor has the same color but different position in userColor)

here is my code that is not working....results should be: same color/same position = 1 same color/different position = 1

any help is appreciated!!!!!!

public void createScoreArray() {  // creates the array for     determining the values for the score panel (2 = same color/same position; 6 = not same color/same position; 1 = same color/different position ignoring those already in same color/same position
    answerColors[]{Color.Red, Color.Blue, Color.Blue};
    userColor[]{Color.Yellow, Color.Blue, Color.Red};
    int j = 0;
    scoreNumCheck = new int[3];
    for (int i = 0; i < answerColors.length; i++) {  // checking same color same position
        if (answerColors[i] == userColor[j]) {
            scoreNumCheck[i] = 2;
            System.out.println(scoreNumCheck[i]);
            j++;
         System.out.println("++++++++++++Score Pegs: " + Arrays.toString(scoreNumCheck));
        } else if (answerColors[i] != userColor[j]) {
            scoreNumCheck[i] = 6;
            j++;
        }
        System.out.println("--------- " + Arrays.toString(scoreNumCheck));


    }
    System.out.println("++++++++++++Score Pegs: " + Arrays.toString(scoreNumCheck));
    for (int s = 0; s < scoreNumCheck.length; s++) {
        if (scoreNumCheck[s] != 2) {
            for (int i = 0; i < answerColors.length; i++) {
                for (int u = 0; u < userColor.length; u++) {
                    if (userColor[u] == (answerColors[i])) {
                        scoreNumCheck[6] = 1;
                    }
                }
            }

        }
        System.out.println("2.  ++++++++++++Score Pegs: " + Arrays.toString(scoreNumCheck));
    }
}

Python - can I repeat if else in a for loop?

Could I repeat if .. else statement in a for loop?

def function_example():
for i in range(len(alist)):
 if ..
   do something
 else
   pass 
 if ...
  do something
 else
   pass

I actually tried this, but it wouldn't work.

Using statement if in looping ajax

Maybe friends here consider me not doing my own business, or googling research. But I am asking a question here because indeed I feel deadlocked, which is why this forum is said to be stack overflow.

I want to use a statement on data looping done on ajax, but I have a problem.

Error:

Uncaught SyntaxError: Unexpected token if

The syntax below is what I made, if this is indeed wrong please help me fix it.

      $.ajax({
        type: 'get',
        url : '<?php echo base_url() ?>index.php/truk/daftar_jeniskerusakan_ajx',
        dataType: 'JSON',
        success:function(data){
          var i = 1;
          var html;
          for (x=0; x<data.length;x++) {
            html += "<tr>"+
                    "<td>"+i+"</td>"+
                    "<td>"+data[x].jenis_kerusakan+"</td>"+
                    if(data[x].status === "1"){
                    "<td>"+"&nbsp;"+"</td>"+
                    }else{                          
                    "<td>"+"<a href='' class='btn btn-xs btn-success'>Approve</a>"+"</td>"+
                    };
                    "</tr>";
                  i++;
          }
          $('#daftar_jenis_kerusakan').append(html);
          $('#daftar_jenis_kerusakan').DataTable({
            "pageLength" : 10,
            "dom" : '<"search"f><"top">rt<"bottom"ip><"clear">'
          });
        }
      });

Multi-line Conditional Statements in Kivy

How do you do multi-line if statements in the kv file?

Button:
    on_press:
        if x == 1:
            do_something
            do_something_else
            do_another_thing

It would be a burden to write

if x == 1: do_something
if x == 1: do_something_else
if x == 1: do_another_thing

Having trouble with Nested if-eilf-else statements in Python

I am experiencing an issue with nested if statements in Python running on repl.it and would like help determine what I am doing wrong or if there is a great way to rework the entire section.

Background and Current Goal: I am attempting to make a generic settings module that will work with various different programs. My goal for the problem block is to be able to detect when a variable is set to a specific string (by a string splitter) to identify the command, and then check the arguments (another variable). Finally, whatever the command does would be executed.

Issue Python/repl.it will not accept my nested if statements.

The problem block:

elif(Command=="debug"):
    print("Not Fully Implemented")
    if(Args=='-E'):
      DebugMode =="Enabled"
    elif(Args=="D-"):
      DebugMode == "False"
    elif(Args=="-query"):
      print(str(DebugMode)
    else:
      print("Argument Error.  For a valid list of commands, type     'help'")

The Error message (Ignore Color)

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
  File "main.py", line 68
    else:
       ^
SyntaxError: invalid syntax

The full program so far:

#SettingsCommandLineUitily #Imports #Initization print("Starting Settings Utitlies... 000%",end="\r") from time import sleep import sys

#Initizatin Countdown
INIT_PERCENT=0
for i in range(97):
  print("Loading Settings Utitlies...            " + str(INIT_PERCENT) +     "%", end="\r")
  INIT_PERCENT += 1
  sleep(0.015)

#Defing Variables
global Args2
global Command
global Args
global DebugMode
DebugMode = "Enabled"
print("Loading Settings Utitlies...        97%", end="\r")

#String Artist
#Splits Input comands into command, args, and args 2 via a space
def StringArtist(CommandIn):
  #Import globals
  global Command
  global Args
  global Args2
  #Parseing
  ParsedCommand = CommandIn.split(" ")
  ParsedCommand.append("Null")
  ParsedCommand.append("Null")
  Command = ParsedCommand[0]
  Args = ParsedCommand[1]
  Args2 = ParsedCommand[2]
print("Loading Settings Utitlies...        98%", end="\r")

#Command Parser
#Interpets Comands and Arguments
def CommandParser(Command, Args, Args2):
  if(Command=="help"):
    print("Displaying Help... ",end="\n")
    print("Command        Args                Function",end="\n")
    print("exit                               Exits the helps         utilty.",end="\n")
    print("help                               Displays This Help     Dialogue",end="\n")
    print("vol            -[0-100/+/-/+10/-10/query]  Sets the volume as     a percenage where zero is off",end="\n")
    print("graphics       -[(B/N/W/query)   Sets the graphics qualitiy     (Best/Normal/Worst)]",end="\n")
    print("_                          Not Implemented",end="\n")
    print("debug          -[E/D/query]      Not Implemented",end="\n")
  elif(Command=="exit"):
    print("Exiting to Program...")
    sys.exit(000)
  elif(Command=="vol"):
    print("Not Implemented")
  elif(Command=="graphics"):
    print("Not Implemented")
  elif(Command=="_"):
    print("Not Implemented")
  elif(Command=="debug"):
    print("Not Fully Implemented")
    if(Args=='-E'):
      DebugMode =="Enabled"
    elif(Args=="D-"):
      DebugMode == "False"
    elif(Args=="-query"):
      print(str(DebugMode)
    else:
      print("Argument Error.  For a valid list of commands, type     'help'")
  elif(Command=="Null"):
    sys.exit("Input may not have a value of 'Null'.  Program Error Code     #201")
  elif(Command==""):
    print("To exit settings and return to your program type exit")
  else:
    print("Command not reconized.  To refer to a refernce list, type     'help'.")
print("Loading Settings Utitlies...        99%", end="\r")

def Main():
  print("\nReturing to Settings Utily...")
  #Import global variables
  global Command
  global Args
  global Args2
  #Main
  print("Enter Command Below or type help for help.")
  #CommandIn=input()
  StringArtist(input())
  CommandParser(Command, Args, Args2)
  #command = "NUll"
  #Args = "Null"
  #Args2= "Null"
print("Loading Settings Utitlies...        COMPLETE", end="\n")
#Debuger
if(DebugMode=="Enabled"):
  while True:
    Main()

Why did a large comparison become 1 line of assembler code?

Following a suggestion in a comment here, I'm trying to understand how does Compiler Explorer work. My input is the following piece of code:

int main() {
    double x,y,x0,y0,x1,y1;
    x = 10;
    y = 10;
    x0 = 5;
    y0 = 5;
    x1 = 15;
    y1 = 15;
    if (x > x0 && x < x1 && y > y0 && y < y1)
        return 1;
    return 0;
}

The result is:

    mov     eax, 1
    ret

I have learned the basics of assembler many years ago, but I don't know if, or how, this makes any sense. Does it? (What I was trying to find is if adding an "else" between the two returns would have any difference in performance. According to this site, it doesn't. But am I getting it right?)

Performance for compound boolean vs. unlikely/likely

Is doing this faster?:

return m_bVisible && (_colorTransform.alphaTransform > 0 || _colorTransform.colorOffsetTransform.a > 0) && (!_masked || _maskVisitable);

Than doing this?:

if (UNLIKELY(_colorTransform.alphaTransform == 0 && _colorTransform.colorOffsetTransform.a == 0))
{
    return false;
}

if (UNLIKELY(_masked && !_maskVisitable))
{
    return false;
}

return m_bVisible;

Doing a lot of minor optimizations which have improved framerate performance significantly for our game, here's one that I'm unsure of. I'm ok with getting 0.01% performance gain since after doing 100 of these optimizations, I've been able to improve performance quite significantly(30-40%). Asking about the use of UNLIKELY optimization vs. just the compound boolean. Short circuiting isn't very easy to do in this particular expression.

It's saying there is a building mistake but I don't see it. Can you?

I am doing this two exercises for an assignment.

First exercise is ok but the second one is not running.It's saying there is a building error, but I checked and double checked and couldn't find it.

Can you see what is wrong in the code?

Thanks a lot for you help.

1.Write a program that accepts a time (24 hour clock) in hours and minutes and converts it to 12 hour clock time. Output should be in the format hours: minutes.

#include<iostream>
using namespace std;
int main ()
{
double hr24,min,hr12;
cout<<"What is the hour? ";
cin>>hr24;
cout<<"What is the minute? ";
cin>>min;
if(hr24>=12){
hr12=hr24-12;
}
else{
hr12=hr24;
}
cout<<"The time is "<<hr12<<" : "<<min<<"\n";
system ("pause");
return 0;
}

2.Modify the above program so that it first validates the time entered before it performs the conversion. An appropriate error message should be output if the time is invalid.

#include<iostream>
using namespace std;
int main ()
{
double hr24,min,hr12;
cout<<"What is the hour? ";
cin>>hr24;
cout<<"What is the minute? ";
cin>>min;
if(hr24>23||hr24<0||min<0||min>59)
{
cout<<"Error! \n";
}
else if(hr24>=12){
hr12=hr24-12;
cout<<"The time is "<<hr12<<" : "<<min<<"PM \n";
}
else
{
hr12=hr24;
cout<<"The time is "<<hr12<<" ; "<<min<<"AM \n";
system ("pause");
return 0;
}

JavaScript If Else errors

So i have this little problem with my If Else structure. When i put in an correct star for example "Vega", the costellation shows me that it is false ("Error") while it needs to show me "Lyra". Click here to see my code.

Conditional if statement or loop?

I'm new in swift and I'm trying to add a feature in a game where I want to add lives and in order to do that I want to create an if statement (or a loop) where I say that if the answer is wrong for 5 times then the game ends. What can I do? If you want you can even send me something I can study where it's explained in a clear way.

xquery for loop and if condition and should only return the first value

I am trying to write an xquery which has if inside a for loop. Below is my request

<PersonIdentifiers> 
<PIR  PersonID="1834040001" IDType="N/A" IDNumber="NA" PrimaryID="true" Version="2" IdentiferFormat=""/> 
<PIR  PersonID="111111111" IDType="WEB" IDNumber="abc" PrimaryID="false" Version="3" IdentiferFormat=""/> 
<PIR  PersonID="222222222" IDType="N/A" IDNumber="xyz" PrimaryID="false" Version="4" IdentiferFormat=""/> 
<PIR  PersonID="333333333" IDType="WEB" IDNumber="aaaaaa" PrimaryID="false" Version="5" IdentiferFormat=""/> 
 <PIR  PersonID="444444444" IDType="WEB" IDNumber="aaaaaa" PrimaryID="false" Version="6" IdentiferFormat=""/> 
</PersonIdentifiers> 

What I want in the response is just 1 or the first "IDNumber" of the row where IDType=WEB I am currently using below xquery which has for loop to go through the array and return me value if IDType=WEB. But Ia m not bale to stop after the first successful value. How can i achieve that?

My current xquery:

        <ns2:account>

        <acc:persons>
            <acc:person>
                <acc:personID>{fn:data($PersonMaintenanceResponse/ns1:PersonIdentifiers/ns1:PIR/@IDType)}</acc:personID>
                {
                for $PIR at $position in $PersonMaintenanceResponse//ns1:PersonIdentifiers/ns1:PIR
                return
                if($PersonMaintenanceResponse//ns1:PersonIdentifiers/ns1:PIR[$position]/@IDType='WEB')
                then
                    if ($PersonMaintenanceResponse/ns1:PersonIdentifiers/ns1:PIR[$position]/@IDNumber)
                    then <acc:ID>{fn:data($PersonMaintenanceResponse/ns1:PersonIdentifiers/ns1:PIR[$position]/@IDNumber)}</acc:ID>
                    else ()
                else
                ()
                }

            </acc:person>
        </acc:persons>
    </ns2:account>

Response from my xquery

  <ns2:account>
<acc:persons xmlns:acc="***************">
  <acc:person>

    <acc:ID>abc</acc:ID>
    <acc:ID>aaaaaa</acc:ID>
    <acc:ID>aaaaaa</acc:ID>

  </acc:person>
</acc:persons>

Expected Response is, just to get the first ID , we do not need otehr ids, how can i stop after getting 1st id

  <ns2:account>
<acc:persons xmlns:acc="***************">
  <acc:person>
     <acc:ID>abc</acc:ID>
  </acc:person>
</acc:persons>

Issue with including if statement in bash script

I am pretty new to bash scripting. I have my bash script below and I want to include an if statement when month (ij==09) equals 09 then "i" should be from 01 to 30. I tried several ways but did not work.

How can I include an if statement in the code below to achieve my task.? Any help is appreciated.

Thanks.

#!/bin/bash
        for ii in 2007 
        do
        for i in 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 #Day of the Month
        do
        for ij in 09 10 # Month
        do
         for j in 0000 0100 0200 0300 0400 0500 0600 0700 0800 0900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900 2000 2100 2200 2300
         do
         cdo cat DAS_0125_H.A${ii}${ij}${i}.${j}.002_var.nc outfile_${ii}${ij}${i}.nc
         done
        done
        done
        done

Objective C, If: a button is not equal to (blank)

I need to figure out how to code an if statement for when a Button's title is NOT a certain string. I already know that to code for if a Button's title IS a certain string, it looks like this:

if ([topLEFT.titleLabel.text isEqualToString:@"Choose for X"])

But, simply changing the "isEqualToString" to "isNotEqualToString" will not work. What would a simple solution be?

Excel VBA If Or Statement with integer and string?

The code below detects the value of 0 in excel and writes "0 Value" on the powerpoint it's exporting to, but it won't detect and do the same for the string value of "TEST WORDS" in excel. Instead it continues to write "NOT 0". What could I fix to get rid of the error?

        If Sheet1.Range("C" & Row).Value = 0 Or Sheet1.Range("C" & Row).Text = "MOB Speaker replacement" Then
            ppSlide2.AddTextbox(msoTextOrientationHorizontal, 855, 0, 105, 150).TextFrame.TextRange.Text = "0 Value"

    Else
            ppSlide2.AddTextbox(msoTextOrientationHorizontal, 855, 0, 105, 150).TextFrame.TextRange.Text = "NOT 0"
    End If

JavaScript - 3 Boolean operators in If statement

Okay, so there are three boolean values. Only one boolean value can be true at a time. If one of the boolean values is already true, it should stay true if the condition hits it, it should not revert back to false. Note that activeCrate1 should be true by default.

When the condition hits activeCrate2, it is true and all other boolean cases are false.

When the condition hits activeCrate3, it is true and all other boolean cases are false.

But how do I hit activeCrate1, and return it again to true, and all other boolean values should be false?

And for example, if the condition hits activeCrate1 which is already True, it should stay true and nothing should change. How can I make it work that way?

Two questions in total, but need to be implemented in the same code.

The code goes like this:

activeCrate1: true,
activeCrate2: false,
activeCrate3: false

if (state.activeCrate2 === false ) {
    state.activeCrate2 = true
    state.activeCrate1 = false;
    state.activeCrate3 = false;
  } else if (state.activeCrate3 == false){
    state.activeCrate3 = true;
    state.activeCrate1 = false;
    state.activeCrate2 = false;

Why do i keep getting a bad input error regarding this string statement?

I have a syntax error that I am confused on within my python code

deliveryValue= input("Is this order for delivery? Y/N")
float (DeliveryTime = 0)
str (zipcode=none)
float (DeliveryFee =0)
if deliveryValue == 'y' or 'Y':
    address = input ("what is the delivery address?")
    zipcode = input ("What zipcode is the address in?")
        if zipcode == 84041:
            DeliveryTime = 30
            DeliveryFee = 6.50
        else:
            DeliveryTime = 45
            DeliveryFee = 7.50
else:
    DeliveryFee = 0

the if zipcode == 84041: line comes out with an error, however I have tried placing ' ' and " " around it and still has the same error. Am i writing this correctly?

Thanks in advance.

How do I use strings from user input in an if-else statement that leads to picking 4 random numbers 1-56?

I've tried looking all over for a way to do this, and this is all that I've come up with so far.

import java.util.Scanner;

public class RandomPerkSelector {

public static void main(String [] args){
Scanner userInput = new Scanner(System.in);
System.out.println("What are you playing as?");

I'm a little new to this, so I may have worded it wrong, but the 2 specific roles I can choose are killer and survivor. If the user inputs "killer", I want the program to pick 4 random numbers of 1-51, and if the user inputs "survivor", I want the program to pick 4 random numbers of 1-56.

Powershell: recurse directories for where a file extension exists if Exist write out comman if not run a command

Specifically, I have a directory with a ton of other random named directories (Not really random but that's not important) in those directories some contain files with .tsidx extension, some do not. the directories which contain the tsidx extension I want to output to screen that it already exists. the ones that do NOT I want it to output it doesn't exist then run a command to build the tsidx files against the directory using an executable provided by vendor of a program. here is what is in my code so far:

$index = Read-Host "Enter the Index Name" #This is to receive a directory  location from user
$loc = "F:\thawdb\splunk\$index\thaweddb"
$dir = dir $loc

cd "d:\splunk\bin"
foreach ($d in $dir) 
{
   if (gci -dir | ? { !(gci $_ -file -recur -filter *tsidx) })
      {
         Write-host -foregroundcolor Yellow "TSIDX Exists"
      }

writes out the directory contains files and doesn't need rebuilt

      else
     {
         write-host -Foregroundcolor Green "Running Rebuild command against $loc\$d" | .\splunk.exe rebuild $loc\$d 
      }

writes out rebuild is necessary and runs the rebuild

}

Transferring value from another column in ifelse within dplyr::mutate

I have dataframe dd (dput at bottom of question):

# A tibble: 6 x 2
# Groups:   Date [5]
  Date     keeper
  <chr>    <lgl> 
1 1/1/2018 TRUE  
2 2/1/2018 TRUE  
3 3/1/2018 FALSE 
4 4/1/2018 FALSE 
5 3/1/2018 TRUE  
6 5/1/2018 TRUE 

Note it is already grouped by Date. I'm trying to create another column that will turn "keeper" to TRUE if there's only one row in the group, and otherwise keep the value of keeper. That seemed fairly simple, but when I tried this, I got the following result:

dd %>% mutate(moose=ifelse(n()==1,TRUE,keeper))
# A tibble: 6 x 3
# Groups:   Date [5]
  Date     keeper moose
  <chr>    <lgl>  <lgl>
1 1/1/2018 TRUE   TRUE 
2 2/1/2018 TRUE   TRUE 
3 3/1/2018 FALSE  FALSE
4 4/1/2018 FALSE  TRUE 
5 3/1/2018 TRUE   FALSE
6 5/1/2018 TRUE   TRUE 

Note that rows 3 and 5 have the same Date, so they should have just retained what's in keeper for the new column -- but they both got turned to FALSE. What am I missing?

Here's the dput for the dataframe:

dd<-structure(list(Date = c("1/1/2018", "2/1/2018", "3/1/2018", "4/1/2018", 
"3/1/2018", "5/1/2018"), keeper = c(TRUE, TRUE, FALSE, FALSE, 
TRUE, TRUE)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L), vars = "Date", drop = TRUE, indices = list(
    0L, 1L, c(2L, 4L), 3L, 5L), group_sizes = c(1L, 1L, 2L, 1L, 
1L), biggest_group_size = 2L, labels = structure(list(Date = c("1/1/2018", 
"2/1/2018", "3/1/2018", "4/1/2018", "5/1/2018")), class = "data.frame", row.names = c(NA, 
-5L), vars = "Date", drop = TRUE, indices = list(0L, 1L, 2L, 
    4L, 3L, 5L), group_sizes = c(1L, 1L, 1L, 1L, 1L, 1L), biggest_group_size = 1L, labels = structure(list(
    Date = c("1/1/2018", "2/1/2018", "3/1/2018", "3/1/2018", 
    "4/1/2018", "5/1/2018"), keeper = c(TRUE, TRUE, FALSE, TRUE, 
    FALSE, TRUE)), class = "data.frame", row.names = c(NA, -6L
), vars = c("Date", "keeper"), drop = TRUE, .Names = c("Date", 
"keeper")), .Names = "Date"), .Names = c("Date", "keeper"))

ADDENDUM:

As I continue to play with this dataframe, I discovered that if I first create a column n using add_count, and refer to that column in my ifelse instead of to n(), I get the result I'm looking for. What's causing this? Why isn't n() giving me the same result?

PHP If do something, else do nothing problem

I have a maybe funny question, but I need from my code following:

If something - do that, else - do nothing.

Example code is here:

$page = 'id';
if (get_page($page)) {
   #do something 
} else {
   #do nothing
}

Original code:

$page = '4827';
if (get_page($page)) {
   echo do_shortcode('[shortcode]');
} else {
    // do nothing
}

VBA - EASY: Lock Range (in the same row) when A"counter" is FALSE

Please help me with this easy question:

IF A2 is TRUE I want to lock the Range D2:I2

IF A3 is TRUE I want to lock the Range D3:I3...

IF AxRow is TRUE I want to lock the Range DxRow:IxRow

I have 744 rows (A2:A745) with TRUE or FALSE statements. And when the FALSE statement appears, all the following cells are FALSE. Example: A2 =TRUE ...A22 = TRUE, A23 = TRUE, A24 = TRUE, A25 = FALSE, A26 = FALSE... A745 = FALSE.

Please, what is the problem with my code?

Private Sub Block(ByVal Target As Excel.Range)

Dim xRow As Long
xRow = 2
ThisWorkbook.ActiveSheet.Unprotect Password:="123"
Do Until Cells(xRow, 1).Value = False
If Worksheets("HourlyCount").Cells(xRow, 1).Value = True Then
Range("D" & xRow & ":I" & xRow).Locked = True
End If
xRow = xRow + 1
Loop
ThisWorkbook.ActiveSheet.Protect Password:="123"


End Sub

SublimeText3. Convert IF statement to SWITCH

Is there any way to convert IF statement to Switch in SublimeText?
May be any plugins can help?

If any list item is different from

I have a list:

infos = [shot['first_frame'], shot['last_frame'], shot['duration']]

I need to check if any of those list items is different from 0 or None.

I have the following "if any" solution but I can't figure out how to add the "different from" part.

if any(value in ['', '0'] for value in infos):

Why are these two If-statements not the same?

I just started learning Javascript. Currently I'm taking an online course and I just ran into my first problem I do not understand.

I want to check how many guesses I still have in a Hangman game:

const Hangman = function (word, remainingGuesses) {
this.word = word.toLowerCase().split('')
this.remainingGuesses = remainingGuesses
this.guessedLetters = []
}

Hangman.prototype.getPuzzle = function () {
let puzzle = ''

this.word.forEach((letter) => {
    if (this.guessedLetters.includes(letter) || letter === ' ') {
        puzzle += letter
    } else {
        puzzle += '*'
    }
})

return puzzle
}

the correct If statement in the video is this:

Hangman.prototype.makeGuess = function (guess) {

const isUnique = !this.guessedLetters.includes(guess)
const isBadGuess = !this.word.includes(guess)

if (isUnique) {
    this.guessedLetters.push(guess)
}

if (isUnique && isBadGuess) {
    this.remainingGuesses--
}
}

But this is below here how I wrote the if statement:

Hangman.prototype.makeGuess = function (guess) {


if (!this.guessedLetters.includes(guess)) {
    this.guessedLetters.push(guess)
}

if (!this.guessedLetters.includes(guess) && !this.word.includes(guess)) {
    this.remainingGuesses--
}
}

The remaining guesses are not calculating correctly, if i do the if statements with the second way. Can you please tell me what is the difference?

TypeError: bad operand type for unary +: 'unicode' python concatenation

I am trying to use a print statement to print out certain elements. I keep facing a TypeError when doing so. The error shows :

File "data.py", line 58, in main
print ("Current file_size" , + data_current['File Name'], "does not match previous file_size" , + data_previous['File Name'])

TypeError: bad operand type for unary +: 'unicode' My code is as follows :

if data_current['File Name'] == data_previous['File Name']:  # If file names match

   if data_current['File Size'] != data_previous['File Size']: # If file sizes do not match
                data_current = json.loads(cd)
                data_previous = json.loads(pd)
                print ("Current file_size" , + data_current['File Name'], "does not match previous file_size" , + data_previous['File Name'])

Can I execute a method when an input box gets to a certain length?

I have an input box that takes a string. Can I execute a method (in vue.js) when the length of the string gets to a certain number?

something like

<input v-if="inputBox.length == 6 THEN runme()"...>

is it better to use multiple ifs in for loop or a for loop for each if

I have the following scenario. I have large amounts of data of the following schema

{
  a: number,
  b: number,
  c: number,
  d: number
}

Say there are ~20k records of this structure. I have to do some calculations with each of the field

Calculations with a and b are mandatory, but c and d are not. I know outside of the for loop itself if I have to perform calculations on c and d or not.

So what is the optimised way to handle this situation?

option1:

workOnC = true
workOnD = false

for (i=0; i< 20k, i++) {
  work on a
  work on b
  if(workOnC) work on c
  if(workOnD) work on d
}

or

option 2

workOnC = true
workOnD = false

for(i=0;i<20k;i++) {
  work on a
  work on b
}

if(workOnC) {
 for(i=0;i<20k;i++) {
   work on c
 }
}

if(workOnD) {
 for(i=0;i<20k;i++) {
   work on d
 }
}

jeudi 29 novembre 2018

Combine conditions in an inner if statement with the outer else statement - C#

I have three conditions (a, b, c) to be checked that's supposed to run on the folliwing syntax:

if (conditionA)
{
    if (conditionB && conditionC)
    {
        // Execute();
    }
}
else if (conditionC)
{
    // Execute();
}

Better still, can these conditions be simplified to one line, so that Execute() will end up in one set of braces? Thanks.

How can I make sure that the entered input matches the array index in order to output the right solution?

So basically, I am trying to output both the top film for a specific year and the total income that movies made that year. Both of my methods are not working correctly and I am especially having trouble in getting the year that was input to match with the year that the movies have in the arrays in order to output the total income and top film of that year.

Here is the getInput.getUserInput()

    public static int getUserInput(int minYear, int maxYear) {
        int year = 0;
        boolean keepLooping = true;
        Scanner input = new Scanner(System.in);
        while (keepLooping) {
            System.out.printf("\nEnter a year from %s - %s:", minYear, maxYear);
            year = input.nextInt();
            if (year < minYear || year > maxYear) {
                System.out.printf("Invalid entry . . .");
            } else {
                keepLooping = false;
            }
        }
        return year;
    }

Here is the class

        public class Films {
            private String filmTitle;
            private double filmIncome;
            private int premiereYear;

        Films(String title, double income, int year) {
            filmTitle = title;
            filmIncome = income;
            premiereYear = year;

        }

        public String getFilmTitle() {
            return filmTitle;
        }

        public void setFilmTitle(String filmTitle) {
            this.filmTitle = filmTitle;
        }

        public double getFilmIncome() {
            return filmIncome;
        }

        public void setFilmIncome(double filmIncome) {
            this.filmIncome = filmIncome;
        }

        public int getPremiereYear() {
            return premiereYear;
        }

        public void setPremiereYear(int premiereYear) {
            this.premiereYear = premiereYear;
        }

    }

Here is the file that runs the program

public static void main(String[] args) {
        Films[] f = new Films[8];
        f[0] = new Films("Frozen", 1290.0, 2013);
        f[1] = new Films("The Lion King", 968.4, 1994);
        f[2] = new Films("Zootopia", 1023.7, 2016);
        f[3] = new Films("Incredibles 2", 1240.3, 2018);
        f[4] = new Films("Finding Dory", 1028.5, 2016);
        f[5] = new Films("Shrek 2", 919.8, 2004);
        f[6] = new Films("The Jungle Book", 966.5, 2016);
        f[7] = new Films("Despicable Me 2", 970.7, 2013);

        int yearEntered = getInput.getUserInput(1991, 2018);
        System.out.printf("\nThank you received %s", yearEntered);

        Films total = getTotalIncome(f, yearEntered);
        System.out.printf("\nThe total amount made for %s was $%2.2f", yearEntered, total.getFilmIncome());

        Films top = getTopFilm(f, yearEntered);
        if (top == null) {
            System.out.printf("0");
        } else {
            System.out.printf("\nThe greatest income made by a movie in %s was %s at $%2.2f", yearEntered,
                    top.getFilmTitle(), top.getFilmIncome());
        }

    }

    private static Films getTotalIncome(Films[] f, int yearEntered) {
        Films totalIncome = null;
        double add = 0;
        for (int i = 0; i < f.length; i++) {
            if (f[i].getPremiereYear() == yearEntered) {
                add += f[i].getFilmIncome();
                totalIncome = f[i];
            }

        }
        return totalIncome;

    }

    private static Films getTopFilm(Films[] f, int yearEntered) {
        Films topFilm = null;
        double max = 0;
        for (int i = 0; i < f.length; i++) {
            if (f[i].getPremiereYear() != yearEntered) {
                continue;
            }
            if (f[i].getFilmIncome() > max) {
                topFilm = f[i];
            }
        }
        return topFilm;
    }

Lavarel PHP for loops and if statements

Currently trying to build a for loop to read through my $userSkills array and then using an if statement to print out specific text based on it.

This is how the code looks like

@for ($x = 1; $x < $skillCount; $x++) {
    @if($userSkills[$x] = '{ 66; }')
        <span>Hi</span>
    @else
        <span></span>
    @endif                        
}
@endfor

And in my array it would be {AA, 66, 67, 69} So I wanted to make it print out as such

Hi 67 69

However the output looks like this

{ Hi } { Hi } { Hi } 

Check if a number inputted in an "EditText" is in an array - Android Studio Java

I want to know if a number that a user inputted into an "EditText" actually exists inside an array, here is my current code:

 final String[] numberArray = {("1"), ("2"), ("3"), ("4"), ("5")};


public void startGame(View v) {

    if (Arrays.asList(agesArray).contains((text))) {

        Outputs1.setText("You typed in: " + text + ", which is correct!");

    } else {

        Outputs1.setText("Please type in a number 1-5.");

When the users type in the number, it checks if the number exists in an array by using an If-Statement, and if it does it displays a message.

Sadly, this does not work, and the other questions and answers also did not work either.

Any response will be great.

Why isn't the y-coordinate property updating?

I've been using CodeCombat for learning. With this code here I've been stuck for a week and nobody can help me. I'm trying to understand why the Y-coordinate property (particularly hero.pos.y) isn't updating. It doesn't register as changed although my hero moves to the position x:18 y:24. Everyone who's willing to help is welcome to reply.

hero.moveXY(18, 40);
while (true) {
hero.say("starting while");
var enemy = hero.findNearestEnemy();
var friend = hero.findNearestFriend();
var item = hero.findNearestItem();
if (enemy) {
    if (enemy.type == "ogre" && hero.canCast("force-bolt")) {
        hero.cast("force-bolt", enemy);
    } else if (enemy.type == "brawler" && hero.canCast("shrink")) {
        hero.cast("shrink", enemy);
        hero.moveXY(34, 24);
    } else if (enemy.type == "scout" && hero.canCast("poison-cloud")) {
        hero.cast("poison-cloud", enemy);
        hero.moveXY(50, 24);
    }
} else if (friend) {
    if (friend.type == "soldier" && hero.canCast("heal")) {
        hero.cast("heal", friend);
    } else if (friend.type == "goliath" && hero.canCast("grow")) {
        hero.cast("grow", friend);
    } else if (friend.type == "paladin" && hero.canCast("regen")) {
        hero.cast("regen", friend);
    }
} else if (item) {
    if (item.type == "potion") {
        hero.say("Potion! Yay!");
        hero.moveXY(item.pos.x, item.pos.y);
        hero.moveXY(66, 24);
    } else if (item.type == "poison") {
        hero.say("darn it! poison!");
        hero.say("help me");
    }
} else if (hero.pos.y === 40) {
    hero.say("moving down");
    hero.moveXY(hero.pos.x, hero.pos.y - 16); //this works
    hero.say("At this point I SHOULD have changed my hero.pos.y to 24");
} else if (hero.pos.y === 24) {//here it works only with x
    hero.say("moving to the steel door");
    hero.moveXY(hero.pos.x + 16, hero.pos.y + 16);
} else if (hero.pos.y !== 24) {
    hero.say("My Y-position hasn't changed!");
    hero.moveXY(hero.pos.x + 16, hero.pos.y + 16);
}

}

missing value in if condition

I created this function:

quadPol <- function(f,lb,rb,tau) {
  tetalower <- lb
  tetaupper <- rb
  tetabest <- 0.5 * (tetalower + tetaupper)
  tetanew <- 0.5 * (f(tetaupper) * (tetalower^2 - tetabest^2) + f(tetabest) *
                      (tetaupper^2 - tetalower^2) + f(tetalower) * (tetabest^2 -
                       tetaupper^2))/(f(tetaupper) * (tetalower - tetabest) 
                       + f(tetabest) * (tetaupper - tetalower) + f(tetalower) * 
                       (tetabest - tetaupper))
  while (abs(tetaupper - tetalower) >= tau * (abs(tetabest) + abs(tetanew))) {
    if (f(tetanew) < f(tetabest)) {
      z <- tetanew
      tetanew <- tetabest
      tetabest <- z
    }
    if (tetanew < tetabest) {
      tetalower <- tetanew
    }
    else {
      tetaupper <- tetanew
    }
    tetaaponew <- tetanew
    tetanew <- 0.5 * (f(tetaupper) * (tetalower^2 - tetabest^2) + f(tetabest) *
                      (tetaupper^2 - tetalower^2) + f(tetalower) * (tetabest^2 -
                       tetaupper^2))/(f(tetaupper) * (tetalower - tetabest) 
                       + f(tetabest) * (tetaupper - tetalower) + f(tetalower) * 
                      (tetabest - tetaupper))
    if (tetanew == tetaaponew || tetanew <= tetalower || tetanew >= tetaupper) {
      return(tetabest)
    }
  }
  return(tetabest)
}



quadPol(cos,2,4,0.00001)
quadPol(abs,-1,1,0.00001)

the first execution with the cosinus works well, but the second doesn't, and it says:

Error in if (tetanew == tetaaponew || tetanew <= tetalower || tetanew >=  : 
  missing value where TRUE/FALSE needed
enter code here

how is it possible that the value is missing there. Looked over it like ten times. Thank you.

MySQL call function and procedure from a trigger

I made a function and procedure successfully, however when I try to call them from my trigger I get errors I don't know how to fix.. Can someone please help me :)

My function and procedure:

CREATE FUNCTION IsInBooking(id INT) RETURNS BOOLEAN BEGIN RETURN EXISTS(SELECT Customer_ID FROM booking WHERE Customer_ID = id); END

CREATE PROCEDURE DeleteRowFromBooking(IN id INT) BEGIN DELETE FROM booking WHERE Customer_ID = id; END

My trigger with error:

CREATE TRIGGER CustomerChargeback FOR EACH ROW BEGIN IF (CALL IsInBooking(Customer_ID)) THEN CALL DeleteRowFromBooking(Customer_ID) END IF; END

Basically what I want to do, is to delete any row with the same Customer_ID in the booking table if the row with the corresponding ID in the payment table is deleted.

Thanks so much!!!

xquery to check xquery how to check if value of boolean variable is true

i am writing a xquery in which I have to check if the value of anattribute is true. The attribute / element is defined as Boolean. I tried multiple options but I am not able to get the correct value, the logic works for other elements but not for 'MainCustomer' since it is defined Boolean. How can I write the xquery for this?

Below is the example of my request:

<Maintenance xmlns="*******">
<AccountPersons>
  <APH AccountID="56987" LastFinancialRespSwitch="Y" LastMainCustomerSwitch="Y" LastPersonID="987569" QuickAddSwitch="false"/>
  <APR AccountID="98759" AccountRelationshipType="MIN" BillAddressSource="PER" PersonID="000000" MainCustomer="true"></APR>
  <APR AccountID="123456" AccountRelationshipType="MAIN" BillAddressSource="PERSON" PersonID="123456" MainCustomer="false"></APR>
</AccountPersons>
</Maintenance>

I am using the if statement inside for loop.APR is an array. I want to get the value of BillAddressSource from only those APR where MainCustomer="true" below xquery doesn't work it gives me the values from all the APR.

 if (fn:boolean($MaintenanceResponse/ns1:AccountPersons/ns1:APR[$position]/@MainCustomer))
    then
       <acc:data>      
               {if ($MaintenanceResponse/ns1:AccountPersons/ns1:APR[$position]/@BillAddressSource)
                then <acc:addressSource>{fn:data($MaintenanceResponse/ns1:AccountPersons/ns1:APR[$position]/@BillAddressSource)}</acc:addressSource>
                else ()
            }
       </acc:data> 

Another xquery I tried is, this gives me syntax error

        if ($MaintenanceResponse/ns1:AccountPersons/ns1:APR[$position]/@MainCustomer='true')
    then
       <acc:data>      
               {if ($MaintenanceResponse/ns1:AccountPersons/ns1:APR[$position]/@BillAddressSource)
                then <acc:addressSource>{fn:data($MaintenanceResponse/ns1:AccountPersons/ns1:APR[$position]/@BillAddressSource)}</acc:addressSource>
                else ()
            }
       </acc:data>  

Please help me find a correct if statement . Thanks in advance

Prompting User to Guess A Number Function [duplicate]

This question already has an answer here:

The program is suppose to generate a random number between 0 and 10 and then prompt the user to guess it within five tries. But the program continuously outputs " You guessed incorrect". I've tried it out various times and it just keeps printing " You guessed incorrect" repeatedly for five tries. How do I prompt it to say " You guessed Correct" when the user has the right number?

import random
def guess():
    randNum = random.randint(0,10)
    count = 0
    while count < 5:
        count = count + 1
        number1 = input("Guess A Number")
    if number1 != randNum:
       print(" You Guessed incorrect")
    else:

        print(" You are Correct")

SAS Keep if all, else

I have a sas dataset that looks like the following:

ID    Day    Instance1  Instance2
1      1         N         Y
1      2         N         Y
1      3         Y         N
1      4         N         N
2      1         N         Y
2      2         N         N
2      3         N         Y  
2      4         N         N

and I would like to keep instances based on whether or not they are marked yes even once. Else it would be marked no. My desired output would be:

ID   Instance1  Instance2
1         Y         Y
2         N         Y

What I'm trying pseudo code:

DATA test, 
    set.test, 
    by ID;
       if all instance1 = N then N, else yes; 
       if all instance2 = N then N, else yes;
RUN; 

ifelse value specified amount less than other value then

Apologies all, I'm new to R and am stumped on something that I am sure is simple!

I have this working code: lr5yr$"LR_3Y_>10%_over_5Y" <- ifelse(lr5yr$lr >= 0.65 & lr5yr$lr - lr5yr$lr5 < lr5yr$lr ,"Y","N")

Effectively all I need is at the end to specify how much less the final calculation is.

In my formula the end is show a Y if the value of lr-lr5 is less than lr. But what I need is for it to show a Y only if the amount less is greater than or equal to 0.1

So, if lr-lr5 is 0.1 or greater less than lr show Y.

Python 2: Statement to check http link and if it finds match move to the next one

So I have following issue:

I have list of domains written in such way:

cat lista-linkow 
http://wp.pl
http://sport.org
http://interia.pl
http://mistrzowie.org
http://detektywprawdy.pl
http://onet.pl

My script is taking each of these links and attaches it to http://archive.org domain, creating list of links similar to this:

cat output
https://web.archive.org/web/20180101033804/http://wp.pl
https://web.archive.org/web/20181121004239/http://wp.pl
[...]
https://web.archive.org/web/20180120205652/http://sport.org
https://web.archive.org/web/20180220185027/http://sport.org
[...]
https://web.archive.org/web/20180101003433/http://interia.pl
https://web.archive.org/web/20181119000201/http://interia.pl
etc...

(of course [...] symbolizes plenty of similar links)

Right now my script is going through this entire list and finds phrase which I am giving as a argument. The problem is, that I need it to take only one unique link (so, interia.pl/... or wp.pl/... or mistrzowie.org/.... etc and if phrase matches there, it moves to the next item from the list.

So, if it finds phrase "Katastrofa" in list of links in "output" file:

python vulture-for-loop-links.py Katastrofa
SUKCESS!! phrase is here:  https://web.archive.org/web/20180101033804/http://wp.pl

http://wp.pl

SUKCESS!! phrase is here:  https://web.archive.org/web/20180113000926/http://wp.pl

http://wp.pl

...I would like it to go to next item in "lista-linkow", so "http://sport.org" and search it there... Here is what I got so far:

from __future__ import print_function
from sys import argv
from selenium import webdriver
import re
import requests
from bs4 import BeautifulSoup


# Wyzerowanie pliku z linkami output:

skrypt, fraza = argv
plik = open("output", "w")
plik.truncate()

# Otwiera liste linkow, i wrzuca ja do archive.org.

lista = open("lista-linkow", "r")
txt = lista.readlines()
driver = webdriver.Chrome()
for i in txt:
    url = 'https://web.archive.org/web/*/{}'.format(i)
    driver.get(url)
    driver.refresh()


    driver.implicitly_wait(1000) # seconds

    captures = driver.find_elements_by_xpath("""//*[@id="wb-calendar"]/div/div/div/div/div/div/div/a""")

# Lapie linki (captures) i zapisuje w wyczyszczonym wczesniej pliku "output"
    for capture in captures:
        stronka = capture.get_attribute("href")
        with open('output', 'a') as plik:
            plik.write(stronka + "\n")
            plik.seek(0)
            plik.close()
#        print(stronka, sep='\n')

# Dla pojedynczej strony z pliku "lista-linkow", otwartej jako "txt":

for elem in txt:
    f = open('output', 'r')
    f.seek(0)
    f2 = f.readlines()

    # Dla kazdej odczytanej linii z pliku output odszukaj frazy:

    for i in f2:
        r = requests.get(i)
        soup = BeautifulSoup(r.text, 'html.parser')
        boxes = soup.find_all(True, text=re.compile(fraza, re.I))


        # Dla odszukanej frazy (d) wypisz link z pliku "output" i podaj link (i)

        for d in boxes:
            if len(i) == 0:
                print ("Fail, phrase not found", i)
            else:
                print ("SUKCESS!! phrase is here: ", i)
                print(elem) 
driver.quit()

How to add an array twice by two TRUE conditions?

this is my code:

import numpy as np
from scipy.ndimage.interpolation import shift

B = np.array([[0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0]])

F = np.array([[0, 0, 0, 0, 0],
          [0, 0, 0, 0, 1],
          [0, 0, 0, 0, 1],
          [0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0]])

M = np.array([[1, 2, 1, 2, 1],
          [1, 2, 1, 2, 1],
          [1, 2, 1, 2, 0],
          [1, 2, 1, 2, 1],
          [1, 2, 1, 2, 1]])

if F[2, 4] == 1:
    B = np.add(F, M)

if F[1, 4] == 1:
    M_shift = shift(M, (-1, 0), cval=0)
    B = np.add(M_shift, F)

print(B)

I want to add M to B if the condition for F is true. In this example both if-conditions are true and i thought that my code will add two times M to B. But apparently it's not working? What is wrong?

Thanks in advance.

Show all the data from the given date through php condition

I am generating a data from the database to html table using php. I want to output with php condition using the student joining date.

I want to run a condition where you take the j.date and anything before should have - and after should have a 'Pay' button which holds the studentid

+---------+------------+-----+-----+------+------+------+-----+
| Student |   J.date   | Jan | Feb | Mar  | Apr  | May  | ... |
+---------+------------+-----+-----+------+------+------+-----+
| John    | 25-03-2018 |   0 |   0 | 2000 |    0 | 1750 | ... |
| Michael | 10-04-2018 |   0 |   0 |    0 | 5000 |    0 | ... |
+---------+------------+-----+-----+------+------+------+-----+

Something like this

+---------+------------+-----+-----+------+------+------+-----+
| Student |   J.date   | Jan | Feb | Mar  | Apr  | May  | ... |
+---------+------------+-----+-----+------+------+------+-----+
| John    | 25-03-2018 |   - |   - | 2000 | Pay  | 1750 | ... |
| Michael | 10-04-2018 |   - |   - |    - | 5000 | Pay  | ... |
+---------+------------+-----+-----+------+------+------+-----+

Nested OR statements in Google Sheets

Currently I'm trying to construct a nested OR statement in Google sheets if any number of items are true, but they return different values based on another IF statement. Right now an example of my code is:

IF(OR($AW2="email1@website.com", $AW2="email2@website.com", $BB2="email1@website.com", $BG2="email1@website.com", IF($BK3="X","Message1",IF($BK3="Y","Message2",IF($BK3="Z","Message3","")))),"")

Essentially I'm trying to say if email1 has signed off on a document in any cell, or if email2 has signed of on the document in AW2, then return the message code based on what is in BK3.

I've attached a sample sheet.

https://docs.google.com/spreadsheets/d/14AiHNpWQcmIJIvPxqb4j2HHgNC8C1cF9YZOe5il14Ro/edit?usp=sharing

Webstorm suggesting I flip if-else, what are the benefits of doing so?

I've seen this happen a few times in Webstorm. Here's an example of a time when it happens. I have a module for logging messages sent to a chatbot and the responses. The log() function looks like this:

log: function(senderID, type, event) {
    if (type === 1) {
        // Event
        logDate = datetime.parseUnixDBDate(event.timestamp);
        logTime = datetime.parseUnixTime(event.timestamp);
        logText = handleText(event.message.text);
        table = "interactions";
        columns = ["fbid", "date", "time", "event"];
        logType = "User input";
    } else {
        // Response
        logDate = datetime.getDBDate();
        logTime = datetime.getTime();
        logText = handleText(event);
        table = "interaction_responses";
        columns = ["fbid", "date", "time", "response"];
        logType = "Chatbot response";
    }
    values = [`'${senderID}'`, `'${logDate}'`, `'${logTime}'`, `'${logText}'`];
    logSQL = `INSERT INTO ${table} (${columns.toString()}) VALUES (${values.toString()})`;
    database.query(logSQL);
    console.log("%s '%s' logged at %s on %s.", logType, logText, logTime, logDate);
}

In Webstorm, I get a little lightbulb next to the if statement, and if I click the warning it suggests that I should "Flip if-else". If I do this, I then get the SAME warning suggesting I flip the if-else back. Warning looks like this:

Webstorm Warning Message

Is there a reason why this is happening? Should I flip my if-else statement?

How work if statement in perl whit a hashmap argument?

i have this variable:

my %permit = (
        "activity" => '',
        "type" => '',
        "sub_type" => '',
        "status" => '',e
        );

    my $permit;

and before i have tihis if:

if($permit->{activity}){
     print "inside if\n";
}

the question is: when the if statement is execute?

How to optimizize this code? i am noob :d

i have a code

for(int i = 0; i < n; i++)
if ( 1 == arr[i+2-r] and   1 == arr[i+1-r] and 1 == arr[i-r] and  1 == arr[i] and  1 == arr[i-1+r] and  1 == arr[i-2+r])
 {
     arr2 = 1; 
 }

i need help. How to optimizize this code? how to reduce this cut

mercredi 28 novembre 2018

What is difference between if(c == 10) and if(c & 10) in javascript?

I saw if condition like this if(c & 10) and This condition similar to this if(c==10). This is a correct way to write code in javascript?

if statement python for column values

I am attempting to write the following logic in python:

if column A is '123' and column B is '456', then column c = 0

I've tried the following function, but returns an error:

 def testfunc(df):
     if df['columna'] == 123:
         if df['columnb'] ==456:
             df['columnc']=0

 return df
 testfunc()

error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

What am i doing wrong?

Basic Javascript question regarding if else if else

any help would be appreciated. I can't figure out what I'm doing wrong. I know it's probably something simple, I'm learning, just slowly... I have 2 tests of the code I was trying to get to work. It's basically just if else statements and then posting the results in a div. I just can't get it to work. Any advice would be grateful! Thank you.

<html>
<head>
<meta charset="ISO-8859-1">
<title>WindChill</title>
</head>
<script>
    function DetermineDanger(){
        // This function should take in the user input from the textBox with id="windchillTxt"
        // Save the user input in a local variable called windchill, be sure to use parseFloat
        // Then using a conditional structure determine the appropriate warning to display based on windchill
        // The result should be displayed in the <div> with id="displayDiv"

        //test 1
    //var windchill
    //number = parseFloat(document.getElementById('windchillTxt').value);

    //if (windchill <= -60)
    //document.getElementById('displayDiv').innerHTML = 'Extreme Danger, frostbite could occur within 5 minutes';

    //else if (windchill <= -45)
    //document.getElementById('displayDiv').innerHTML = 'Danger, frostbite could occur within 10 minutes';

    //else if (windchill <= -25)
    //document.getElementById('displayDiv').innerHTML = 'Caution, frostbite could occur within 30 minutes';

    //else 
    //document.getElementById('displayDiv').innerHTML = 'Just really cold! Be sure to bundle up!';


    //test 2
        var windchill
        number = parseFloat(document.getElementById('windchillTxt').value);

        if (windchill <= -60) {
        document.getElementById('displayDiv').innerHTML = 'Extreme Danger, frostbite could occur within 5 minutes';
        }

        else {
            if (windchill <= -45) {
            document.getElementById('displayDiv').innerHTML = 'Danger, frostbite could occur within 10 minutes';
        }
        else {
            if (windchill <= -25) {
            document.getElementById('displayDiv').innerHTML = 'Caution, frostbite could occur within 30 minutes';
        }
        else { 
        document.getElementById('displayDiv').innerHTML = 'Just really cold! Be sure to bundle up!';
        }   
       }        
     }
    }

</script>
<body>
<h1>Wind Chill Danger</h1>
Enter windchill:<input id="text" id="windchillTxt"><br>
<!-- Finish the onclick handler with a function call -->
<input type="button" value="Information" onclick="DetermineDanger();">
<hr>
<div id="displayDiv"></div>
</body>
</html>

change value of a radio button based on database value in php

i have a radio button in my form

<input type="radio" id="radio-2" name="radio" checked  onclick="calculate()" >

how to set the radio button value based on database value like

if(db_val==2){
value=50
} else{
value=100
}

How does this if not statement work without parentheses?

When creating a new Windows Service in Delphi, it inserts the following:

if not Application.DelayInitialize or Application.Installing then
  Application.Initialize;

The author didn't bother including parentheses, so I'm trying to wrap my head around this. Only the first part of the statement has not.

I can see this possibly meaning two things:

if not (Application.DelayInitialize or Application.Installing) then

or

if (not Application.DelayInitialize) or Application.Installing then

Based on the context of the particular code, I would expect the first scenario to apply, considering if a service is starting, you don't want it to initialize, but do want it to initialize if it's not installing. However, my testing proved the opposite. At least that's what I've gathered based on the following test:

program TestIfNot;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

var
  Bool1, Bool2: Boolean;

begin
  try
    WriteLn('if not Bool1 or Bool2 then True else False');

    WriteLn('1) False, False');
    Bool1:= False;
    Bool2:= False;
    if not Bool1 or Bool2 then
      WriteLn('True')
    else
      WriteLn('False');

    WriteLn('2) True, False');
    Bool1:= True;
    Bool2:= False;
    if not Bool1 or Bool2 then
      WriteLn('True')
    else
      WriteLn('False');

    WriteLn('3) False, True');
    Bool1:= False;
    Bool2:= True;
    if not Bool1 or Bool2 then
      WriteLn('True')
    else
      WriteLn('False');

    WriteLn('4) True, True');
    Bool1:= True;
    Bool2:= True;
    if not Bool1 or Bool2 then
      WriteLn('True')
    else
      WriteLn('False');

    WriteLn;



    WriteLn('if not (Bool1 or Bool2) then True else False');

    WriteLn('1) False, False');
    Bool1:= False;
    Bool2:= False;
    if not (Bool1 or Bool2) then
      WriteLn('True')
    else
      WriteLn('False');

    WriteLn('2) True, False');
    Bool1:= True;
    Bool2:= False;
    if not (Bool1 or Bool2) then
      WriteLn('True')
    else
      WriteLn('False');

    WriteLn('3) False, True');
    Bool1:= False;
    Bool2:= True;
    if not (Bool1 or Bool2) then
      WriteLn('True')
    else
      WriteLn('False');

    WriteLn('4) True, True');
    Bool1:= True;
    Bool2:= True;
    if not (Bool1 or Bool2) then
      WriteLn('True')
    else
      WriteLn('False');

    WriteLn;



    WriteLn('if (not Bool1) or Bool2 then True else False');

    WriteLn('1) False, False');
    Bool1:= False;
    Bool2:= False;
    if (not Bool1) or Bool2 then
      WriteLn('True')
    else
      WriteLn('False');

    WriteLn('2) True, False');
    Bool1:= True;
    Bool2:= False;
    if (not Bool1) or Bool2 then
      WriteLn('True')
    else
      WriteLn('False');

    WriteLn('3) False, True');
    Bool1:= False;
    Bool2:= True;
    if (not Bool1) or Bool2 then
      WriteLn('True')
    else
      WriteLn('False');

    WriteLn('4) True, True');
    Bool1:= True;
    Bool2:= True;
    if (not Bool1) or Bool2 then
      WriteLn('True')
    else
      WriteLn('False');




    ReadLn;


  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

These are the results:

if not Bool1 or Bool2 then True else False
1) False, False
True
2) True, False
False
3) False, True
True
4) True, True
True

if not (Bool1 or Bool2) then True else False
1) False, False
True
2) True, False
False
3) False, True
False
4) True, True
False

if (not Bool1) or Bool2 then True else False
1) False, False
True
2) True, False
False
3) False, True
True
4) True, True
True

The first block shows the original line in question, the second block shows what I expected to be the case, but the third block shows the same result as the first, suggesting that

if not Application.DelayInitialize or Application.Installing then

is the same as

if (not Application.DelayInitialize) or Application.Installing then

And in the context of the service app, it seems as if it's the opposite - it would initialize if it's being installed (opposite of what I thought).

Can someone give me some clarification what I'm looking at here?

Java - JUnit testing for a method when else statement outputs error message as String

I'm working on a program that processes bank transactions. My withdraw method subtracts the amount from the balance and if there aren't enough funds for the withdrawal, an error message is outputted to the screen. The error message is the case I am having trouble testing.

public void withdraw(double amt) {
    double bal = getBalance();
    if(bal >= amt) {
        super.setBalance(bal - amt);
        if(bal < minBalance) {
            super.setBalance(bal - amt - maintFee);
        }   
    } else {
        System.out.println("Error: Not enough funds for withdraw");
    }       
}

These are my JUnit tests for this method currently. I just need help on testWithdrawThree(). Thank you!

@Test
void testWithdrawOne() {
    Savings s = new Savings(500.00, 30.00, "111", "Andrew Green", 1000.00);
    s.withdraw(200);
    assertEquals(800.00, s.getBalance());
}

@Test
void testWithdrawTwo() {
    Savings s = new Savings(500.00, 30.00, "111", "Andrew Green", 400.00);
    s.withdraw(200.00);
    assertEquals(170.00, s.getBalance());
}

@Test
void testWithdrawThree() {
    Savings s = new Savings(500.00, 30.00, "111", "Andrew Green", 400.00);
    s.withdraw(600.00);
    //Need to check that program will output "Error: Not enough funds for withdrawal"

}

if statement with 3 conditions

I have a problem with a program that takes a calender year and calculates whether it's a leap year or not. my if statement just eats the input and doesn't work at all, what's the issue?

#include <stdio.h>

//program de a verifica daca un an calendar introdus este bisect sau nu

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

{

int anul;

printf("\n");
printf("\nIntroduceti anul calender: ");

scanf("%d", &anul);


if( (anul%4==0) && (anul%100==!0) && (anul%400==0) )    
{
        printf("\n");
        printf("Anul %d este bisect", anul);
}

else
    printf("\n");
    printf("Anul %d NU este bisect", anul)


return 0;
}

get the last value in column (mimicking a hierarchy structure)

I currently have some vlookup formulas set up as so. An example cell formula would be

=IF($F2=G$1,$C2,"")

My current situation

Basically, the hierarchical data was stored in the database in numerical form. (ie, level 1 = 1, level 2 = 2, etc)

Ideal output

I would need some formula for the "value if false" portion of my above 'if' statement. Essentially, it would grab the last value in the column (the 'red' values). Notable exception is when it's a new value (see the yellow cells), and that case it's blank.

IF ELSE statement in Teradata

I have two sql statements SQL 1 & SQL 2. Further, I want to run them as per below logic,

SELECT * 
FROM MY_TABLE
WHERE COL1 > 0;

If ACTIVITY_COUNT = 0 THEN RUN SQL 1     ----- if records are present then run sql 1

ELSE 

RUN SQL 2    ----- if records are not present the run sql 2

Could you please suggest a SQL code or logic?

Thanks in Advance!

C# calculate + display possible knight positions chessboard

I'm currently trying to make a chessboard of 8x8. I want to randomly generate a position for my knight. After that i want to show all possible moves the knight can make.

I've managed to make it work if all possible positions are in the chessboard matrix. When one of the positions isn't in the matrix however the program does weird things. It's shows possible positions that should not be possible. Sometimes it even gives a error saying that the position is out of bounds.

I think my if statements are wrong. Can't see what's wrong.

This is my code:

        void PossibleKnightMoves(int[,] chessboard, Position position)
    {
        for (int row = -2; row <= 2; row+=4)
        {
            for (int col = -1; col <=1; col+=2)
            {
                if (row >= chessboard.GetLength(0) || row <0 || col >= chessboard.GetLength(1) || col < 0)
                {
                    continue;
                }
                if (row < chessboard.GetLength(0) && row >= 0 && col < chessboard.GetLength(1) && col >= 0)
                {
                    chessboard[position.col + row, position.row + col] = 2;
                    chessboard[position.col + col, position.row + row] = 2;
                }

            }

        }
    }

Kind regards,

Lorenzo.

When Ifelse statement is true, ifelse only returns one value instead of all

I have this data frame:

> new


     median
1    3.957587 
2    3.957587 
3    3.957587 
4    3.957587 
5    3.957587 
6    3.957587 
7    3.249960 
8    3.249960 
9    3.249960 
10   3.249960 
11   3.249960 
12   3.249960 
13   2.962515 
14   2.962515
15   2.962515 
16   2.962515 
17   2.962515 
18   2.962515

Now I compare these median values with this command:

# if difference of median values is bigger than 50%, get index of where this is happens
# returns numeric(0) when condition not met

results <- which(c(0, abs(diff(new$median))) > 0.5 * new$median) - 1

This works fine.

What I want to do now, is when the difference of median values is less than 50% (condition not met), just get the index of where the median values change. I could do it this way:

> testing <-  which(new$median[-1] != new$median[-length(new$median)])
> testing
[1]  6 12

I put these two ideas in an ifelse statement:

> results <- ifelse(length(results) == 0, testing, results)
> results
[1] 6

But this just gives me the first number, not also the second. Why?

php If statement inside another php if statement [duplicate]

This question already has an answer here:

I want to display whole code if $ws_user_status is 1, but inside this i want to separate the code on 2 another if statements... if $ws_total_sales == 0 to display info message, else ($ws_total_sales > 0) to display the table with all content items

But i have something made wrong... the table is visible all the time...

<?php
$ws_total_sales == 3;
$ws_user_status == 1;
?>

<?php if ($ws_user_status == 1) : ?>
<?php if ($ws_total_sales == 0 ) : ?>
<div class="woocommerce-info">
    <?php _e( 'You do not have any items to sell.', 'woocommerce' ); ?>
</div>
<?php else : ?>
<div>
<div class="alert alert-info">
    <?php _e( 'Your sales.', 'woocommerce' ); ?>
</div>      
      <table class="table table-hover">
        <thead>
          <tr>
            <th>Item</th>
            <th>Total sale</th>
            <th>Your profit</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Item 1 name</td>
            <td>100</td>
            <td>75000</td>
          </tr>
          <tr>
            <td>Item 2 name</td>
            <td>100</td>
            <td>60000</td>
          </tr>
          <tr>
        </tbody>
      </table>
</div>  
<?php endif; ?>
<?php endif; ?>

Using a return statement inside of an if statement [duplicate]

I am writing some JavaScript but I can't seem to make it work. I have the following code:

function() {

  var number = ;
  var level = " ";

  if(number = 198115) {
  var level = "HBO Bachelor";
}
  else if(number = 198118) {
  var level = "HBO Master";
}
  else if(number = 198121) {
  var level = "WO Bachelor";
}
  else if(number = 198124) {
  var level = "WO Master";
}
  else {
  var level = "Undefined";
}
  return level;
}

The variable that 'number' will be is one of the options stated in the if statement. What happens is that I only get 'undefined' and I don't get why.

Do you guys have any tips?

Trying to get property' of non-object, update existing users with new forms

I have extended an existing form, with another form with address information. New clients i can edit, since they got the values which are given with them.

Existing users, who dont have address information yet, i can't edit.

Trying to get property 'region' of non-object

I think this is because, the edit page returns a Null value.

    $regions = DB::table("regions")->pluck("name","id");
    $address = Address::where('id', $request->address_id)->with('region')->first();
    $data = $this->data->getEditClient($id);
    $admins = $this->data->getAdmin();

 if (is_null($address) && is_null($regions))
    {
        return view('client.edit', [

    //code for succesfully go to the edit page without address information.

        ]);
    } 


    return view('client.edit', [
        'client'        => $data, 
        'admins'        => $admins,
        'regions'       => $regions,
        'address'       => $address
        ]);
    }
}

Anyone knows the right solution for this error?

Greetings,

How to check if the variable contains the same string as a file?

My variables name is A and my files name is dogs.txt . I need to check if the variables text is the same as dogs.txt (contains the same string). What is the best way to do it?

I tried this

if [ cat dogs.txt == "$A" ] ; then  echo "equal" ; fi

How can i apply a function with an ifelse stricture

I make a new function:

  newFunction <- function (varX) {

  lst_a <- c("aa", "bb", "cc")
  lst_b <- c("dd", "ee", "ff")
  lst_c <- c("gg", "hh", "ii")

  ifelse(varX %in% lst_a , x.out <- "List A" , x.out <- "Other List" )
  ifelse(varX %in% lst_b , x.out <- "List B" , x.out )
  ifelse(varX %in%  lst_c , x.out <- "List C" , x.out)

  return(x.out)

 }

When I test the function it works well. But when I apply it to a dataframe it does not work:

     df <- as.data.frame(c("aa","cc","kk", "nn"))
    df$new <- newFunction((df[,1]))

I expected to get "List A", "List A", "Other list", "Other List" - but no such luck have I, and left with me is "Other list", "Other List", "Other list", "Other List"

r - Ordering problems when using mutate with ifelse conditional to date

I'm trying to use mutate to create a column that takes the value of one column up to a point and then uses cumprod to fill the rest of the observations based on the values of another column.

I tried combining mutate with ifelse but the order of the statements is not correct and I can't figure out why

Below I reproduce a more basic example that replicates my problem:

foo1 <- data.frame(date=seq(2005,2018,1))
foo1 %>% mutate(h=ifelse(date>2008, seq(1,11,1), 99))

The output is:

   date  h
1  2005 99
2  2006 99
3  2007 99
4  2008 99
5  2009  5
6  2010  6
7  2011  7
8  2012  8
9  2013  9
10 2014 10
11 2015  1
12 2016  2
13 2017  3
14 2018  4

And I'd like it to be:

   date  h
1  2005 99
2  2006 99
3  2007 99
4  2008 99
5  2009  1
6  2010  2
7  2011  3
8  2012  4
9  2013  5
10 2014  6
11 2015  7
12 2016  8
13 2017  9
14 2018 10

Thanks for your help!

Images with PHP and checkboxes

I want to learn how to display combined images with help of checkboxes. Lets say I have three images, the first one is a car, second one is a new wheels for the car, third tinted windows. I always display the original image of the car on the website, but lets say if I click the box for new wheels it appears on the car image or if I click tinted windows box, tinted windows appear on the car. The images are prepared with photoshop and stored in folder, simple stuff.

<form action="#" method="post">
<input type="checkbox" name="option" value="Wheels">Wheels</input>
<input type="checkbox" name="option" value="Tint">Windows</input>
<input type="submit" name="submit" value="Submit"/>
</form>
<?php
if (isset($_POST['option'])){
 // Display.
}
?>

I made a simple form so far and lets say as I said if I check Wheels, the wheels appear on the car, I uncheck it they disappear. Same with Windows. But how can I go about doing that lets say if I had 10 items I would not need to hard code a lot of statements? I am not asking for a code, but just ideas how to do it, because my idea is to hard code many if statements.

R - combining ifelse and substr

My sample data is:

df <- as.data.frame(c("10M_Amts", "D2B_Exp", "D3C_Exp", "D2_Amt", "D5_Amt", "53D_Amt"))
colnames(df) <- c("Label")

I'd like to adhere to the following rule:

If the first 2 letters are either D2, D3, D4, D5 or if the first 3 letters are D1A or D1_ then I would like to return the word "Work" in a new column called Work. If not, then return "NA".

I've searched around but wasn't able to find an example of dplyr combining ifelse and multiple substr commands. My attempted code using dplyr is:

df2 <- df %>%
       mutate(WRE = ifelse(substr(Label, 1, 3) == c("D1_", "D1A") |
                           substr(Label, 1, 2) == c("D2", "D3", "D4", "D5"), Work, "NA"))

As you can observe, there are multiple OR's going on for example for the first three strings I attempted to use c("D1_", "D1A") to represent D1_ or D1A. This is the same for the first two strings c("D2", "D3", "D4", "D5") to represent D2 or D3 or D4 or D5. In all, if there is D1_ or D1A or D2 or D3 or D4 or D5 in the first 2 or 3 letters, then it should return "Work" and if not, "NA". However, using substr function I resorted to split both of these categories.

My ideal output is:

     Label       Work
1   10M_Amts      NA
2   D2B_Exp      Work
3   D3C_Exp      Work
4   D2_Amt       Work
5   D5_Amt       Work
6   53D_Amt       NA

As you can see the new column name is Work. In excel, I would write the following:

=IF(OR(LEFT(A1,3)="D1_",LEFT(A1,3)="D1A",LEFT(A1,2)={"D2","D3","D4","D5"}), 
"Work", "")

where column A is the Label column as per above. Sorry for the small sample, this worked when I did this in excel for ~5000 rows and for multiple categories other than "Work" but because the sheet will be too big, we'd like to convert to R.

Thank you so much in advance!

c# select new with an if statement inside

I have this piece of code that select new some info from the database in my c# project but i only want it to do it if the name is not a certain name so here is the code

public List<Info> GetInfo(int id)
    {
        var cacheKey = "allinfo-" + id;
        var info = SoftCache.GetData<List<info>>(cacheKey);
        if (info != null)
            return info;

        using (var db = DB.InfoModel)
        {
            info = (from j in db.info_list()

                        select new Info
                        {
                            InfoName = j.info_name,
                            InfoId = j.info_id,
                            InfoValue = j.info_value,
                        }).ToList();
        }

        SoftCache.Add(cacheKey, info, new TimeSpan(0, 0, 5), new TimeSpan(0, 1, 0));
        return info;
    }

what i want is something like

if(j.info_name != "BadName"){
            select new Info
                            {
                                InfoName = j.info_name,
                                InfoId = j.info_id,
                                InfoValue = j.info_value,
                            }).ToList();
}

Sql is one of my weak areas tried with some case when but cant seem to get it to work with select new.

Statements out of function, but where?

Trying to get my last assignment in for the quarter, balance my job, and my other class. I would love an extra set of eyes to tell me where in the world my statements go out outside of my function:

This is an implementation file. The associated header is throwing no errors.

I get the following errors:

1.) In file included from tests.cpp:7:0: GBoard.cpp:31:2: error: expected unqualified-id before ‘for’ for(int r=0;r<15;r++) ^~~

2.) GBoard.cpp:31:14: error: ‘r’ does not name a type for(int r=0;r<15;r++) ^

But I am pretty sure 2 is part of my code being outside of the function somehow.

Here is my code, parts redacted so I don't get hit w/ plagiarism:

bool Gfunction::makeMove(int redacted,int redacted,char secret)
{

    if(redacted >= 0 && redacted < 15 && redacted >= 0 && redacted<15)
    {
        if(redacted() == UNFINISHED && function[redacted][redacted] == '.')
        function[redacted][redacted] = secret;
        return true;
    }   
        else
    {
        return false;

    }

    int track = 0;


    for(int r=0;r<15;r++)
    {
        track = 0;
            for(int c=0;c<15;c++)
            {
                    if(function[r][c] == secret)
                    {
                track++;
                    if(track==5)
                        {
                                if(secret == 'x')
                                secret squirrel stuff = X_WON;
                                else
                            secret squirrel stuff = O_WON;
                                return true;
                    }
                }
                else
                {
                    track = 0;
                }
        }

    }   



    for(int r=0;r<15;r++)
    {
            track = 0;
            for(int c=0;c<15;c++)
            {
                    if(function[r][c] == secret)
                    {  
                        track++;
                        if(track==5)
                        {
                            if(secret == 'x')
                                secret squirrel stuff = X_WON;
                                else
                                secret squirrel stuff = O_WON;
                                return true;
                        }

                    }
                        else
                    {
                            track = 0;
                    }
            }

    }



        int r = 0, c = 0;
        for(int redacted = 0; redacted<15; redacted++)
        {
            r = redacted;
                c = 0;
                track = 0;
                while(r < 15 && c < 15)
                {
                    if(function[r][c] == secret)
                    {
                        track++;
                        if(track == 5)
                        {
                                if(secret == 'x')
                                secret squirrel stuff = X_WON;
                                else
                                secret squirrel stuff = O_WON;
                                return true;
                        }
                }
                        else
                        {
                                track = 0;
                        }
                                r++;
                                c++;
        }
    }

    for(int redacted = 0; redacted<15; redacted++)
    {
            r=0;
            c=redacted;
            track=0;
            while(r<15 && c<15)
                {
                    if(function[r][c] == secret)
                    {
                            track++;
                            if(track == 5)
                            {
                                if(secret == 'x')
                                secret squirrel stuff = X_WON;
                                else
                                secret squirrel stuff = O_WON;
                                return true;
                        }
            }
                        else
                        {
                                track = 0; 
                        }
                                r++;
                                c++;
                }
        }


    for(int redacted=0; redacted<15; redacted++)
    {
        r=redacted;
        c=15-1;
        track=0;
        while(r<15 && c>=0)
        {
                    if(function[r][c] == secret)
                    {
                        track++;
                        if(track == 5)
                {
                    if(secret == 'x')
                            secret squirrel stuff = X_WON;
                            else
                            secret squirrel stuff = O_WON;
                            return true;
                        }
            }
                            else
                    {
                            track = 0;
                    }
                            r++;
                            c--;
        }
    }


    for(int redacted=15-1;redacted>=0;redacted--)
    {
            r=0;
            c=redacted;
            track=0;
            while(r<15 && c>= 0)
            {
                    if(function[r][c] == secret)
                    {
                        track++;
                        if(track == 5)                    
                        {
                                if(secret == 'x')
                                secret squirrel stuff = X_WON;
                                else
                                secret squirrel stuff = O_WON;
                                return true;
                        }
            }
                        else
                        {
                            track = 0;
                        }
                            r++;
                            c--;
            }
        } 


    for(int r=0;r<15;r++)
    {
            for(int c=0;c<15;c++)
            {
            if(function[r][c] == '.')
                {
                    secret squirrel stuff = UNFINISHED;
                    return true;
            }
        }
    }  
        secret squirrel stuff = DRAW;
        return true;
}

mardi 27 novembre 2018

How to build widgets based on if-else statement?

I need to build a widget based on the data as example shown below. I need to run the CircularProgressIndicator first. My problem is that I need to get data from Server 1. If Server 1 has no data stop CircularProgressIndicator and show “No Registration Found” Widget. If Server 1 has data then get details data from Server 2. If Server 2 has no data show “Temporarily Data is not available” Widget. If Server 2 has Data then show "Server 2 Data Widget"

Run loading animation widget (CircularProgressIndicator)
    - Get Data from Server 1
        - If Server 1 Data is okay
            - Get Data from Server 2 using Server 1 Data item value
                - If Server 2 Data is okay
                    - Show Server 2 Data Widget
                - Else
                    - Show “Temporarily Data is not available” Widget
       - Else
            - Show “No Registration Found” Widget

I try to create a Boolean variable and in main build Widget I try to show the page. But I am keep getting error and keep shows the “No Registration Found” Widget and few seconds later when I ger Server 2 Data using setState it shows the "Server 2 Data Widget". But it never shows the CircularProgressIndicator. Any idea how to build the widgets base on the if else statement as I explained above.

bool _runLoading = true;
bool _data1 = false;
bool _data2 = false;

    return _runLoading == true
        ? _buildLoadingAnimation
        : _data2 == true
          ? _buildServer2Data
          : _buildNoDataFound

php if statement argument in laravel

I have a calculation to make which the variable $totalPercent might be a 0 so I added some if statements to the script to only run since the initial returned with an error on division by zero on some occasion.

This was the newly revised calculation, which now works when $totalPercent is a 0, but when it has a value and the supposed script is called, it returned me an error of Undefined variable: designPercent

Here is the new script with the added if statement that was meant to do calculation only if $totalPercent is more than 0.

@if ($totalnumerical > '0')
    $totalPercent= '100' / $totalnumerical;
    $stylePercent= ($styletempt *  $totalPercent).'%';
    $designPercent= ($designtempt * $totalPercent).'%';
    $managePercent= ($managetempt * $totalPercent).'%';
    <div class="graphSection">
        <div class="skillGraph">
            <span style="width:" class="bar-1"></span>
            <span style="width:" class="bar-2"></span>
            <span style="width:" class="bar-3"></span>
        </div><br>
        <div class="skillGraph graph_text">
            @if(($designtempt * $totalPercent) > 15)
                <span style="width:" >Design</span>
            @else
                <span class="hovertext" style="width:; margin-top:-57px" >Design</span>
                <span style="width:" ></span>
            @endif
            @if(($styletempt * $totalPercent) > 15)
                <span style="width:" >Interior Styling</span>
            @else
                <span class="hovertext" style="width:; margin-top:-67px;" >Interior Styling</span>
                <span style="width:" ></span>
            @endif
            <span style="width:" >Project Management</span>
        </div>
    </div>

@endif

"Dynamic" if-else statement with jQuery

I'm not understanding how to accomplish this without hardcoding an if else statement.

I have two table examples. One has 4 quantity breaks and the other has 5 quantity breaks below. Some may have 1,2,3,4,5,6,7,8,9, and up to 10.

I also have an input box for the quantity the customer wants to buy. When the quantity break is updated and it is within another quantity break I want to "do this" (which isn't my problem) it's the dynamic if-else statement that I'm unsure how to build.

I'm looking for a solution that will 1) Add up the number of quantity breaks. In these two examples it's 4 and 5. 2) Create an if - else if where the last else if will be => 99999. Or can I create an infinite => ??? Sorry I'm new to jQuery. 3) Not allow me to order less than minimum quantity - first quantity break (I have a button that says add to order... I tried an on click function but it alerts twice, so annoying!)

Maybe this will help: As the front-end user, when I enter in a number with a different quantity break I should only see the option code that is available for that quantity break so that the price matches the quantity break.

I've put together this:

 text1 =$('.priceGrid > thead > tr > th:eq(1)').text(); 
 number1 = parseInt(text1,10);
 text2 =$('.priceGrid > thead > tr > th:eq(2)').text();
 number2 = parseInt(text2,10);
 text3 =$('.priceGrid > thead > tr > th:eq(3)').text();
 number3 = parseInt(text3,10);
 text4 =$('.priceGrid > thead > tr > th:eq(4)').text();
 number4 = parseInt(text4,10);
 number10 = number2-1;
 number20 = number3-1;
 number30 = number4-1;

//find all unique option codes
tab_attribs = [];
$('[name^=optionCode_]').each(function () {
  tab_attribs.push( $(this).attr("value") );
});
//var unique;
unique = $.grep(tab_attribs, function(v, i) {
    return $.inArray(v, tab_attribs) === i
});

//count how many price breaks
//var size;
size = $('.priceGrid > thead > tr > th').size();
$('.qty_input').keyup(function(){
    value = $('.qty_input').val();
});

if (size === 5){
$('.qty_input').keyup(function () {
       //var value = $('.qty_input').val();

       if (value >= number1 && value <= number10){

           $('.productOptionName .option').addClass('hide-option'),
           $("select[name^="+unique[0]+"]").parent().parent().parent().removeClass('hide-option');
       }
       else if (value >= number2 && value <= number20){

           $('.productOptionName .option').addClass('hide-option'),
           $("select[name^="+unique[1]+"]").parent().parent().parent().removeClass('hide-option');
       }
           else if (value >= number3 && value <= number30){

           $('.productOptionName .option').addClass('hide-option'),
           $("select[name^="+unique[2]+"]").parent().parent().parent().removeClass('hide-option');
       }
       else if (value >= number4 && value <= 999999){

           $('.productOptionName .option').addClass('hide-option'),
           $("select[name^="+unique[3]+"]").parent().parent().parent().removeClass('hide-option');
       }
   
//else if (size === 4) {}
   }); 
<div class="qty_input_wrapper">
   <input type="text" autocomplete="off" maxlength="5" value="25" class="qty_input form-control" name="quantity_610597" id="quantity_610597">
   <input type="hidden" value="610597" name="product.id" id="productId">
   <div name="show_inventory" id="show_inventory" style="text-align:center;">
   </div>
</div>
table.priceGrid thead tr th {
  font-weight: bold;
  background: #F2F2F2;
  text-align: center;
}

table.priceGrid tbody tr th {
  font-weight: bold;
  background: #F2F2F2;
  text-align: center;
}

table.priceGrid tbody tr td {
  font-weight: normal;
  text-align: center;
}

table.priceGrid tbody tr.saving_percentage th {
  color: red;
}

table.priceGrid tbody tr.saving_percentage td {
  color: red;
}

table.priceGrid tr th.disabled,
table.priceGrid tr td.disabled {
  position: relative;
  opacity: 0.7;
  filter: alpha(opacity=70);
}

table.priceGrid tr th.disabled:before,
table.priceGrid tr td.disabled:before {
  display: block;
  content: "";
  background: repeating-linear-gradient(45deg, transparent, transparent 5px, #000 5px, #000 10px);
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  opacity: 0.2;
  filter: alpha(opacity=20);
}
<table class="priceGrid table table-bordered">
  <thead>
    <tr>
      <th>Quantity</th>
      <th>
        25+
      </th>
      <th>
        50+
      </th>
      <th>
        100+
      </th>
      <th>
        250+
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">Price</th>
      <td style="color: #000000;">
        <span class="prod-price">
                $28.10
                </span>
      </td>
      <td style="color: #000000;">
        <span class="prod-price">
                $26.38
                </span>
      </td>
      <td style="color: #000000;">
        <span class="prod-price">
                $24.97
                </span>
      </td>
      <td style="color: #000000;">
        <span class="prod-price">
                $23.83
                </span>
      </td>
    </tr>
    <tr class="saving_percentage">
      <th scope="row">You Save</th>
      <td>
        -
      </td>
      <td>
        <span class="prod-price">
                $1.72
                </span> (6.12%)
      </td>
      <td>
        <span class="prod-price">
                $3.13
                </span> (11.14%)
      </td>
      <td>
        <span class="prod-price">
                $4.27
                </span> (15.20%)
      </td>
    </tr>
  </tbody>
</table>
<span>OR</span>
<div class="priceGridWrapper table-responsive">
  <table class="priceGrid table table-bordered">
    <thead>
      <tr>
        <th>Quantity</th>
        <th>
          48+
        </th>
        <th>
          96+
        </th>
        <th>
          192+
        </th>
        <th>
          384+
        </th>
        <th>
          768+
        </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th scope="row">Price </th>
        <td style="color: #000000;">
          $10.94
        </td>
        <td style="color: #000000;">
          $10.55
        </td>
        <td style="color: #000000;">
          $10.06
        </td>
        <td style="color: #000000;">
          $9.40
        </td>
        <td style="color: #000000;">
          $9.00
        </td>
      </tr>
      <tr class="saving_percentage">
        <th scope="row" style="color:#1FA814;">Quantity Savings</th>
        <td style="color:#1FA814;">
          -
        </td>
        <td style="color:#1FA814;">
          $0.39 (3.56%)
        </td>
        <td style="color:#1FA814;">
          $0.88 (8.04%)
        </td>
        <td style="color:#1FA814;">
          $1.54 (14.08%)
        </td>
        <td style="color:#1FA814;">
          $1.94 (17.73%)
        </td>
      </tr>
    </tbody>
  </table>
</div>

Here is a snippit of all the option codes... this is what I'm working with. I don't have access to the java, I need to do this with jQuery. I don't have any real syntax knowledge of Javascript, I know that's weird...

I know that only one of the option codes has a different price, it won't always be that way. Sometimes they will sometimes they won't. My main goal is to think of a way where I don't have to hardcode any of this.

<div class="product_options">
   <div class="productOptionName">
      <input type="hidden" name="optionCode_610597_" value="BENTO8">
      <input type="hidden" name="optionCode_610597" value="BENTO8">
      <div class="option">
         <label for="" class="control-label fs-16">M&amp;Ms:</label>
         <input type="hidden" name="BENTO8-option_610597" value="0">
         <div class="row">
            <div class="col-sm-8 col-md-7 col-lg-6">
               <select class="form-control" name="BENTO8-option_values_610597_0" onchange="showAttachmentInput('0', this.value)" id="PRODUCT-610597-0">
                  <option class="opt" value="0" id="OPTION-610597-0-0-0">
                     No
                  </option>
                  <option class="opt" value="1" id="OPTION-610597-0-0-1">
                     Yes + $2.89
                  </option>
                  <option class="opt" value="2" id="OPTION-610597-0-0-2">
                     Yes + $2.89
                  </option>
                  <option class="opt" value="3" id="OPTION-610597-0-0-3">
                     Yes + $2.89
                  </option>
                  <option class="opt" value="4" id="OPTION-610597-0-0-4">
                     Yes + $2.89
                  </option>
               </select>
            </div>
         </div>
      </div>
      <input type="hidden" name="optionCode_610597_" value="BENTO8">
      <input type="hidden" name="optionCode_610597" value="BENTO8">
      <div class="option">
         <label for="" class="control-label fs-16">Espresso Coffee Beans:</label>
         <input type="hidden" name="BENTO8-option_610597" value="1">
         <div class="row">
            <div class="col-sm-8 col-md-7 col-lg-6">
               <select class="form-control" name="BENTO8-option_values_610597_1" onchange="showAttachmentInput('1', this.value)" id="PRODUCT-610597-1">
                  <option class="opt" value="0" id="OPTION-610597-1-1-0">
                     No
                  </option>
                  <option class="opt" value="1" id="OPTION-610597-1-1-1">
                     Yes + $4.34
                  </option>
                  <option class="opt" value="2" id="OPTION-610597-1-1-2">
                     Yes + $4.34
                  </option>
                  <option class="opt" value="3" id="OPTION-610597-1-1-3">
                     Yes + $4.34
                  </option>
                  <option class="opt" value="4" id="OPTION-610597-1-1-4">
                     Yes + $4.34
                  </option>
               </select>
            </div>
         </div>
      </div>
      <input type="hidden" name="optionCode_610597_" value="BENTO8">
      <input type="hidden" name="optionCode_610597" value="BENTO8">
      <div class="option">
         <label for="" class="control-label fs-16">Optional Inside Label Run Charge:</label>
         <input type="hidden" name="BENTO8-option_610597" value="2">
         <div class="row">
            <div class="col-sm-8 col-md-7 col-lg-6">
               <select class="form-control" name="BENTO8-option_values_610597_2" onchange="showAttachmentInput('2', this.value)" id="PRODUCT-610597-2">
                  <option class="opt" value="0" id="OPTION-610597-2-2-0">
                     No
                  </option>
                  <option class="opt" value="1" id="OPTION-610597-2-2-1">
                     Yes + $50.00
                  </option>
                  <option class="opt" value="2" id="OPTION-610597-2-2-2">
                     Yes + $1.75
                  </option>
                  <option class="opt" value="3" id="OPTION-610597-2-2-3">
                     Yes + $1.50
                  </option>
                  <option class="opt" value="4" id="OPTION-610597-2-2-4">
                     Yes + $1.25
                  </option>
               </select>
            </div>
         </div>
      </div>
      <input type="hidden" name="optionCode_610597_" value="BENTO8">
      <input type="hidden" name="optionCode_610597" value="BENTO8">
      <div class="option">
         <label for="" class="control-label fs-16">Laser Engraving Run Charge (Silver Only):</label>
         <input type="hidden" name="BENTO8-option_610597" value="3">
         <div class="row">
            <div class="col-sm-8 col-md-7 col-lg-6">
               <select class="form-control" name="BENTO8-option_values_610597_3" onchange="showAttachmentInput('3', this.value)" id="PRODUCT-610597-3">
                  <option class="opt" value="0" id="OPTION-610597-3-3-0">
                     No
                  </option>
                  <option class="opt" value="1" id="OPTION-610597-3-3-1">
                     Yes + $1.15
                  </option>
                  <option class="opt" value="2" id="OPTION-610597-3-3-2">
                     Yes + $1.15
                  </option>
                  <option class="opt" value="3" id="OPTION-610597-3-3-3">
                     Yes + $1.15
                  </option>
                  <option class="opt" value="4" id="OPTION-610597-3-3-4">
                     Yes + $1.15
                  </option>
               </select>
            </div>
         </div>
      </div>
      <input type="hidden" name="optionCode_610597_" value="BENTO8">
      <input type="hidden" name="optionCode_610597" value="BENTO8">
      <div class="option">
         <label for="" class="control-label fs-16">Heat Transfer Run Charge (Silver Only):</label>
         <input type="hidden" name="BENTO8-option_610597" value="4">
         <div class="row">
            <div class="col-sm-8 col-md-7 col-lg-6">
               <select class="form-control" name="BENTO8-option_values_610597_4" onchange="showAttachmentInput('4', this.value)" id="PRODUCT-610597-4">
                  <option class="opt" value="0" id="OPTION-610597-4-4-0">
                     No
                  </option>
                  <option class="opt" value="1" id="OPTION-610597-4-4-1">
                     Yes + $2.50
                  </option>
                  <option class="opt" value="2" id="OPTION-610597-4-4-2">
                     Yes + $2.50
                  </option>
                  <option class="opt" value="3" id="OPTION-610597-4-4-3">
                     Yes + $2.50
                  </option>
                  <option class="opt" value="4" id="OPTION-610597-4-4-4">
                     Yes + $2.50
                  </option>
               </select>
            </div>
         </div>
      </div>
   </div>
</div>

Thank you.