jeudi 31 mai 2018

JavaScript Statements Flagged as Not a Function?

I have an JavaScript if..else statement inside of a block to hide or show two buttons:

/* Toggle Revert or Complete buttons based on order status */

if (!status1 || status2 == "wc-completed" ) { // Status check working
  (function() {
    $(document.getElementById(idDIVOrder)).querySelector('form.complete-order-cred').style.visbility = "hidden";
    $(document.getElementById(idDIVOrder)).querySelector('form.revert-order-cred').style.visbility = "show";
  })();
} else if (!status1 || status2 == "wc-processing" ) {
  (function() {
    $(document.getElementById(idDIVOrder)).querySelector('form.revert-order-cred').style.visbility = "hidden";
    $(document.getElementById(idDIVOrder)).querySelector('form.complete-order-cred').style.visbility = "show";
  })();
} else {
  console.log("Hide or display buttons not working! Order has a status of " + status1 + " and " + status1);
}

I'm getting the error "Uncaught TypeError: $(...).querySelector is not a function", which also occurs if I place the .querySelector statements inside the if and else without functions.

What's the right way to declare JS functions here?

Introducing a new tune to Arduino code

Okay last question for this project. We have this face-to-sound code for raspberry pi and Arduino. Basically, when the camera detects a face, it sends a signal to Arduino to play a tune. So my question is, how can I introduce another 'song' (which we already have) into Arduino? So to be clear, if = 1 face is found : play tuneA. If >1 faces are found : play tuneB

We would have to modify both the Arduino and Python parts Here are both codes

Python:

import time
import io
import os
import sys
from cStringIO import StringIO
import random
import pipan
import picamera
import cv2
import numpy
import base64
import serial

ser = serial.Serial('/dev/ttyACM0', 9600)

find_face = False
serach_time = 0

def looking_face():

    #Create a memory stream so photos doesn't need to be saved in a file
    stream = io.BytesIO()

    with picamera.PiCamera() as camera:
        camera.resolution = (1280, 720)
        camera.hflip = True
        camera.vflip = True
        camera.capture(stream, format='jpeg')

    #Convert the picture into a numpy array
    buff = numpy.fromstring(stream.getvalue(), dtype=numpy.uint8)

    #Now creates an OpenCV image
    image = cv2.imdecode(buff, 1)

    #downsize the image for face recognition
    image_small = cv2.resize(image, (0, 0), fx=0.5, fy=0.5)

    #Load a cascade file for detecting faces
    face_cascade = cv2.CascadeClassifier('face.xml')

    #Convert to grayscale
    gray = cv2.cvtColor(image_small,cv2.COLOR_BGR2GRAY)

    #Look for faces in the image using the loaded cascade file
    faces = face_cascade.detectMultiScale(gray, 1.1, 5)

    print "Found "+str(len(faces))+" face(s)"

    if len(faces) > 0:

        # If a face is found, send a meesage to Arduino
        ser.write('1')

        #Draw a rectangle around every found face
        for (x,y,w,h) in faces:
            cv2.rectangle(image,(x*2,y*2),(x*2+w*2,y*2+h*2),(255,255,0),2)

        cv2.imwrite('face_found.jpg',image)

        exit()


def main():

    raw_input("press enter to start searching")
    print 'Search Begin!'

    # Infinite Loop
    while True:
        looking_face()

if __name__ == '__main__':
    main()

Arduino:

#include <Wire.h>
#include <Zumo32U4.h>

Zumo32U4Buzzer buzzer;

// Store this song in program space using the PROGMEM macro.
// Later we will play it directly from program space, bypassing
// the need to load it all into RAM first.
const char fugue[] PROGMEM =
  "! O5 L16 agafaea dac+adaea fa<aa<bac#a dac#adaea f";

boolean play_sound = false;

void setup()       // run once, when the sketch starts
{
  Serial.begin(9600);
}

void loop()        // run over and over again
{
  //Listening from Python
  if(Serial.read() == '1'){
     play_sound = true;
  }

  if(play_sound == true){
    // Start playing a tone with frequency 440 Hz at maximum
    // volume (15) for 200 milliseconds.
    buzzer.playFrequency(440, 200, 15);

    // Delay to give the tone time to finish.
    delay(1000);

    // Start playing note A in octave 4 at maximum volume
    // volume (15) for 2000 milliseconds.
    buzzer.playNote(NOTE_A(4), 2000, 15);

    // Wait for 200 ms and stop playing note.
    delay(200);
    buzzer.stopPlaying();

    delay(1000);

    // Start playing a fugue from program space.
    buzzer.playFromProgramSpace(fugue);

    // Wait until it is done playing.
    while(buzzer.isPlaying()){ }

    delay(1000);

    play_sound = false;
  }
}

Any help would be greatly appreciated!

convert a if statement to a swicth

Could this program be switch to a switch statement?

if((Month*Day)==Year){
System.out.println("The date is magic");
}
else{
System.out.println("The date is not magic");
}

Without changing condition in if statement i need to print else statement by giving any value to i?

#include <stdio.h>

int main() {
    int i =-1;
    if(1< i <10){
        printf("1");
    } else {
        printf("2");
    }
}

expected output: 2
present output: 1

set command isn't working in if statement

For the life of me, I can't figure out why the below set prompt won't work when it is in the if statement:

@echo off

REM :askdeletecsvs
if exist *.csv (
    echo Warning! All files in the scripts folder that have the "CSV" extension will be deleted!
    echo Answering "n" will continue the script without deleting the CSVs.
    set /p ASKDELETE=Delete CSVs? (y/n): 
REM     
REM     if ( /i %ASKDELETE% equ "y" goto :deletecsvs )
REM     if ( /i %ASKDELETE% equ "n" goto :runscripts )
REM     goto :askdeletecsvs
)

When I run the batch file as it is above the cmd window opens and then shuts quickly. If I move the set line outside of the if statement then the prompt shows as expected.

What am I missing?

Multiple conditionals in php

if
(
  ($page_num >=10 && $page_num<= 20)  || 
  ($page_num >= 21 && $page_num =< 30) || 
  ($page_num >=31 && $page_num =<40)
){
     if($i==1){
       $i = $page_num;
     }
 }

I am trying to achieve multiple conditionals using the above in PHP. I tried it and it kept outputting an error, so I don't know if I am making a mistake or what I am trying above is not possible in PHP or programming.

The error message

Parse error: syntax error, unexpected '<' in C:addsdcredit.php on line 398

How to make my application wait until the condition is met

How about, I'm a bit new to c#, I have a stored procedure that inserts data to a backup table, I wanted to do it through a job, but I have sql server express, so it's not an option, I'm looking to do an .exe(console application) and I want you to wait until a certain time for to just run stored procedure, what would be the best way to do it?

static void Main(string[] args)
    {
       using (SqlConnection conn = new SqlConnection
             ("Server=localhost\\SQLEXPRESS;Database=VIDEOJUEGOS;IntSecurity=SSPI"))
       {
                conn.Open();

                if (DateTime.Now.ToString("HH:mm")  == "11:00")
                {
                    SqlCommand cmd = new SqlCommand("usp_virtualX", conn);
                    cmd.CommandType = CommandType.StoredPro
                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            Console.WriteLine();
                        }
                    }
                }
            }
        }

trying to use 2 columns

So basically the goal of this code is to report which ports on a group of devices are being utilized.

The code is as follows:

$ file_name = input('Enter File Name: ') + str('.csv') total_ports = 500

my_reader = csv.reader(open(file_name)) ctr = 0 for total_reserved in my_reader: if total_reserved[2] == 'Reserved': ctr += 1 print(ctr, 'out of ', total_ports, 'PLS ports are reserved')

my_reader = csv.reader(open(file_name)) ctr_pls0 = 0 for pls0 in my_reader: if pls0[0] == 'L1 switches/L1 Switch 10G PLS0.BLLAB/Blade01' and total_reserved[2] == 'Reserved': ctr_pls0 += 1

print(ctr_pls0, 'of these', ctr, 'are pls0 ports') $

This gives me the following output...

Enter File Name: 31.05.2018 175 out of 500 PLS ports are reserved 0 of these 175 are pls0 ports

Process finished with exit code 0

0 of these 175 are pls0 ports this is where the issue lies, this line should be providing me with the amount of ports that are called 'L1 switches/L1 Switch 10G PLS.BLLAB/Blade01' AND that are shown as 'Reserved' as per the .csv file.

Any ideas of what this could be?

Thanks!

J

Faster way to perform an If statement

Is there a faster way to run the below code? the "hr" sheet has 24000 rows and it takes about 30+ minutes to run this simple query.

Sub populateHRData17()
'APAC
Set report = ActiveWorkbook.Worksheets("Report")
Set hr = ActiveWorkbook.Worksheets("HR_Report")
Set apac = ActiveWorkbook.Worksheets("APAC_L_R")

For x = 2 To report.UsedRange.Rows.Count
    If report.Cells(x, 1) = "" Then
    End If
Next x


For i = 2 To hr.UsedRange.Rows.Count
  For j = 2 To apac.UsedRange.Rows.Count

    If apac.Cells(j, 2) = hr.Cells(i, 3) Then
       report.Cells(x, 1) = apac.Cells(j, 2)


 x = x + 1
    End If

Next j
Next i
End Sub

if-else statements are not working properly for Appium Java script

I have written a Java code with if-else statements and user would move from 'Screen1' to 'Screen2' through any of 4 alternate routes and I have attached an image for all enter image description herepossible application flows which are decided on the go by of course code written by developer. Just to add tool used is Appium.

    driver.findElement(By.id("----")).click(); //this click will take from  'screen1' to next screen.

    if(driver.findElement(By.id("abc")).isDisplayed())//see if element on 'screen A' is displayed
    {
        //execute a few statements

    }

    else if(driver.findElement(By.id("xyz")).isDisplayed()) //see if element on 'Screen B' is displayed
    {

       //execute a few statements

    if(driver.findElement(By.id("abc")).isDisplayed()) //see if element on 'screen A' is displayed

    {
        // execute
    }

    }
 driver.findElement(By.id("----")); //this is code for 'Screen 2'

What happens is during execution of script, first 'If' is checked and rest all code skipped. I am not able to figure out the issue. Please help.

how replace a Picture url when that return me null or nothing

i call an API of vehicle for the photos with a php GET, that return me an array,

i use this for for get the vehicle :

   $vehiculecount=count($data);
   for($x = 0; $x < $vehiculecount; $x++) { ?>

Now i want to if i have a return of the photo that return me the photo, else that return me a special "noPhoto"photo in my folder

I do this :

<?php
$photo = echo $data[$x][gallery][0][big];
if ($photo = null) {
       $photo = img/noPhoto.png;
        echo $photo;
else {
            $photo = $photo;
            echo $photo;
                                      }
  }
endif
?>

Here the HTML :

<img class="card-img-top" src="<?php echo $photo;?>" alt="">

Thx for the help.

Returning forloop to if statement

I'm making a IntegerList in Java. The list containt 6 Integers. [0,1,2,3,4,5]. I have a function getNormalList(). This list must return a list with 3 random Integers. And it may not be 3 the same Integers. The function getNormalList() is not working like I want it to work.

public class SpinResultGenerator {

    public ArrayList<Integer> getNormalList() {
        ArrayList<Integer> integerList = new ArrayList<Integer>();
        Random r = new Random();
        int Low = 0;
        int High = 6;
        for (int i = 0; i < 3; i++) {
            int number = r.nextInt(High - Low) + Low;
            integerList.add(number);
        }
        if (integerList.get(0) == integerList.get(1) && integerList.get(0) == integerList.get(2)
                && integerList.get(1) == integerList.get(2)) {
            integerList.clear();
            for (int i = 0; i < 3; i++) {
                int number = r.nextInt(High - Low) + Low;
                integerList.add(number);
            }
        }
        return integerList;
    }

    public ArrayList<Integer> getJackpotList() {
        ArrayList<Integer> integerList = new ArrayList<Integer>();
        integerList.add(5);
        integerList.add(5);
        integerList.add(5);
        return integerList;
    }
}

In this way, if the result = for example: [4,4,4]. The forloop then work again and is still able to output 3 the same Integers.

IndexError: single positional indexer is out-of-bounds and if condition

I have a dataframe that looks like this:

    Repo
    Out[624]: 

1             Instrument    Term Code  WTD Rate
2    GC_AUSTRIA_SUB_10YR          T-N     -0.49
3    GC_AUSTRIA_SUB_10YR            O -0.467643
4      R_RAGB_1.15_10/18          S-N -0.520299
5      R_RAGB_4.35_03/19          S-N -0.497759
6      R_RAGB_4.35_03/19          T-N      -0.5
7      R_RAGB_1.95_06/19          S-N -0.501478
8      R_RAGB_0.25_10/19          S-N -0.497765

I have an if condition which is dependent on the column "Instrument"

if condition:
   return Repo.loc[(Repo['Instrument']=='GC_LCH_BELGIUM') & (Repo['Term Code']=='T-N'),'WTD Rate'].iloc[0]

The issue is that the Instrument name sometimes does not exist and get an error IndexError: single positional indexer is out-of-bounds

How can I say in the "if condition" that if the instrument does exist (or if there is an error) reverts back to default value of say 10.

I should point out that when Instrument does not exist there is no row in the dataframe. therefore code that looks something like "is empty" would not work

SUMIFS combine with LARGE

Is there a way to combine "LARGE" with "IF"?

My Large formula is working, but if I want to Combine it with "IF", I don't know, how to solve it. The Problem is that I have named an Area in the data set with "Area1" and different names in it. I want for "Name1", which is in the "Area1" several times, the highest value he can find in another named area,"Area2".

Hope you understand my Problem and can help me out :)

Using for loop within if statement in PHP

I am writing a rostering app. This statement checks that by booking an extra shift the user doesn't violate a rule whereby they have booked more than 7 night shifts in a row. This code runs fine but I am trying to find a more elegant way to write it, for instance using a for loop within the if statement. This snippet exists within a bigger while loop.

if (
    $original_shift->night_shift==true &&
    $p_lookback_night_7===[1,1,1,1,1,1,1] || $p_lookforward_night_7===[1,1,1,1,1,1,1] ||
    ($p_lookback_night_1===[1] && $p_lookforward_night_6===[1,1,1,1,1,1]) ||
    ($p_lookback_night_2===[1,1] && $p_lookforward_night_5===[1,1,1,1,1]) ||
    ($p_lookback_night_3===[1,1,1] && $p_lookforward_night_4===[1,1,1,1]) ||
    ($p_lookback_night_4===[1,1,1,1] && $p_lookforward_night_3===[1,1,1]) ||
    ($p_lookback_night_5===[1,1,1,1,1] && $p_lookforward_night_2===[1,1]) ||
    ($p_lookback_night_6===[1,1,1,1,1,1] && $p_lookforward_night_1===[1])
) {
    return 'You can\'t do more than 7 night shifts in a row'; 
    break;
}

Best way to code multiple decisions in Python

I have the following practical problem (related to Django/Python).

I'm trying to get the following in the most efficient piece of Python code ->

There are 2 items to be checked:

  1. Is the user logged in? if not show a login page, else check if the request is a post request.
  2. Is the request a post request? If not show a form, else handle the form

    def upload(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
        form = forms.DocumentForm()
        return HttpResponse('Handle POST and LoggedIn Prefix Form Validation')
    #return (request, 'upload.html', {'form': form})
    else:
        return HttpResponse('Not Logged In Need to Make Error Landing Page')
    else:
    if request.method == 'POST':
        return HttpResponse('POST but not logged in')
            #return render(request, 'upload.html', {'form': form})
    
    

mercredi 30 mai 2018

image change onclick not working!! help needed

Hi i want to make a program that changes the image when i click on it this is the code:

 <!DOCTYPE html>
<html>
<head>
    <title>logo change</title>
    <script type="text/javascript">
        var image_tracker="f"
        function change() {
            var image=document.getElementByid('social');
            if (image_tracker=="f") {
                image.src="twit.jpg"
                image_tracker="t"
            }
            if (image_tracker=="t") {
                image.src="fb.jpeg"
                image_tracker="f"
            } 
        }

    </script>
</head>
<body>
<img src="fb.jpeg" id="social" onclick="change()">
</body>
</html>

i tried the same as the person on youtube did LINK:https://www.youtube.com/watch?v=SGKXZUGe2sw

Conditionally add data-attributes in Jekyll

My basic YAML Front Matter for blog posts looks as:

   layout: post
   title:  'Crepes'
   permalink: /crepes/
   src: '/assets/images/crepes.jpg' 
   date:   2018-05-24 21:41:00
   origin: http//...
   ingredients: 
    - ingredient1: amount
    - ingredient2: amount 

Here is my index.html to display entries:

<ul>

</ul>

The problem is: Some posts are supposed to have no origin value, like origin:. And I am looking for a way to add data-origin attribute only if it's value specified in YAML Front Matter.

Liquid give following option:



Is there any way to use it inside of html tag? In my case I expect something like this:

 

Creating a new column with ifelse condition (python)

I am trying to create a new column 'New' that:

1) if 'y' values is different from zero, give me 'y'

2) if 'y' is equal zero, give me 'yhat' value

           ds     y         ds       yhat
0    1999-03-05  45.0 1999-03-05  37.168417
1    1999-03-06  45.0 1999-03-06  37.109215
2    1999-03-07  45.0 1999-03-07  37.049726
3    1999-03-08  45.0 1999-03-08  36.987036
4    1999-03-09  45.0 1999-03-09  36.926852
5    1999-03-10  45.0 1999-03-10  36.864715
6    1999-03-11  45.0 1999-03-11  36.771622
7    1999-03-12  45.0 1999-03-12  36.712117
8    1999-03-13  45.0 1999-03-13  36.646144
9    1999-03-14  45.0 1999-03-14  36.578244
...         ...   ...        ...        ...
7356        NaT   0   2019-04-25   8.321119
7357        NaT   0   2019-04-26   8.315796

In order to do that, I am using this function:

df['New'] = np.where(df['y']!=0, df['y'], df['yhat'])

But I get an error saying:

KeyError: 'y'

case statements for different date columns

I'm facing issues while writing the below code in SQL developer:

 'If Trim$(psFromDate) <> "" and NOT ISNULL(psFromDate) AND Trim$(psToDate) <> "" and NOT ISNULL(psToDate) Then
select case ps_datetype
 CASE "CTA"
    wc = wc & " AND (trunc(sf_get_local (p_con.created_date,p_con.cdate_tz_code)) Between "
    wc = wc & " TO_DATE (" & "'" & sFromDate & "'" & ", 'DD/MM/YYYY') "
    wc = wc & " AND TO_DATE (" & "'" & sToDate & "'" & ", 'DD/MM/YYYY'))"
 'CASE "ATA" 
 CASE "VAD" 
    wc = wc & " AND trunc(sf_get_local(route_s.orgn_vsl_arvl_date,route_s.orgn_vsl_arvl_date_tz_code)) Between "
    wc = wc & " TO_DATE (" & "'" & sFromDate & "'" & ", 'DD/MM/YYYY') "
    wc = wc & " AND TO_DATE (" & "'" & sToDate & "'" & ", 'DD/MM/YYYY')"
 CASE "ETA"
    wc = wc & " AND TRUNC(sf_get_local(route_s.arrival_date,route_s.arrival_date_tz_code)) Between "
    wc = wc & " TO_DATE (" & "'" & sFromDate & "'" & ", 'DD/MM/YYYY') "
    wc = wc & " AND TO_DATE (" & "'" & sToDate & "'" & ", 'DD/MM/YYYY')"
END SELECT
'End If

I tried the below code but no luck:

Where (case when pstatustype='CTA' then (p_con.created_date Between     to_date('&1','DD-MON-YYYY:HH24:MI:SS')
                                AND to_date('&2','DD-MON-YYYY:HH24:MI:SS'))
        when pstatustype='VAD' then (route_s.orgn_vsl_arvl_date Between     to_date('&1','DD-MON-YYYY:HH24:MI:SS')
                                AND to_date('&2','DD-MON-YYYY:HH24:MI:SS'))
        when pstatustype='ETA'  then (route_s.arrival_date Between  to_date('&1','DD-MON-YYYY:HH24:MI:SS') 
                                AND to_date('&2','DD-MON-YYYY:HH24:MI:SS'))
        else NULL end)

getting an error missing parenthesis. In then it is not taking BETWEEN operator. Please help, how i can write this code in SQL developer.

Regards, fuko

If else formatting Visual Studio not indenting correctly

So this is going to be a kind of strange question, I have never run into this formatting issue with any other programs I have written. I think it is because my if statements has multiple || which needed multiple lines to make it appear more readable.

Notice the dotted line under my else if(). It is getting shifted right for some reason under the if instead of the else.

enter image description here

Is there some kind of formatting setting that can fix this? Or is there a different way I am supposed to do this else if statement? Having all those OR checks is pretty much necessary but I did not wan't to put them all on a single line as that would look real ugly.

Thanks!

Google Apps Script - Sheets - IF statement in a script

I have 300,000 cells that all use the same base IF statement (copying/pasting over and down updates the respective row or column reference). This is used to populate a Gantt chart, comparing the column header's date value to another cell in the same row. Depending on the values found, the outputs are a letter, or nothing at all.

The issue is, as you can imagine, performance - it's very very slow. Any time I do anything on the Sheet, it seems, every IF statement is re-evaluated, and the performance is very poor.

Is there a way to remove this IF statement in the cells, and add it as a function, only calling it via a menu when I'd like the Gantt chart to update?

Here's the IF statement:

=IF($K2="N/A","",IF(AND(L$1>=$H2,L$1<=$I2),IF(ISBLANK($E2),"A",IF(ISBLANK($F2),"B",IF($G2="Crew","D","C"))),""))

I've tried a few different ways, but I'm stumped on how a single inputted formula in GAS could be evaluated for every cell with their own respective column and row references?

// Adds a custom menu
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Refresh Data')
  .addItem('Update Gantt', 'setIfForGantt')
  .addToUi();
}

// Set IF statement for Gantt chart
function setIfForGantt() {
  var sheetName = "Project Management";
  var range = "L:CW";

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  var range = sheet.getRange(range);
  var values = range.getValues();
  var formula = ['IF($K2="N/A","",IF(AND(L$1>=$H2,L$1<=$I2),IF(ISBLANK($E2),"A",IF(ISBLANK($F2),"B",IF($G2="Crew","D","C"))),""))'];

Returning If-Else Result Independent of If-Else Order?

If I had the following code:

string x = "123";
string y = "abc";

if (stringVar.Contains(x))
{
    return x;
}
else if (stringVar.Contains(y))
{
    return y;
}

where

string stringVar = "123abc";

it would

return x;

However

stringVar = "abc123";

would also

return x;

Is there a way where instead of following the pre-defined order of the if-else statement, I could have the return result be based upon the order of stringVar instead?

My desired result is if:

stringVar = "123abc";
...
return x;

and if:

stringVar = "abc123";
...
return y;

R Replace values based on conditions (for same ID) without using for-loop

I have a df similar to this one but much bigger (100.000 rows x 100 columns)

df <-data.frame(id=c("1","2","2","3","4","4", "4", "4", "4", "4", "5"), date = c("2015-01-15", "2004-03-01", "2017-03-15", "2000-01-15", "2006-05-08", "2008-05-09", "2014-05-11", "2014-06-11", "2014-07-11", "2014-08-11", "2015-12-19"), A =c (0,1,1,0,1,1,0,0,1,1,1), B=c(1,0,1,0,1,0,0,0,1,1,1), C = c(0,1,0,0,0,1,1,1,1,1,0), D = c(0,0,0,1,1,1,1,0,1,0,1), E = c(1,1,1,0,0,0,0,0,1,1,1), A.1 = c(0,0,0,0,0,0,0,0,0,0,0), B.1 = c(0,0,0,0,0,0,0,0,0,0,0), C.1 = c(0,0,0,0,0,0,0,0,0,0,0), D.1 = c(0,0,0,0,0,0,0,0,0,0,0), E.1 = c(0,0,0,0,0,0,0,0,0,0,0), acumulativediff = c(0, 0, 4762, 0, 0, 732, 2925, 2956, 2986, 3017, 0))

What I have to accomplish is this:

structure(list(id = structure(c(1L, 2L, 2L, 3L, 4L, 4L, 4L, 4L, 4L, 4L,5L), .Label = c("1", "2", "3", "4", "5"), class = "factor"), date = structure(c(9L, 2L, 11L, 1L, 3L, 4L, 5L, 6L, 7L, 8L,10L), .Label = c("2000-01-15", "2004-03-01", "2006-05-08","2008-05-09", "2014-05-11", "2014-06-11", "2014-07-11", "2014-08-11","2015-01-15", "2015-12-19", "2017-03-15"), class = "factor"), A = c(0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1), B = c(1, 0, 1, 0,1, 0, 0, 0, 1, 1, 1), C = c(0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0), D = c(0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1), E = c(1, 1, 1,0, 0, 0, 0, 0, 1, 1, 1), A.1 = c(0, 0, 4762, 0, 0, 732, 2925,0, 0, 3017, 0), B.1 = c(0, 0, 0, 0, 0, 732, 0, 0, 0, 3017,0), C.1 = c(0, 0, 4762, 0, 0, 0, 2925, 2956, 2986, 3017,
0), D.1 = c(0, 0, 0, 0, 0, 732, 2925, 2956, 0, 3017, 0),E.1 = c(0, 0, 4762, 0, 0, 0, 0, 0, 0, 3017, 0), acumulativediff = c(0, 0, 4762, 0, 0, 732, 2925, 2956, 2986, 3017, 0)), .Names = c("id","date", "A", "B", "C", "D", "E", "A.1", "B.1", "C.1", "D.1", "E.1", "acumulativediff"), row.names = c(NA,-11L), class = "data.frame") 

The idea is to replace 0's from A.1, B.1, C.1 columns with the values of 'acumulativediff' column, based on two conditions:

df[i,1]  == df[i-1,1] & df[i,names] == "1" & df[i-1,names] == "1", df[i,diff]
df[i,1]  == df[i-1,1] & df[i,names] == "0" & df[i-1,names] == "1", df[i,diff]

I was able to do it, using a non-efficient loop-for which seems to work on small df but not with bigger ones (it takes almost two hours)

names <- colnames(df[3:7])
names2 <- colnames(df[8:12])
diff <- which(colnames(df)=="acumulativediff")
for (i in 2:nrow(df)){
df[i,names2] <- ifelse (df[i,1]  == df[i-1,1] & df[i,names] == "1" & 
df[i-1,names] == "1", df[i,diff],
      ifelse (df[i,1]  == df[i-1,1] & df[i,names] == "0" & df[i-1,names] == "1", df[i,diff], 0))}

Any idea or advice to omit the loop to achieve a more efficient code?

executing these two codes after each other with an if statement

if (m>1){

        if (x1>=0 || x1<0) {
            System.out.println("Please enter the values of f(x1): \n");
            for (int i = Koef.length-2; i >=0; i--) { // gives the length of my row (m)
                for (int j =Koef[0].length-1; j>=0;j--) { //gives the length of my column (n).
                    Koef[0][j] = readInteger("Enter the values of your coeffecients: "
                                            +"f(x1), Coeffecient" +(j)+": "); // readInteger takes an input from the user
                }
                    System.out.println();
            }
        }

//MY PROBLEM is here
//I was trying to execute this code below too after the code above finishes, but somehow it never reaches to it

        if(x2>=0 || x2<0) {
            System.out.println("Now enter the value of f(x2):  \n");
            for (int i = Koef.length-2; i >=0; i--) { 
                for (int j =Koef[0].length-1; j>=0;j--) { 

                    Koef[1][j] = readInteger("Enter the value of coefficients: "
                                            +"f(x2), Coefficient" +(j)+": ");
                }
            }
        }
====================================================================

//This what happens in the testClass:

if (m==2) {
int n = 1+readInteger("Which polynomial degree do you want to enter for f(x1)?");
                int x1 = readInteger("please enter the value of x1:");
                polynom pol1 = new polynom (m,n,x1,0); //m-2 = array 0 & n +1 = polynomial degree of array 0

// m is first array, n is second array, x1 is the value of 1st polynomial x2 value of 2nd

int n = 1+readInteger("Which polynomial degree do you want to enter for f(x2)?");
                int x2 = readInteger("Please enter the value of x2:");
                polynom pol2 = new polynom (m,n,0,x2);
}

I already tried not to use the if statements, but I got as a print of f(x1) and f(x2) with the first given power and then got both results again with the 2nd given power.

What I want is: to get f(x1) with the first power (n) and f(x2) with the second power Each, one time only.

I would be grateful if you can get me out of this predicament Thanks for any help :)

Validate parts of URLs with PHP

I'm trying to check against an array of URL's with PHP, but one of the URL's will have some random strings in front of it (generated sub domain).

This is what I have so far:

<?php
$urls = array(
    '127.0.0.1',
    'develop.domain.com'
);
?>

<?php if (in_array($_SERVER['SERVER_NAME'], $urls)) : ?>
//do the thing
<?php endif; ?>

The only thing is that the develop.domain.com will have something in front of it. For example namething.develop.domain.com. Is there a way to check for a wildcard in the array of URL's so that it can check for the 127.0.0.1 and and matches for develop.domain.com?

Creating an if/else Statement so Page Changes Based on Cursor Value

I'm creating a gardening game for kids. The user clicks on the gardening tool (e.g. shovel) they need and then they click on the background image of the field which will take them to the next step/page (e.g. background image of plowed field). The javascript function that changes the cursor to the image of the tool works fine. However, I notice the background image changes on any click which is not what I want. It should only change when the cursor has the right value (i.e. shovel).

To resolve this problem, I thought it might be best to use a second function in the form of an if/else statement.

<script>
 function myFunction() {

  document.body.style.cursor = "url(img/Shovel.png), pointer";

}

function changePage() {
  var cursor = document.body.style.cursor;

  if (cursor === "url(img/Shovel.png)") {
    window.location.href = "Potato1.html";
  } else {
    window.location.href = "Potato0.html";
  }
}

It's not working as I thought it would, the page automatically changes to the next one. I'm wondering if my logic makes sense so I would appreciate some guidance.

Conditional substring

I have a table similar to:

--- ID ----  ErrorDescr ---
    1        Error: ERROR1 - ESK - motor problem
    1        Error: ERROR13 - EPN - window problem
    1        Human problem 

What i want:

--ID--ErrorType---Count
  1   ESK            1
  1   EPN            1
  1   Human problem  1

if the "ErrorDescr" starts with Error:... the i want substring after "-" and get the 3 char error code, but if there is no Error:... I just take the text....and count the instances of those text...

Anyone ?

Can I use a IF statement for Accept command

I would like to know if you can put an IF statement before DECLARE, where you can declare the input variables with the ACCEPT statement EX

basic example.

ACCEPT V_epno PROMPT 'Enter employee name: '
DECLARE
     v_cepno CHAR(20);
BEGIN
     SELECT cepno INTO v_cepno 
            FROM employee
     WHERE cepno = '&V_epno ';
END;

I want something like this

ACCEPT V_epno PROMPT 'Enter employee name: '
IF '&v_epno' = 'john' then
  ACCEPT V_epsu PROMPT 'Enter employee surname: '
END IF;
DECLARE
     v_cepno CHAR(20);
     v_cepsu CHAR(20);
BEGIN
     SELECT cepsu INTO v_cepsu 
            FROM employee
     WHERE cepno = '&V_epno'
      and cepsu = '&V_epsu';
END;

but if I run this example, the program skips the if statement.

How to use else/if in password input?

i wrote a program that users can login. below u see some codes that i wrote for password input but the second if of them dos not work properly.please help me to find the problem. why it dos not work?

import java.util.Scanner;

public class Elevator {

    public static void main(String[] args) {

        Scanner passwordInput = new Scanner(System.in);
        System.out.print("Please enter your password: ");
        int builtInPassword=1254;

        if (passwordInput.hasNextInt() && passwordInput.nextInt()==builtInPassword) {
            System.out.println("Your password is correct.");
        } 


        else if(passwordInput.hasNextInt() && passwordInput.nextInt()!=builtInPassword){
            System.out.println("The password entered is incorrect");
        }



        else {
            System.out.println("Sorry, please enter the right format");
        }




    }

}

mardi 29 mai 2018

Click function never reading else statement to remove class

I have been stuck on a sliding down menu, but have made some headway with it. I had to modify a lot to make it work for both desktop and mobile viewports. The only thing I am stuck on now is getting the menu to close in a < 640px viewport. In my snippet and jsfiddle below there is a lot of code, but the only code that really matters to this question is the javascript below:

$('#serviceClick').click( function () {
    var relative = $(this);
    if (!relative.hasClass('activeSol')) {
        $('#serviceNav').removeClass('activeSol');
        $('#serviceNav').addClass('activeSol').slideDown();
    } else  {
        $('#serviceNav').removeClass('activeSol').slideUp(500);
    }
    return false;
});

Basically my else statement is now removing the class 'activeSol` and then sliding up the selection.

In the mobile viewport, after clicking on "Solutions" the menu expands, but when you click on "Solutions" again, nothing happens.

enter image description here

It seems as if the variable relative is never reading as the class appended to it, making the click function run else. I did a simple console.log and the else never runs. I tried changing the click function to a change, but then the menu never triggers.

Does anyone see what is causing my else statement to not removeClass from serviceNav and slideUp?

JSfiddle link to see in mobile viewport.

$('#serviceClick').click( function () {
                var relative = $(this);
                if (!relative.hasClass('activeSol')) {
                        $('#serviceNav').removeClass('activeSol');
                        $('#serviceNav').addClass('activeSol').slideDown();
                } else  {
                        $('#serviceNav').removeClass('activeSol').slideUp(500);
                }
                return false;
        });
        $('[data-pop-close]').on('click', function(e)  {
                //var targeted_pop = $(this).attr('data-pop-close');
                $('#serviceNav').removeClass('activeSol');
                $('body').css('overflow', 'auto');
                e.preventDefault();
        });
nav {
        background: #FFF;
        height: 70px;
        width: 100%;
        max-width: 100%;
        box-shadow: 0px 6px 15px -4px rgba(0,0,0,0.12);
        position: fixed;
        top: 0;
        z-index: 999;
        box-sizing: border-box;
}
#nav-logo {
        float: left;
        height: 100%;
        width: auto;
        display: block;
        position: relative;
        margin-left: 5%;
}
#nav-logo img {
        height: 80%;
        width: auto;
        position: absolute;
        top: 50%;
        transform: translateY(-50%);-webkit-transform: translateY(-50%);
}
#mobile-button {
        background-image: url("https://s3.us-east-2.amazonaws.com/mbkitsystems/menu.svg");
    background-size: 30px 30px;
        float: right;
        width: 30px;
        height: 30px;
        margin-right: 5%;
        margin-top: 15px;
        cursor: pointer;
        display: none;
        transition: ease 0.3s;-webkit-transition: ease 0.3s;
}
#mobile-button:hover {
        transition: ease 0.3s;-webkit-transition: ease 0.3s;
}
#nav-pop {
        float: right;
        display: block;
        margin-right: 5%;
        margin-top: 25px;
        transition: ease 0.5s;-webkit-transition: ease 0.5s;
}
#nav-pop.active {
        opacity: 1;
        background: rgba(0,0,0,0.8);
        background: #2f2f2f;
        right: 0;
        margin-top: 0;
        margin-right: 0;
        z-index: 999999;
        transition: ease 0.6s;-webkit-transition: ease 0.6s;
        transform: translateX(0);-webkit-transform: translateX(0);
        box-shadow: -9px 0px 9px 1px rgba(0,0,0,.2);
}
#nav-list li {
        display: inline-block;
        margin: 0 17px;
        vertical-align: top;
}
#nav-list li:first-child {
        margin-left: 0px;
}
#nav-list li:last-child {
        margin-right: 0px;
}
#nav-list li a, #serviceClick {
        text-decoration: none;
        font-family: 'Muli', sans-serif;
        font-size: .9rem;
        color: #747678;
        letter-spacing: 1px;
        vertical-align: top;
        transition: all .3s;-webkit-transition: all .3s;
        cursor: pointer;
}
#nav-list li a:after, #serviceClick:after {
        content: '';
    display: block;
        width: 0;
        margin-top: 6px;
        background: #b82222;
        height: 2px;
        transition: width .3s;
}
#nav-list li a:hover, #serviceClick:hover {
        color: #4b4b4b;
        transition: all .3s;-webkit-transition: all .3s;
}
#nav-list li a:hover:after, #serviceClick:hover:after {
    width: 100%;
    transition: width .3s;
}
#nav-list li a.navInverse {
        padding: 10px 12px;
        border-radius: 2px;
        box-sizing: border-box;
        font-family: 'Muli', sans-serif;
        font-size: 1.2rem;
        color: #FFF;
        border: 1px solid #b82222;
        background: linear-gradient(to right bottom, #b82222, #a51e1e);
        text-transform: uppercase;
        text-decoration: none;
        cursor: pointer;
}
#nav-list li a.navInverse:hover {
        background: #b82222;
        background: #FFF;
        color: #b82222;
        /*transition: all 0s;-webkit-transition: all 0s;*/
}
#nav-list li a.navInverse:after {
        content: '';
    display: none;
        width: 0px;
        height: 0px;
        transition: none;
}
#nav-pop-close {
        display: none;
}
#nav-pop-close, #close-panel {
        position: relative;
        top: 3%;
        left: 90%;
        background-image: url("https://s3.us-east-2.amazonaws.com/mbkitsystems/icon_close.png");
        background-size: 30px 30px;
    background-repeat: no-repeat;
        height: 30px;
        width: 30px;
        cursor: pointer;
}
/*- Service NAV -*/
#serviceNav {
    width: 100%;
    top: -40vh;
        left: 0;
    z-index: -1;
    position: fixed;
    background-color: rgba(0,0,0,0);
    height: 40vh;
    transition: all .4s;
        padding: 20px 0;
}
#serviceNav.activeSol {
    top: 0;
    width: 100%;
    background-color: rgba(0,0,0,.9);
    z-index: 99999;
        height: 40vh;
}
.popup-close {
        position: absolute;
        right: 12px;
        top: 12px;
        width: 32px;
        height: auto;
}
#serviceNavInner {
        margin: 0 5%;
        height: 100%;
        position: relative;
}
/*--- Block 1 ---*/
#serviceNavBlock1 {
        width: 33%;
        height: 100%;
        border-right: 1px solid rgba(255,255,255,.5);
        position: relative;
}
#serviceNavBlock1Wrap {
        width: 80%;     
        text-align: left;
}
/*--- Block 2 ---*/
#serviceNavBlock2 {
        width: 66.6%;
        height: 100%;
        margin: 10px auto;
        position: relative;
}
.servNavItemWrap {
        display: inline-block;
        vertical-align: top;
        width: 25%;
        margin-bottom: 50px;
        text-align: center;
        cursor: pointer;
        -webkit-backface-visibility: hidden;
}
.servNavItemWrap img {
        width: 75px;
        height: 75px;
        -webkit-transition: all 0.25s;transition: all 0.25s;
}
.servNavItemWrap:hover img {
        -webkit-transition: all 0.25s;transition: all 0.25s;
    -webkit-transform: scale(1.1);transform: scale(1.1);
        -webkit-backface-visibility: hidden;
}
.servNavItemWrap a {
        text-decoration: none;
        outline: none;
        box-sizing: border-box;
}
.servNavItemTitle {
        margin-top: 5px;
        -webkit-transition: all 0.25s;transition: all 0.25s;
}
.servNavItemWrap:hover .servNavItemTitle {
        color: #FFF;
        -webkit-transition: all 0.25s;transition: all 0.25s;
}

/*---------------------------------------------- MEDIA QUERY 640 --------------------------------------------*/

@media screen and (max-width:640px) {
  
  #mobile-button {
        display: block;
}
#nav-pop {
        float: none;
        opacity: 0;
        position: fixed;
        margin-top: 0;
        width: 75%;
        right: -100%;
        height: 100vh;
        transform: translateX(100%);-webkit-transform: translateX(100%);
}
#nav-pop-close {
        display: block;
        background-size: 20px 20px;
        height: 20px;
        width: 20px;
}
#nav-list {
        margin-top: 20px;
}
#nav-list li {
        display: block;
        position: relative;
        width: 100%;
        margin: 0;
        padding: 20px 10%;
        background: linear-gradient(to bottom right, #151515, #2f2f2f);
        background: #2f2f2f;
        text-align: left;
        cursor: pointer;
        border-bottom: .3px solid #FFF;
}
#quoteButton {
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
}
#nav-list li:hover #quoteButton {
        background: #2f2f2f;
}
#nav-list li:hover, #nav-list li:active {
        background: #000;
}
#nav-list li:first-child {
        margin-left: 0;
}
#nav-list li:last-child {
        margin: 20px auto;
        text-align: center;
        border-bottom: none;
        background: #2f2f2f;
        padding: 20px 0;
}
#nav-list li a, #serviceClick {
        font-family: 'Nunito', sans-serif;
        font-size: .8rem;
        color: #FFF;
        letter-spacing: .3rem;
}
#nav-list li a:after, #serviceClick:after {
    display: none;
}
#nav-list li a:hover, #serviceClick:hover {
        color: #FFF;
}
#nav-list li a:hover:after, #serviceClick:hover:after {
    width: 0%;
}
/*- Service NAV -*/
#serviceNav {
    width: 100%;
    z-index: 1;
    position: relative;
    background-color: rgba(0,0,0,0);
    height: 200px;
    transition: all .4s;
        padding: 10px 0;
        display: none;
        top: 0;
}
#serviceNav.activeSol {
    background-color: #000;
    z-index: 9999999;
        height: auto;
        min-height: 20%;
        top: 0;
        border-bottom: .01em solid #FFF;
}
.popup-close {
        display: none;
}
#serviceNavInner {
        margin: 0 2.5%;
}
/*--- Block 1 ---*/
#serviceNavBlock1 {
        width: 100%;
        height: 50px;
        border-right: none;
        display: block;
        position: relative;
}
#serviceNavBlock1Wrap {
        width: 100%;
        text-align: center;
}
#navOverviewT, #navOverviewP {
        display: none;
}
#solOverviewB {
        font-size: .7rem;
}
/*--- Block 2 ---*/
#serviceNavBlock2 {     
        width: 100%;
        height: 100%;
        margin: 10px auto;
        display: block;
}
.servNavItemWrap {
        display: inline-block;
        width: 25%;
        margin-bottom: 15px;
}
.servNavItemWrap img {
        width: 30px;
        height: 30px;
}
.servNavItemTitle {
        margin-top: 5px;
        font-size: .5rem;
}

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav>
        <div id="nav-logo">
        </div>
        <div id="mobile-button"><img src="" class="hidden" alt=""></div>
        <div id="nav-pop">
        <div id="nav-pop-close"></div>
                <ul id="nav-list">
                        <li><a href="http://localhost:8080/about.php">ABOUT</a></li>
                        <li id="serviceClick">SOLUTIONS</li>
                        <div id="serviceNav">
                                <div id="serviceNavInner">
                                        <div id="serviceNavBlock1" class="iblock">
                                                        <a href="http://localhost:8080/solutions.php"><button class="buttonInv2" id="solOverviewB">Solutions Overview</button></a>
                                        </div><div id="serviceNavBlock2" class="iblock">
                                        </div>
                                </div>
                        </div>
                        <li><a href="http://localhost:8080/learn.php">LEARN</a></li>
                        <li><a href="http://localhost:8080/contact.php">CONTACT</a></li>
                        <li><a href="http://localhost:8080/quote.php" class="navInverse" id="quoteButton">REQUEST QUOTE</a></li>
                </ul>
        </div>
</nav>

IF statement - Unity c#

I don't understand why it isn't working. When I pick up the Shield Powerup, it turns canShield from false to true. But then, when I'm damaged, it is supposed to turn it back to false but it doesn't. It keeps true for the entire game.

public void Damage()
{
    if(canShield == true)
    {
        canShield = false;

        return;
    }

    _life--;


    if(_life < 1)
    {
        Destroy(this.gameObject);
        Instantiate (_explosionPrefab, transform.position, Quaternion.identity);
    }
}

How to Use Multiple IF Conditions in C#

I want to store multiple values in different SESSIONS for that I have Multiple If Conditions in VB Code that Works fine

   If roleRow.Item("Code").ToString() = "101" Then 'Admin Settings
                            If roleRow.Item("Active") = True Then Session("101") = True Else Session("101") = False
                        End If
                        If roleRow.Item("Code").ToString() = "102" Then 'Summaries / Reports
                            If roleRow.Item("Active") = True Then Session("102") = True Else Session("102") = False
                        End If
                        If roleRow.Item("Code").ToString() = "103" Then 'Invoices List
                            If roleRow.Item("Active") = True Then Session("103") = True Else Session("103") = False
                        End If

**but same code structure doesn't work in C# ** It evaluate only first IF Condition and rest conditions it shows the same value as first IF Condition. Any Suggestions how to solve this.....

if (dRow["Code"].ToString() == "104" && (Boolean)dRow["Active"] == true)
                {
                    Session["104"] = true;
                }
                else
                {
                    Session["104"] = false;
                }

                if (dRow["Code"].ToString() == "105" && (Boolean)dRow["Active"] == true)
                {
                    Session["105"] = true;
                }
                else
                {
                    Session["105"] = false;
                }

                if (dRow["Code"].ToString() == "106" && (Boolean)dRow["Active"] == true)
                {
                    Session["106"] = true;
                }
                else
                {
                    Session["106"] = false;
                }

Why does this if statement work but this other solution does not?

Im doing this for a dice game where the player is switched if either dice rolled is a 1 or if 6 is rolled twice in a row. My friends code worked but mine didn't, It looks like my if statement accomplishes the same thing.

This code works(friends code):

if (dice === 1 || diceTwo === 1) {
    nextPlayer();
} else if (doubleSix === 6) {
    if (dice === 6 || diceTwo === 6) {
        roundScore = 0;
        score[activePlayer] = 0;
        nextPlayer();
    }
} else {
    roundScore += (dice + diceTwo);
    document.querySelector('#current-' + activePlayer).textContent = roundScore;
    doubleSix = dice;
}

This code does not (my code):

if (dice !== 1 || diceTwo !== 1) {
    //Add score
    if (doubleSix === 6 && dice === 6) {
        roundScore = 0;
        score = 0;
        nextPlayer();
    } else if {
        roundScore += (dice + diceTwo) ;
        document.querySelector('#current-' + activePlayer).textContent = roundScore;
        doubleSix = dice;
    }
    } else {
    //Next Player
    nextPlayer();
}

Laravel if no data from select many to many relation

How to check whether there's data from database or not
My DB looks like this

enter image description here

My user Model

public function monsters()
{
    return $this->belongsToMany('App\Monster')->orderBy('star');
}

My Controller

public function list_monster_user()
{
    //GET USER LOGIN ID
    $id = Auth::user()->id;

    $monster_user = User::find($id);

    //IF DATA IS NOT EMPTY OR USER HAVE MONSTERS
    if(!is_null($monster_user->monsters))
    {
        return 'yes';
    }

    //IF DATA IS EMPTY OR USER DOESNT HAVE ANY MONSTER
    else
    {
        return 'nope';
    }
}

I'm using ajax, so the result will be return to ajax.
I don't get the return I want. I know something's wrong with my if statement.
But I couldn't figure it out.

Formatting Cells with Numeric values as Numbers

a very trivial question for you illuminated lot. I am basically trying to identify each cell in a range which has a numeric value, and then format it as 'number' (hence overlooking those cells which contain a string). I have found an excel formula which uses an IF and TRUE/FALSE expression to figure out which cell match the condition, but when running the code in VBA I cannot seem to store the IF statement?

It is probably very silly, as I am new to VBA, but would appreciate all the help!

Code below:

Sub formatnumbers()

Dim rng As Range
Dim cell As Range

Set rng = ActiveSheet.Range("A1:N10")

For Each cell In rng
 cell.Select
         If cell.Formula = "=COUNT(FIND({0,1,2,3,4,5,6,7,8,9},cell))>0, TRUE, FALSE)" = True Then
            cell.NumberFormat = "0.00"
         End If

Next cell

End Sub

php update array value in foreach loop with if condition

I want to update array data which comes in foreach loop. I am trying with script given below, it is only updating the very last row of data and giving error in this line -

if ($updateInvoiceAddedItems AND $updateInvoiceSubtractedItems) .

PHP script

if (isset($_POST['submit'])) {

foreach($_POST['data'] as $key => $value) {
    $invoiceItemId = intval($value['invoiceItemId']);
    $itemId = intval($value['ItemId']);
    $QTY = intval($value['QTY']);
    $addedQTY = intval($value['addedQTY']);
    $subtractedQty = intval($value['subtractedQty']);
    $Total = is_numeric($value['total']) ? $value['total'] : false;

    try {

        if($addedQTY > 0) {
            $updateInvoiceAddedItems = $db - > prepare("UPDATE `invoiceItems` SET 
            qty = qty + : addedQTY,
            addedQty = addedQty + : addingQTY where id = : Iid ");

            $updateInvoiceAddedItems - > execute(array(':Iid' => $itemId, ':addedQTY' => $addedQTY, ':addingQTY' => $addedQty));

        }
        elseif($subtractedQty > 0) {
            $updateInvoiceSubtractedItems = $db - > prepare("UPDATE `invoiceItems`  SET 
            qty = qty - : subtractedQty,
            subtractedQty = subtractedQty + : subtractingQty where id = : iiId ");

            $sub_invoiceItems - > execute(array(':iiId' => $itemId, ':subtractedQty' => $subtractedQty, ':subtractingQty' => $subtractedQty));


        }

        if ($updateInvoiceAddedItems AND $updateInvoiceSubtractedItems) {
            echo ' <script> alert("success") </script>';
            exit;

        } else {
            echo ' <script> alert("Error") </script>';
        }
    } catch (PDOException $e) {
        echo 'Connection failed: '.$e - > getMessage();
    }
  }
}

Not working IF condition between arrays [on hold]

This code cannot read the if condition, if replaced Node[i] with number it run easily

for j in range (0,m):
   #print(Distance[i][j])
   if(Node[i]==Distance[i][j]):
        print(Distance[i][j])

if else multiple conditions comparing rows

I am strugling with this loop. I want to get "6" in the second row of column "Newcolumn".I get the following error.

Error in if (mydata$type_name[i] == "a" && mydata$type_name[i -  : 
missing value where TRUE/FALSE needed.

The code that I created:

id  type_name   name    score   newcolumn
1   a   Car 2   2
1   a   van 2   6
1   b   Car 2   2
1   b   Car 2   2

mydata$newcolumn <-c(0)
for (i in 1:length(mydata$id)){
  if ((mydata$type_name [i] == "a") && (mydata$type_name[i-1] == "a") && ((mydata$name[i]) != (mydata$name[i-1]))){
    mydata$newcolumn[i]=mydata$score[i]*3 }
  else {
    mydata$newcolumn[i]=mydata$score[i]*1
  }
}

Thank you very much in advance

conditionally replace values in preceding rows in R

I would like to replace values in previous row(s) conditional on values in other columns.

This is an example of my data that has minutes/day spent in various activities.

activity <- c("car","soccer","eat","drink")
category <- c("travel","sport","eat/drink","eat/drink")
duration <- c(75,15,10,160)
df <- data.frame(activity, category,duration)

   activity  category duration
1      car    travel       75
2   soccer     sport       15
3      eat eat/drink        5
4    drink eat/drink      160

If in any row, duration of "drink" is > 5 minutes (as it is in row 4), I want to replace "duration" in that row with 5 minutes, and add the remaining time (in this case 155 minutes) to the "duration" value in the preceding row, UNLESS the preceding row has "eat/drink" as its "category", in which case I want to add the remaining time to "duration" of the row before the preceding row...

In the above example, I would add 155 minutes to "duration" in row 2. However, if row 2 also had "eat/drink" as its "category", I would want to add the 155 minutes to the preceding row (row 1).

Thanks for any help!

R round product between positive real numbers x and y to between 0 and 1 efficiently

I am having this function to make products between two positive number that returns the product if this it less or equal to 1, otherwise returns 1.

f1 <- function(x, y) ifelse(x*y <= 1, x*y, 1)

It annoys me that I have to do the x*y calculation twice - is there a base R function that can do this, or another way to do the task ? I am aware that the difference in computing time perhaps is small (is it O vs 2*O ?) but still ... and out of curiosity.

Javascript - Add class to a class (not ID)

In a HTML file i load a javascript file (in the header) which contains some code. In that code it checks if a cookie exists. If the cookie doesn't exists it should add a class to a div which should be matched with a class.

Example:

The class where it should add the class:

<header class="firstClass">

The javascript:

var classcode = document.getElementsByClassName("firstClass");

if (myCookie == null) {
    add class "secondClass" to "firstClass";
}

I've tried several things but I can't get it to work...

I should mention, the javascript file is loaded before the div where the class should be added.

Add time increment, based on ifelse statement/ another column, to POSIXct

My dataset includes time-stamped events that occur during rounds of team-sport matches. Each round 5 minutes in duration. I wish to add the cumulative time that each time stamp occurs however, I only have the time an event occurs within a specified time.

An example of my dataset is:

 > head(OutcomeData$Match_EndingRound, 15)
 [1] 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2
> head(OutcomeData$TimeStamp, 15)
 [1] "1899-12-31 00:02:36 UTC" "1899-12-31 00:02:36 UTC" "1899-12-31 00:03:01 UTC" "1899-12-31 00:03:01 UTC" "1899-12-31 00:03:21 UTC"
 [6] "1899-12-31 00:03:21 UTC" "1899-12-31 00:04:37 UTC" "1899-12-31 00:04:37 UTC" "1899-12-31 00:02:19 UTC" "1899-12-31 00:02:19 UTC"
[11] "1899-12-31 00:02:19 UTC" "1899-12-31 00:02:19 UTC" "1899-12-31 00:02:09 UTC" "1899-12-31 00:02:09 UTC" "1899-12-31 00:02:09 UTC"

dput(head(OutcomeData$TimeStamp, 15))
structure(c(-2209075044, -2209075044, -2209075019, -2209075019, 
-2209074999, -2209074999, -2209074923, -2209074923, -2209075061, 
-2209075061, -2209075061, -2209075061, -2209075071, -2209075071, 
-2209075071), class = c("POSIXct", "POSIXt"), tzone = "UTC")

I wish to add 5 minutes to the time-stamped data, for every round = 2. When rounds are equal to 3, 4 and 5 (not displayed in my example), I wish to add 10, 15 and 20 minutes, respectively.

I have attempted the following:

OutcomeData$CumulativeTime <- ifelse(OutcomeData$Match_EndingRound==1, OutcomeData$TimeStamp,
                              ifelse(OutcomeData$Match_EndingRound==2, OutcomeData$TimeStamp + 300,
                              ifelse(OutcomeData$Match_EndingRound==3, OutcomeData$TimeStamp,
                              ifelse(OutcomeData$Match_EndingRound==4, OutcomeData$TimeStamp,
                              ifelse(OutcomeData$Match_EndingRound==5, OutcomeData$TimeStamp + 1200, OutcomeData$TimeStamp)))))

Although I ended up with this output and unsure where I have gone wrong?

 head(OutcomeData$CumulativeTime, 15)
 [1] -2209075044 -2209075044 -2209075019 -2209075019 -2209074999 -2209074999 -2209074923 -2209074923 -2209074761 -2209074761 -2209074761 -2209074761
[13] -2209074771 -2209074771 -2209074771

My anticipated output would be:

> head(OutcomeData$TimeStamp, 15)
     [1] "1899-12-31 00:02:36 UTC" "1899-12-31 00:02:36 UTC" "1899-12-31 00:03:01 UTC" "1899-12-31 00:03:01 UTC" "1899-12-31 00:03:21 UTC"
     [6] "1899-12-31 00:03:21 UTC" "1899-12-31 00:04:37 UTC" "1899-12-31 00:09:37 UTC" "1899-12-31 00:07:19 UTC" "1899-12-31 00:07:19 UTC"
    [11] "1899-12-31 00:07:19 UTC" "1899-12-31 00:07:19 UTC" "1899-12-31 00:07:09 UTC" "1899-12-31 00:07:09 UTC" "1899-12-31 00:07:09 UTC"

Any assistance would be greatly appreciated. Thank you!

lundi 28 mai 2018

How to use the And function with the Not function in a VBA if statement

I'm very sorry if you can't understand this because i'm having a very hard time trying to explain what i'm trying to do but, basically i'm trying to make a cost sheet table that when you fill it out it will make a list based on what you mark off and if you don't pick some items then the other ones will pump up into that position.Is anyone able to tell me where I'm going wrong here? I'm trying to get it to see if a cell is greater then 0 and if another cell is not equal to the "BBQ" then i want it to say "BBQ"

If Range("'Cost Sheet'!D87", "'Cost Sheet'!D88") > 0 And Not Range("B97") = "     •     BBQ" Then
    Range("B98") = "     •     BBQ"

When I login with id=0 (as Administrator) I want it to show the Admin Menu (and select options from there), not to be overwritten by Student Menu

1.The problem I want to solve is in while(id){ if(id==0){} else if(id!=0){} }. Is there another way how can I solve this problem without while.
So both if and else if statements are executed here, instead of executing only one case. So, when I login with id=0 (as Administrator) I want it to show the Administrator Menu (and select options from administrator menu), not to be overwritten by Student Menu.

*/
#include <stdio.h> 
#include <stdlib.h> 
#include <conio.h> 
#include <windows.h> 
#include <string.h>

void login(int id, char password) {
   printf("\n\t\tLogin: \n");
   printf("\t\tID:\t");
   scanf("%d", & id);
   printf("\n");
   printf("\t\tPassword:\t");
   scanf("%s", & password);
   system("cls");

if (id == 0) {
    system("cls");
    showAdminMenu();
} else if (id > 0) {
    showStudentMenu();
} else {
    printf("\n\n\t\t");
    printf("ID doesn't exist!\n");
    login(id, password);
}
}

void showAdminMenu() {
   printf("ADMINISTRATOR MENU:\n");
   printf("1.Add\n");
   printf("2.Modify\n");
   printf("3.Delete\n");
   printf("4.Exit\n");
}

void showStudentMenu() {
   printf("STUDENT MENU:\n");
   printf("1.Change Password\n");
   printf("2.Register\n");
   printf("3.Report\n");
   printf("4.Exit\n");
}

int main() {
  int userChoice;
  int id;
  char password;
  printf("\n\n");

printf("\t\t1.Login\n");
printf("\t\tPress -1 to exit\n");
printf("\t\tChoice: ");
scanf("%d", & userChoice);

system("cls");

if (userChoice == 1) {
    login(id, password);
} else if (userChoice == -1) {
    exit(1);
}

FILE * fp, * ft; //file pointers
char anotherChoice, choice;

/* structure that represents a astudent*/

struct student {
    char id[15];
    char name[40];
    char password[10];
    int age;
};
struct student s; //create struct student
char studentID[15];
char studentName[40];

long int recsize;

fp = fopen("STUDENT.DAT", "rb+");
if (fp == NULL) {
    fp = fopen("STUDENT.DAT", "wb+");
    if (fp == NULL) {
        printf("File cannot open");
        exit(1);
    }
}

recsize = sizeof(s);

//function inside admin menu
void addStudent() {
    system("cls");
    fseek(fp, 0, SEEK_END);
    anotherChoice = 'y';
    while (anotherChoice == 'y') {
        system("cls");
        printf("\nID:\t");
        scanf("%s", & s.id);
        printf("\nName:\t");
        scanf("%s", & s.name);
        printf("\nPassword:\t");
        scanf("%s", & s.password);
        printf("\nAge:\t");
        scanf("%d", & s.age);

        fwrite( & s, recsize, 1, fp); //writes records in a file
        printf("\nWould you like to add another student(y/n)");
        fflush(stdin);
        anotherChoice = getche();
    }

}

//function inside student menu
void changePassword() {
    system("cls");
    printf("Type a new password:\t");
    scanf("%s", & s.password);
    fseek(fp, -recsize, SEEK_CUR);
    fwrite( & s, recsize, 1, fp);
    printf("\nPassword successfully changed!");

}

while (id) {     //

    if (id == 0) {   //shows admin menu
        system("cls");
        printf("ADMINISTRATOR MENU:\n");
        printf("1.Add\n");
        printf("2.Modify\n");
        printf("3.Delete\n");
        printf("4.Exit\n");
        printf("Choice: ");
        fflush(stdin);
        char choiceFromAdminMenu;
        choiceFromAdminMenu = getch();

        switch (choiceFromAdminMenu) {
        case '1':
            addStudent();
            break;
        case '2':
        //modifyStudent();
        //break;
        case '3':
        //deleteStudent();
        //break;
        case '4':
        //exit();
        //break;

        default:
            printf("\nWrong!Please enter a valid option");
            getch();
        }
    } else if (id != 0) {        //show student menu
        system("cls");   
        printf("STUDENT MENU:\n");  
        printf("1.Change Password\n");
        printf("2.Register\n");
        printf("3.Report\n");
        printf("4.Exit\n");
        printf("Choice: ");
        fflush(stdin);
        char choiceFromStudentMenu;
        choiceFromStudentMenu = getch();

        switch (choiceFromStudentMenu) {
        case '1':
            changePassword();
            break;
        case '2':
        //register();
        //break;
        case '3':
        //report();
        //break;
        case '4':
        //exit(0);
        //break;

        default:
            printf("\nWrong!Please enter a valid option");
            getch();
        }

    }
}

return 0;
}

Simple If statement VBA

I am getting "End if without block if" while executing below code. I have no idea why.Please help.

If erange.Offset(0, 1).Value = "RTN" Then
    If erange.Value = "RASP" Then erange.Offset(0, 11).Value = "a"
    If erange.Value = "FEATHER EDGE" Then erange.Offset(0, 11).Value = "b"
    If erange.Value = "BIG TAPER" Then erange.Offset(0, 11).Value = "c"
    If erange.Value = "SQ & 3SQ" Then erange.Offset(0, 11).Value = "d"
    If erange.Value = "SMALL FLAT" Or erange.Value = "BIG FLAT" Or erange.Value = "BIG MILL" Or _
    erange.Value = "SMALL MILL" Then erange.Offset(0, 11).Value = "e"
    If erange.Value = "HALF ROUND" Then erange.Offset(0, 11).Value = "f"
    If erange.Value = "CHAINSAW" Then erange.Offset(0, 11).Value = "g"
    End If
End If

PHP PUT method if statment issue

here's a code snippet:

var_dump($_SERVER['REQUEST_METHOD']);
if (
$_SERVER['REQUEST_METHOD'] == 'PUT'
) {
//do things
}

this does not work despite var dump indicates it is indeed a PUT method.

GET,POST,DELETE all ok tough.

I'd appreciate some help.

Printing a value (if there is any value) of a variable when exiting the program

I've made this program below to calculate the average mark of a student. Everything works well until I exit the program using -1, it is supposed to display the average of all students that have been entered and say Goodbye. If no students have been entered and you hit -1 at the start of the program it's supposed to just say goodbye but it still prints the average mark and some crazy number that seemingly comes out of no where.

Can anyone tell me where I'm going wrong with my code, how can I get it to just say goodbye when -1 is entered and how come the final average mark of all students entered is wrong? Thanks in Advance.

#include <stdio.h>

int main(void)
{
float final_mark(int a_mark1, int a_mark2, int lab_mark, int quiz_mark, int exam_mark);
int i, a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark;
float average_mark = 0.0;
do
{
    for (i = 0; i < 2; i++)
    {
        printf("Enter assignment 1 mark (-1 to quit): ");
        scanf("%d", &a_mark1);

        if(a_mark1 == -1)
        {
            average_mark = final_mark(a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark);
            printf("The average student mark is %.2f%% \n", average_mark);
            printf("Goodbye! \n");
            return 0;
        }

        printf("Enter assignment 2 mark: ");
        scanf("%d", &a_mark2);

        printf("Enter laboratory mark: ");
        scanf("%d", &lab_mark);

        printf("Enter quiz mark: ");
        scanf("%d", &quiz_mark);

        printf("Enter exam mark: ");
        scanf("%d", &exam_mark);

        printf("Student %d final mark: %.2f \n", i + 1, final_mark(a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark));
    }
}
while(a_mark1 != -1);
return 0;
}
float final_mark(int a_mark1, int a_mark2, int lab_mark, int quiz_mark, int      exam_mark)
{
float final_mark = a_mark1 * 0.1 + a_mark2 * 0.15 + lab_mark * 0.15 + quiz_mark * 0.1 + exam_mark * 0.5;
return final_mark;
}

How can i display "Conditional" custom text on WooCommerce Order Email

I'm trying to display some "conditional" custom text on the "Order Complete" email, which is sent to the customers when an order is marked as completed.

I have used the following code from, Business Blommer.

Now, I want to make this code conditional, so this code should only be active for the "Gift" Category products. I couldn't find any appropriate Woocommerce functions for this particular functionality.

Any help would be appreciated.

Thank You So Much.

add_action( 'woocommerce_email_before_order_table', 
'bbloomer_add_content_specific_email', 20, 4 );

function bbloomer_add_content_specific_email( $order, $sent_to_admin, $plain_text, $email ) {
if ( $email->id == 'customer_completed_order' ) {
    echo '<p class="email-text-conditional">Thank you for your order with Adventure Clues, we have sent your recipient the gift card’</p>';
}
}

(https://businessbloomer.com/woocommerce-add-extra-content-order-email/)

How to use if statement to declare a new variable with ES6? JavaScript

How can I optionally declare a variable using let or const? For example it would be possible to do:

if (variableNotMade) {
  var makeVariable
}

But how can this be achieved using let or const instead of var?
A similar post here shows that it's possible to do:

let makeVariable = variableNotMade ? foo : bar

Although this approach only really works if you have an else.
Is there a suitable way to achieve this or should a different approach be taken?

Changing one specific word to another word throughout the whole document maintaining case

I'm new to JavaScript and I just can't figure out this one thing.. I'm trying to change the specific word "katt" to "smurf" throughout the whole webpage. Every single "katt" is within a "span" tag and I can change it using this code:

for(var i=0;i<100;i++) {
  changeCat = document.getElementsByTagName("span")[i].innerHTML = "smurf";
}  

The problem is though that every single "smurf" is now only in lowercase letters, even if it's in the beginning of a sentence. I do know I need a if/else to solve my problem but I have no idea how to code it. Any help would be greatly appreciated.

Select interval for a logic if condition

I have a number 0-59, or 60 minutes, and I want to do an if logic for every 5 minutes: 0, 5, 10, 15 and etc. How do I write a good if statement?

Here is what I come up with.

if( ((tmin/5) == thr) && ((tmin%5) ==0 ) ) { //DO Whatever}

It works and all, but I need something faster.

Create a column using based on conditions on other two columns in pandas

I want to create a column in pandas based on the conditions on other two columns. I was trying this with a for loop with if else condition but getting error in checking for string values.

My dataframe:

df=pd.DataFrame({"Area:['USA','India','China','UK','France','Germany','USA','USA','India','Germany'],
         "Sales":[2,3,7,1,4,3,5,6,9,10]})

I want to create a column RATING based on the condition:

If country is in ASIA and Sales >2, then 1

If country is in NA and Sales >3, then 1

If country is in EUR and Sales >=4, then 1 else 0

I am using a function:

ASIA=['India','China']
NA= ['USA']   
EUR=['UK','France','Germany']     
def label_race(row):
 if row['Area'].isin(ASIA) & row['Sales'] >2  :
   return 1
 if row['Area'].isin(NA) & row['Sales'] >3  :
   return 1  
 if row['Area'].isin(EUR) & row['Sales'] >=4  :
   return 1
 return 0  

df['Rating']=df.apply(lambda row: label_race(row),axis=1) 

which is throwing following error:

AttributeError: ("'str' object has no attribute 'isin'", 'occurred at index 0')

Please tell me what am I doing wrong in the function or any other way easier way to do this.

Parse error: syntax error, unexpected 'else' (T_ELSE) on line 10 [duplicate]

This question already has an answer here:

Can someone please give me some guidance on how to deal with this error? I'm not a programmer and so have little to no skills / knowledge about this kind of thing. But, I'm keen to learn, and would be really greatful if someone could give me some guidance.

Parse error: syntax error, unexpected 'else' (T_ELSE) on line 10

The code this relates to is below:

<?php 


include 'desciptions.php';
include 'title.php';
$rand=rand(0,67);


else if($rand=='1')
    $desciptions=$d1;
    $title=$m1;

else if($rand=='2')
    $desciptions=$d2;
    $title=$m2;

else if($rand=='0')
    $desciptions=$d0;
        $title=$m0;
?>

PL/SQL exceptiion handling

I have PL/SQL Anonyms block to work with finding an employees based on their department_id, I written Procedure for that, on that procedure one input and one output

Code:

CREATE OR REPLACE PROCEDURE find_employees(p_dept_no IN 
NUMBER,p_error_message OUT VARCHAR2)
AS 
v_dept_no NUMBER;
dept_chk EXCEPTION;
CURSOR find_emp 
   IS 
SELECT 
    employee_id,
    first_name,
    last_name,
    salary,
    hire_date
FROM    
    employees
WHERE
    department_id = p_dept_no;
BEGIN


-- Check if the department_id in departments table
IF  Condition  THEN /* Need to check the condition here */
    RAISE dept_chk;
END IF;
FOR i in find_emp
LOOP
    dbms_output.put_line(i.employee_id);
    dbms_output.put_line(i.first_name);
    dbms_output.put_line(i.last_name);
    dbms_output.put_line(i.salary);
    dbms_output.put_line(i.hire_date);
END LOOP;       
EXCEPTION
    WHEN dept_chk THEN
    p_error_message:='Please enter valid department number';
END find_employees;

  • How to check if the department_id in departments table

Note:

On that procedure there is one input parameter p_dept_no as INPUT Then p_error_message Is the output parameter

I need to check the if the department_id is in in the departments table then automatically the records will show other wise it's showing an exception so there i need to check the condition how it's possible let me know Thanks in advance.

dimanche 27 mai 2018

Python if-else statements

I have this:

 if (...some text...):
     ...some text...
 elif flag:
     if num >= 2:
         f.write('one')
         if num >= 10:
             flag = False

but this doesn't work. After "elif" there is something happening and code doesn't work right. What should I change?

Unknown or uninitialised column when using Lag in calculation

I am trying to refer to the previous row in the same column inside a calculation for said column. However this always leads to an 'Unknown or uninitialised column' warning message and a lot of NA's.

df$A c( -1, -2, -1, 1, 2, 4 )

df$B <- ifelse(df$A <= 0 , 0, ifelse(lag(df$B,1) == 0,1,2))

This gives me the previously mentioned error. How can i refer to previous rows in the same column when calculating said column?

If statement in python3

I am trying to solve a mathematics combinatorics question in python in which we select a committee of 5 people with female majority from a group of 8 men and 9 females. My code:

import random
people=["m1", "m2", "m3","m4", "m5", "m6" , "m7","m8", "l1", "l2", "l3", "l4", "l5", "l6", "l7", "l8", "l9"]
combinations=[]

for g in range(10000):
    a=random.sample(people, k=5)
    b=a.count("l1")
    b+=a.count("l2")
    b+=a.count("l3")
    b+=a.count("l4")
    b+=a.count("l5")
    b+=a.count("l6")
    b+=a.count("l7")
    b+=a.count("l8")
    b+=a.count("l9")
    if b>=3:
        if a in combinations:
            pass
        else:
            combinations.append(a)

print (len(combinations))

But for some reason this is including repeated groups. Which means my last few lines of code are not working correctly.

If goes on true and false in the same time

I have an if statement.On true i have a die function with the message "its working" and on false a die function with message "no its not".

The problem is that, the function goes on true and it's printing the message "its working" but if i comment the die from true it will go on false and it will display "no its not".

Code:

if(substr($cart_item['id'],0,1) != "M") {
                $resp = $this->order_model->check_normal_product($cart_item['id']);
                if ($resp != null || !(empty($resp))) {
                    if (strcmp($resp['product_name'],$cart_item['name']) == 0 && $resp['price'] == ($cart_item['subtotal'] / $cart_item['qty'])) {
                        die('its working');
                    }else{
                        die('no its not');
                    }
                }
            }

Checking if user input equals a certain string always evaluates to false

I'm trying to implement a small game, and the user has the option to choose whether or not proceed. The Scanner should read the input and compares the choice to see whether or not do so.

public static void main(String[] args){
    System.out.println("This is agame where you fight 7 bosses one after another, using nothing but the weapons that you have on you.");
    System.out.println("Progress will not be saved, you must fight them all in one shot.");
    System.out.println("Don't worry, your health and damage will increase after each fight.");

    Scanner readChoice = new Scanner(System.in);
    System.out.println("Are you up for the challenge? Enter no to leave, anything else to play");
    String playerChoice = readChoice.next();

    if ("no".equals(playerChoice)){
        System.out.println("Oh, well, come back when you feel you are ready.");
        System.exit(0);
    }
    else{
        beginGame();
    }

    readChoice.close();
}

However, the method beginGame() is always called even when the string "no" is entered. I'm not sure why the if keeps evaluating to false. I'm following the advice from the link below, but it still doesn't solve anything for me.

Reading and checking strings from user input

Why complete Arraylist is not getting printed through second for loop?

My complete arrayList is not getting printed through second for loop.(print statement highlighted by comment:second loop print statement),whereas its getting printed through first for loop.

What I am trying to accomplish.:Print the objects of arraylist except characters.[print first object regardless of character or any other object].

problem I am facing:Arraylist object '2' is not getting printed on console through second for loop.

code:

import java.util.ArrayList;

public class Test1 {

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

    ArrayList al = new ArrayList<>();
    al.add('a');
    al.add('2');

    for(int i=0;i<al.size();i++){
        System.out.println("element enterd in for loop: "+al.get(i));
    }

    for(int i=0;i<al.size();i++){
        System.out.println("element enterd in for loop: "+al.get(i));     //second loop print statement

        if(al.get(i).toString().charAt(0)>=65 & al.get(i).toString().charAt(0)<=122){

            al.remove(i);
            continue;

                }
        }
    }

}

Help:please help me in figuring out where the issue.

If else return issue in the loop in python

I need to make expression as:

def foo():    
number = 0
for x in request:
   if x is y:
       number += 1

    return "x is not y"

return number

but even if x is y it gives "x is not y". If I use else like:

def foo():
number = 0
for x in request:
   if x is y:
       number += 1

   else:
        return "x is not y"

return number

But else return is against syntax rools. How to correct code?

if elseif statement with three condition where second condition is between two number Laravel

I want to filter results based on three conditions in Laravel view blade. I wrote this code but is not giving me the right results because I second condition has to be between two numbers. My code:

@foreach($post_array[$key] as $array)
    @if($array['diff'] <= 168)
        <td><td>
    @elseif($array['diff'] > (168) && (720))
        <td><td>
    @elseif($array['diff'] > 720)
        <td><td>
    @endif
@endforeach

samedi 26 mai 2018

How to find if one of the items in a JSON data is equal to one of the values in an array?

I have found and tried out .includes to help with this problem. But .includes did not work as I intended. It actually did find one item in the JSON that matched the value in the other array, but it only matched similar values:

result_postid array:

[10,22,12,36,45,206]

item.id from JSON data:

[{"id":"5","username":"Mike"},{"id":"13","username":"Tom"},{"id":"28","username":"Jake"},{"id":"136","username":"Josie"},{"id":"400","username":"Bill"},{"id":"538","username":"Sam"}]

I tried to figure out why some of the values kept returning true when they should be clearly false. Then I came to the conclusion that .includes was actually taking 36 from result_postid and matching it with 136 in item.id. This is how I setup the if statement with .includes:

{result_postid.includes(item.id) ?
 <Text>True</Text>
 :
 <Text>False</Text>
}

This is the result:

result_postid | item.id | Result

10 != 5,13,28,136,400,538: False
22 != 5,13,28,136,400,538: False
12 != 5,13,28,136,400,538: False
36 =  5,13,28,136,400,538: True <--- this should be false
45 != 5,13,28,136,400,538: False
206 != 5,13,28,136,400,538: False

Then I tried this attempt with Lodash:

{_.intersection(item.id, result_postid) ?
<Text>True</Text>
 :
 <Text>False</Text>
}

And the results all came true, which is not correct:

10 = 5,13,28,136,400,538: True
22 = 5,13,28,136,400,538: True
12 = 5,13,28,136,400,538: True
36 = 5,13,28,136,400,538: True 
45 = 5,13,28,136,400,538: True
206 = 5,13,28,136,400,538: True

Is it possible to even compare values in an array to JSON data and show whether one value equal each other, if so true? If not, false?

Showing content only after user is logged in php

I've been doing web page with login/registration form. Everything works perfectly, except action, that will show content 2 (in that circle should be "You are logged in") only if user is logged in. Any suggestion what i have wrong in my code? 1 Thank you :)

3

C++ Do/While Loops and If/Else: Dice game -- Error on Line 75: Expected "While" before "Cout" -- How to fix this?

Beginner coder -- first C++ class.

I keep getting errors at line 75 onward, and I cannot figure out where I went wrong. I know my code is pretty sticky...I need help on cleaning it up. Anyone know how I can code this correctly?

This is the assignment:

Dice (if/else, loop, random):

Using if/else, loops, and random numbers, write a Dice Game program where the user rolls 2 dice and decides whether they want to "hold" those numbers or roll again. It should let the user roll as many times as they like until they hold.

The computer then should roll 2 dice as well. The object of the game is to get a higher score than the computer.

===

Hint: use random numbers b/w 1-6, make 4 random numbers

When I tried to build the program, I get a bunch of errors and don't really know what I am doing wrong (tried to debug myself). Here are the errors:

||=== Build file: "no target" in "no project" (compiler: unknown) ===|
||In function 'int main()':|
|75|error: expected 'while' before 'cout'|
|75|error: expected '(' before 'cout'|
|75|error: expected ')' before ';' token|
|87|error: expected 'while' before 'While'|
|87|error: expected '(' before 'While'|
|87|error: 'While' was not declared in this scope|
|87|error: expected ')' before ';' token|
||=== Build failed: 7 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Here is the code I have so far--can anyone show me the correct code?:

#include <iostream>
#include <cstdio>
#include <time.h>
#include <stdlib.h>
using namespace std;

int main()
{

srand(time(0));

int Roll1 = 1+(rand()%6);
int Roll2 = 1+(rand()%6);
int UserRoll = Roll1 + Roll2;
int Roll3 = 1+(rand()%6);
int Roll4 = 1+(rand()%6);
int ComputerRoll = Roll3 + Roll4;
string Hold;
string ThrowDice;
string Again;

do
{

do
    {
    cout << "Please enter \"throw\" (lowercase) to roll the dice: ";
    cin >> ThrowDice;
    } while(ThrowDice != "throw");

do
    {
    cout << "You rolled: " << Roll1 << " and " << Roll2 << endl;
    cout << "Would you like to hold onto these numbers or roll again? " << endl;
    cout << "Enter (lowercase) \"hold\" to keep this roll, or \"throw\" to roll again): ";
    cin >> Hold;
        if (Hold != "hold" && Hold != "throw")
        {
            cout << "Your choice isn't valid!  Please try again by typing \"hold\" or \"throw\": " << endl;
        }
    }while (Hold != "hold" && Hold != "throw");

do
    {
        if (Hold == "hold")
        {
        cout << "You chose to keep these numbers, totaling: " << UserRoll << endl;
        cout << "The computer rolled " << Roll3 << " and " << Roll4 << " totaling: " << ComputerRoll << endl;
        } break;

        if (Hold == "throw")
        {
        cout << "You chose to roll again. " << endl;
        }
    }while (Hold == "throw");

do
    {
        if (UserRoll < ComputerRoll)
        {
        cout << "Sorry. You lose. " << endl;
        } break;

        if (ComputerRoll < UserRoll)
        {
        cout << "Congratulations! You win! " << endl;
        } break;

        if (ComputerRoll == UserRoll)
        {
        cout << "It's a draw. " << endl;
        } break;
    }

cout << "Would you like to play again? [Yes/No]: " << endl;
cin >> Again;

if (Again == "Yes")
    {
        continue;
    }

else if (Again == "No")
    {
        break;
    }
}While (Again == "Yes");

return 0;

}

Check if date is there then update 0 otherwise update amount in R?

First of all sorry for incorrect formatting , actually this is my first question,

I have a following dataset

In this new_effective_ upto is date in posixct format

And amount is in integer

I want to do

if new_effective_upto is NA then update new_amount to amount

if new_effective_upto contains any date then updated new_amount to 0

actually i m not able to compare date in ifelse statment??

What i have done

First i apply substr to extract some part of date & then convert it to integer & then apply ifelse

substr(chart_fixed_rent_recovery_1$new_effective_upto,1,4)

as.integer(chart_fixed_rent_recovery_1$sub_upto)

ifelse(chart_fixed_rent_recovery_1$sub_upto == 'NULL',chart_fixed_rent_recovery_1$AMOUNT,0)

but this does not update amount in any field it only update 0 ??

Dataframe name chart_fixed_rent_recovery_1

how to use elif with pandas dataframe

I have a sales dataframe which looks like below

    Company         Sales
    MC                360.0
    MC                340.0
    MC                338.5
    MC                335.5
    MC                235.0
    MC                235.0
    MC                234.0
    MC                127.0
    MC                121.0
    MC                120.5

I want to create a new column based on the values of Sales column And my output table should be like

    CompanyCode     ActivityDate    Category
    MC                360.0         Fast Mover
    MC                340.0         Fast Mover
    MC                338.5         Fast Mover
    MC                335.5         Fast Mover
    MC                235.0         Medium Fast Mover
    MC                235.0         Medium Fast Mover
    MC                234.0         Medium Fast Mover
    MC                127.0         Slow Mover
    MC                121.0         Slow Mover
    MC                120.5         Slow Mover

I tried elif statement

if df['Sales']>=300:
   df['Category'] = 'Fast Movers'
elif (df['Sales']>=200) & (df['Sales'] < 300) :
   df['Category'] = 'Medium Fast Movers'
else:
   df['Category'] = 'Slow Movers'

Not sure if my approach is correct. I will appreciate your kind help and effort.

Can we put 2 conditions in a single if statement?

I wanna ask if we can put 2 or more conditions in single 'if' For example:

If a == 1 b == 2: print 'can we do this? If yes, how? '

unreachable code when trying to stop executing method if condition true

Good day!

Im currently trying to stop my method if one of the digits = 0. For some reason it says "unreachable code" at the point below:

    static void method(int y) {


    int dig1 = y % 10;
    int dig2 = y / 10 % 10;  //digits of y
    int dig3 = y /100 % 10;

    if (num1 == 0);{         //if dig1 = 0, stop the method
       return; 
    }
     if (num2 == 0);{      // unreachable code, but why?
        return;
     }
      .... and so on

How come it says unreachable code even if the condition is not true? y = numbers from 122 - 133 and the only number who is supposed to stop the method is 130 because of the 0. Could someone be this kind and explain it to me please? Thanks!

Else if not working on android studio

If statement is always working. So else if statement never works. operators stack is always empty. So i can not calculate result.

  public static Double evaluate(String exp) {
    char[] tokens = exp.toCharArray();
    Stack<Double> operands = new Stack<>();
    Stack<Character> operators = new Stack<>();

    for (int i = 0; i < tokens.length; i++) {
        if (isOperand(tokens[i])) {
            StringBuffer sb = new StringBuffer();
           while (i < tokens.length && isOperand(tokens[i])) {
                sb.append(tokens[i++]);
                operands.push(Double.parseDouble(sb.toString()));
            }
        } 
        else if (isOperator(tokens[i])) {
            while (!operators.empty() && hasHigherPrec(tokens[i], operators.peek())){
                operands.push(performOperation(operators.pop(), operands.pop(), operands.pop()));
            }
            operators.push(tokens[i]); 
        }

    }
    while (!operators.empty()){
        operands.push(performOperation(operators.pop(), operands.pop(), operands.pop()));
    }

    return operands.pop();
}

Blank cell in excel with iF FUNCTION

I'm trying to make a world cup 2018 excel sheet prediction for me and my friends. I have succeeded to make all the functions for example - I have one table that presents the real scores which are connected with a function to the other members prediction table. the only problem that I have now that if someone predicts a tie (1-1) and the game didn't happen yet so that means the cells are empty - then it gives him a 1 point for guessing true... like 1-1 equals to blank - blank.

This is my function so far -

//

=VALUE(IF(AND(E9="",J9=""),"0",IF(AND(E9>F9,J9>K9),"1",IF(AND(F9>E9,K9>J9),"1",IF(AND(E9=F9,J9=K9),"1","")))))

//

the prediction is only for tie/win/lose it's not related to specific score.

how can I prevent blank cells from being equal to tie?

Can a multi-condition if-statement include an exception along with boolean/relational conditions?

I have a piece of code that fits each voxel in a data cube with a Gaussian plus a non-zero, sloping linear baseline. Each voxel is a spectrum of line+continuum emission that, depending on the location, can be pretty noisy and is known not to behave well at the edges of either the image or the spectral range. Therefore, sometimes it's necessary to fit the Gaussian and linear components separately in the parts of the spectra where each is most likely to occur, either because the original fit failed, or because the fitting parameters were nonsensical and I can see the line it failed to fit despite the noise. I'd skip straight to the piecewise version if I could, but the discontinuities can be problematic, not to mention it's generally a more costly procedure in terms of time and memory usage.

So my situation is this: I want to have my program respond to multiple possible conditions, where some are exceptions (ValueError and RuntimeError) and the others are Boolean or relational conditions, with the same procedure. Can that be done? Right now I have two copies of the same procedure, one in the exception block and the other in the else block with an internal if-statement, and it's annoying the heck out of me. If I can't combine them, is there a way to reroute one or the other statement to the same block of code without defining a new function?

vendredi 25 mai 2018

Show number depending on date

I need help to understand what way to use to make function work depending on current day.

$dateOne = 2018-01-24

$dateTwo = 2018-07-24

$full_amount= 10000

$amountOne = 2500

$amountTwo = 416

$frequency = 2(months)

What I have now:

if (date("Y-m-d") >= $dateTwo) { 
        return $amountOne + $amountTwo;
    } elseif (date("Y-m-d") >= $dateTwo) { 
        return $amountOne;
    } else {
        return 0;
    }

When current date >= $dateTwo I need to return $amountOne + $amountTwo but every 2 months ($frequency) after $dateTwo it need to count plus one more $amountTwo and if it like 4 months ($frequency x 2) plus $amountTwo 2 times.

In actual my users have some amount that they receive during some exact period partially. (you will have 10000 at all, but we will give it to you like $amountTwo parts every $frequency months until you get full amount (10000) )

if current date >= $dateOne + $frequency he will receive $amountOne + $amountTwo + $amountTwo. And it should work on what exact day today.

Hope I explained well, bc it can look a bit complicated to understand.

If else statement doesn't work [duplicate]

This question already has an answer here:

I have a problem with the if else statement in my code. The code after if works, but after else it doesn't work. I don't get a error. The code after else just doesn't work.

Does somebody know what this problem can be solved ?

https://i.stack.imgur.com/i9RED.jpg

DRY (Don't Repeat Yourself) and if assignements

I think I'm forgetting something evident but I can't seem to find a way to assign a value if it validates a condition remaining as DRY as possible... Some code to explain what I mean ...

a = (b > 1) ? b : c;

or even a = (a > 1) ? a : b;

So of course here it's no big deal but if a was to be replaced by an method call, (maybe a yield return there) or whatever, I would then have to call it twice...

Only thing I see is stocking it in a variable which would then be as the code above...

Any better idea?

Unity C#: If-Statement hadn't been obeserved

in my Unity project I have a script attached to a couple of prefabs. Every few seconds a random prefab is spawned. This is a part of my attached script:

private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.transform.CompareTag("ground"))
        {
            if (transform.gameObject.name == "FallingKeule(Clone)") 
            {
                Destroy(transform.gameObject);
            }
            if (transform.gameObject.name == "FallingHeart(Clone)")
            {
                Destroy(transform.gameObject);
            }
            if (transform.gameObject.name == "FallingCup(Clone)")
            {
                Destroy(transform.gameObject);
            }
            else
            {
                print("You lost a life!");
                Player.GetComponent<Colliding>().LostLife();
                Destroy(transform.gameObject);
            }

        }
    }

If a GameObject is spawned by random and it hit's the ground, and it is a "FallingKeule(Clone)" --> "(Clone)" because the prefab is cloned by it's initalisation the Code from

if (transform.gameObject.name == "FallingKeule(Clone)") 

isn't be done! The else code is been done:

else
                {
                    print("You lost a life!");
                    Player.GetComponent<Colliding>().LostLife();
                    Destroy(transform.gameObject);
                }

I have no clue what I have done wrong but I'm really thanksfull for all answers.

Jul

Python - Elif not working, and it is just skipped

This is my code for a ANPR camera, which scans the license, plate and also check if they were speeding or not and writes all the information to a text document named output.txt. All of it works other than one part, see the bottom. Also no error code comes up for it

#Imports
import time
import random

#Gets the number plate
np=input()

#Sets the parts of the license plate
twoletters=np[0:2]
twonumbers=np[2:4]
threeletters=np[4:7]

#Sensors
sensor1=0
sensor2=random.uniform(0.25, 0.4)
sensor2=round(sensor2, 1)

#Variables
twoletterstf=False
twonumberstf=False
threeletterstf=False
valid=False
speed=0
ticketprice=0
ticket=False
distance=10

#Calculations to work out the speed
time.sleep(1)
distance=10
times=sensor2-sensor1
ans=1/times
speed=distance*ans



#If more than 7 letters and numbers
if len(np)>7 or len(np)<7:
    valid=False
    print("Invalid Nuber Plate")

#If less than 7 letters and numbers outputs number plate and speed

#If their is upper case letters and digits in correct order
elif twoletters.isupper() and twoletters.isalpha and twonumbers.isdigit() 
and threeletters.isupper() and threeletters.isalpha():
    valid=True
    twoletterstf=True
    twonumberstf=True
    threeletterstf=True


#If isn't upper case or their isn't 2 numbers or if their isnt't three letters, then outputs the number plate with speed
elif twoletterstf==False or twonumberstf==False or threeletterstf==False:
    print("Invalid Number Plate")
    valid=False

elif speed > 31:
    ticket=True
    ticketprice=100+speed

elif speed < 31:
    ticket=False
    ticketprice=0

else:
    exit



f=open("Output.txt", "a")
f.write("Number Plate:" + str(np) + "\n")
f.write("Valid:" + str(valid) + "\n")
f.write("Speed:" + str(speed) + "M/S" + "\n")
f.write("Ticket:" + str(ticket) + "\n")
f.write("Ticket Price: £" + str(ticketprice) + "\n")
f.write("\n")
f.close()

This is the problem, the elifs aren't actually working, and so it acts as if they weren't there. And when it writers the code in the text document it always comes up as false and never true if they are actually speeding So if anyone could help it would be a real help

elif speed > 31:
    ticket=True
    ticketprice=100+speed

elif speed < 31:
    ticket=False
    ticketprice=0