vendredi 31 mars 2017

String index out of range: -1 within a crowded 'if' statement

I'm running a program that parses the text off of a website and then spell checks a string containing all of the text after it's been cleaned from HTML mark up.

Once the spell checker reaches the end of the string, it returns this this exception. I saw similar questions which were resolved by setting the index greater than 0 in an "if" statement, but I've been struggling to fix this for some time now and would appreciate some help in figuring this out.

Exception thrown:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(Unknown Source)
    at ParseCleanCheck.checkWord(ParseCleanCheck.java:173)
    at ParseCleanCheck.SpellChecker(ParseCleanCheck.java:101)

Java line 173-175 is where the word is stripped of any punctuation marks:

if (length > 2 && word.substring(length - 2).equals(",\"") || word.substring(length - 2).equals(".\"")
                || word.substring(length - 2).equals("?\"") || word.substring(length - 2).equals("!\"")) {
            unpunctWord = word.substring(0, length - 2);

Line 101 is documented below, I've added the relevant surrounding code that might be part of the exception being thrown

String user_text = "";
user_text = cleanString;
while (!user_text.equalsIgnoreCase("q")) {
                // check if necessary or if cleanString still works
                // PageScanner();
                user_text = cleanString;
                String[] words = user_text.split(" ");

                int error = 0;

                for (String word : words) {
                    suggestWord = true; // ~~~ Line 101 ~~~~
                    String outputWord = checkWord(word);

                    if (suggestWord) {
                        System.out.println("Suggestions for " + word + " are:  " + suggest.correct(outputWord) + "\n");
                        error++;
                    }
                }

                if (error == 0 & !user_text.equalsIgnoreCase("q")) {
                    System.out.println("No mistakes found");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }

How can I check if there is a value for a key in local storage?

The user should only be able to store information if there is not a preexisting value stored to the key. How can i check if there is already a value, and alert the user that there is already a value? I know i have to use an if statement. If there is a value alert the user. Else set item...(save the object). But how do i check for the value?

function addEvent() {
var announcement = {
    title: document.getElementById('title').value,
    group: document.getElementById('group').value,
    author: document.getElementById('author').value,
    type: document.getElementById('type').value,
    date: document.getElementById('date').value,
    time: document.getElementById('time').value,
    gender: document.getElementById('gender').value,
    grade: document.getElementById('grade').value,
    message: document.getElementById('message').value
    };
var objS = JSON.stringify(announcement);

localStorage.setItem('announcement', objS);

alert('Announcement successfully stored!');

}

function showA() {
var getObj = localStorage.getItem('announcement');
var objP = JSON.parse(getObj);

document.getElementById('showAnnouncement').innerHTML = "Announcement"+"<br/>Title:"+objP.title+"<br/>Group:"+objP.group+"<br />Author:"+objP.author+"<br />Type:"+objP.type+"<br/>Date:"+objP.date+"<br />Time:"+objP.time+"<br/>Gender:"+objP.gender+"<br/>Grades:"+objP.grade+"<br />Message:"+objP.message;

}

if else complications in C

In my code I trying to build this weather calculator for class. I am having issues with these if else statements and I can't seem to figure out why any extra eyes please take a look. The if's are supposed to print out separate statements based on the average temp however, it always outputs the second statement.

#include <stdio.h>

int main(void){
    int high_temp[14];
    int warmdays = 0, colddays = 0, i = 0;
    float average = 0.0f, sum = 0.0f;


    printf("\nWeather Analyzer Application by Joey Peters");
    for(i = 0; i < 14; i++) {
        printf("\n\nPlease enter the temperature for day #%d ", i+1);
        scanf("%d", &high_temp[i]);

        sum += high_temp[i];

        if(high_temp[i] > 60){
            warmdays++;
        }

        if(high_temp[i] < 60){
            colddays++;
        }


    }

        average = sum / 14;
        printf("\nThe number of warm days: %d", warmdays);
        printf("\nThe nuber of cold days: %d", colddays);
        printf("\nThe average high temperature: %.2f", average);

        if(average = 100 || average >= 90 ){
            printf("These two weeks were blazing hot");
        }
    else    
        if(average >= 80 || average <= 89){
            printf("\nThese two weeks were quite hot");
        }
    else    

        if(average >= 70 || average <= 79){
            printf("\nThese two weeks hot for Michigan");
        }
    else    

        if(average >= 60 || average <= 69){
            printf("\nThese two weeks were decent for Michigan");
        }
    else    
        if(average >= 50 || average <= 59){
            printf("\nThese two weeks were somewhat cold");
        }
    else
        if(average < 50){
            printf("\nThese two weeks were basically cold");
        }   

    printf("\n\nThank you for using the weather analyzer!");
    return 0;

}       

can someone plz help me about this uml statement.

+setCourse(type:char,desc:String):void The type can either be ‘n’,’N’,’D’,’d’. Any other type is invalid. If the type is either ‘n’ or ‘N’ then parameter desc (which MUST have a length>0) will be assigned to the property courseNum. If the type is either ‘d’ or ‘D’ then the parameter desc (which must have length>0) is assigned to the courseDesc. If the type is not any of ‘d’, ‘D’,’n’,’N’, simply exit the method without making ANY changes at all.

Iterate through populated rows, Match based on criteria, add value to specific cell in another sheet in Excel using VBA

I am trying to select a value in column hours in tab Time and put it in the appropriate column in tab Month. I would like to iterate through every row in sheet Time and add all of the Data to tab Month.

For every line in Tab TIME add the Hours to the appropriate engagement in Tab Month based on Engagement Number, Engagement Phase, Staff Level. I do this manually every month. I create a copy of last months tab and add on to that each month. Most columns have cells with something like this in them: =1+3+6+4+14+5+2+5 which are the hours that have been worked on that engagement. For cells with something in them i would just like to add on to what is there. For cells with nothing in them i would like to make the new value: = 1 if the value was 1. I want to automate this as it takes up a few days every first of the month, This one just so happens to be on a weekend so guess what I'll be doing. :)

This is where I am at.

Sub Recon()

'Macro to add time to reconciliation report


'Declare variables

Dim Last_Row_TIME As Double
Dim Last_Row_MONTH As Double
Dim wb As Workbook
Dim ws As Worksheet
Dim rw As Range
Dim wstime As

Set wb = ActiveWorkbook
Set wstime = Sheets("TIME")
Set wsmonth = Sheets("MONTH")

wstime.Select

'Find the last non-blank cell in column A(1)
Last_Row_wstime = wstime.Cells(Rows.Count, 1).End(xlUp).Row

'Find the first blank cell in column A
First_Empty_Row_wstime = Last_Row_wstime + 1

I_Col = 1

For i = 1 To Last_Row_wstime

For Each rw In wstime.Rows

If wstime.Cells(rw.Row,1).Value = wsmonth.Cells(rw.Row, 3).Value
And

End Sub

I am stuck at the if statement and not sure how to make this work.

IF 
TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = PARTNER or MANAGING DIRECTOR

THEN

Add Value TIME.Hours (Column Y) to  Month.Partner/MD (Column I) 

'If blank then "=TIME.Hours) elseif add to the previous value "previous     addition statement +(hours)"


ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = SR. MANAGER/DIRECTOR

THEN 

Add Value TIME.Hours (Column Y) to  Month.Director (Column J)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = MANAGER

THEN

Add Value TIME.Hours (Column Y) to  Month.Manager (Column K)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = SENIOR ASSOCIATE

THEN

Add Value TIME.Hours (Column Y) to  Month.Sr.Assoc (Column L)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = ASSOCIATE

THEN

Add Value TIME.Hours (Column Y) to  Month.Associate (Column M)

ELSEIF

'Create a new line after the biggest primary key, located in Month.Primary Key (Column A) 

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Eng. Description (Column B) = Month.Project Name (Column D)


End If

R: split vector intro more vectors with constrains

Im working on a mealplan and I need some advice on how to split the Daily intake into several meals. I have a vector where each element represents # of grams of different foods that a person should eat in order to meet his/her Daily intake of protein, carbs, fat, fiber..etc.

The vector looks as such:

intake <-  Salmon                 Chicken                   Pesto                  Butter 
         162.573720               96.262731               48.415283                4.560707 
            Yoghurt                Couscous              Boiled Egg                   Apple 
         190.233090              518.741711              198.049714                0.000000 
            Avocado                Broccoli              Grapefruit Quark / Kesella Natural 
           0.000000              350.000000                0.000000              217.450103 
            Oatmeal 
          67.820707 

This has lenght 13. I also have a matrix X with all the nutritional facts about each food type, it looks like this:

        Salmon Chicken   Pesto Butter Yoghurt Couscous Boiled Egg  Apple Avocado Broccoli Grapefruit
protein   0.18   0.231 0.12740  0.004  0.0342   0.0379     0.1225 0.0000  0.0194   0.0350      0.007
fat       0.12   0.010 0.53850  0.820  0.0300   0.0016     0.0973 0.0005  0.1960   0.0027      0.001
carbs     0.00   0.000 0.04080  0.005  0.0484   0.2182     0.0040 0.1058  0.0170   0.0312      0.070
fibre     0.00   0.000 0.00218  0.000  0.0000   0.0140     0.0000 0.0232  0.0475   0.0310      0.019
Greens    0.00   0.000 0.00000  0.000  0.0000   0.0000     0.0000 0.0000  1.0000   1.0000      0.000
        Quark / Kesella Natural Oatmeal
protein                   0.127   0.133
fat                       0.001   0.070
carbs                     0.036   0.576
fibre                     0.000   0.100
Greens                    0.000   0.000

Lastly, I have (0/1)- vectors that indicate if the food source is considered a "breakfast" or not. The same goes for "lunch", "dinner" and "snack".

I want to split the vector "intake" into meals that one eats throughout the day. My first idea was to simply take the dot product of intake*breakfast to get all the Foods that are considered breakfast and just eat them. This method does not give very reasonable answers since It may give way to much food to eat for breakfast and almost nothing left for the rest of the meals.

So lets say someone eats 5 meals a day;

I want to split the intake vector into 5 separate vectors, with the Foods that are considered breakfast to go in the new breakfast-vector. Also, I want to be able to adjust how much of every food that goes in each vector: such as

Default (Breakfast 50% Protein or lower, 10% Fat or higher, 40% Carbohydrates or lower, Evening Snack 70% Protein or lower, 25% Fat or higher, 5% Carbohydrates or lower).

So that I can adjust so that one eats a lot of protein for breakfast and a lot of carbs Before they work out.

Any help is grealy appreciated :)

Conditional IFs in powershell to populate a column in csv

let's say I have a csv with:

 A,B,C,D
1,2,a,
1,2,b,
1,2,a,
1,2,c,

I want to populate the last column D with conditional values based on the values in the column C.

in excel that would be like (if C2 = a,value1,if(C2=b,value2, if C2=c,value 3...etc.

How can I achieve something as simple as this in PS??

Count IF with mutiple OR statements

If any cell in column H has a "yes" and column I has Performance, Fitblitz or Barbell, then count all the cells with "Yes" in column H.

python executing both if and else statement together

I am not sure why, but python is executing the if statement then the else statement in the same iteration

i'm cutting out unimportant code:

from livewires import games
...
...
def update(self):
  if games.keyboard.is_pressed(games.K_s):
    if self.y == games.screen.height/3:
      self.y = games.screen.height/2
    else:
      self.y = games.screen.height

In my mind it should go: if 's' is pressed: then, if the height is equal to whatever do whatever otherwise, do whatever2

But the computer is going: if 's' is pressed then, make the height equal to whatever and since the height is no longer equal to whatever, make it equal to whatever2

I have tried this by using single if statements with 'and' operators and all kinds of funky ways of doing it, but everything I do, the code just seems to move to the next line regardless of if/elif/else

I even tried implementing a sort of timer that kind of works, but is unreliable.

Python SyntaxError (else statement)

When I ran the script below it displays
SyntaxError: invalid syntax

single = True    

if single = True:
 print "Hey Girl, can I get your number ? "
else
 print "Bye. !"

errors with Elif expected indented block

I'm trying to create a menu for my application, the menu has 4 options and each of these options should return with the correct information when the user has entered the chosen value. i keep getting an error with the Elif statements. I am a newbie so please understand where am coming from. much appreciation.

when i indent the while ans: i will receive an error says invalid syntax after indenting the elif ans==2.

elif ans==2 <--- this error keeps saying indention block error or syntex invalid when i indent it.

def print_menu(self,car):
print ("1.Search by platenumber") print ("2.Search by price ") print ("3.Delete 3") print ("4.Exit 4")

loop=True
while loop: print_menu() ans==input("Please choose from the list")

    if ans==1:
        print("These are the cars within this platenumber")
    return platenumber_

    while ans:  
        if ans==2:
        elif ans==2:
            print("These are the prices of the cars")
    return price_   

    elif ans==3:
        print("Delete the cars ")
    return delete_ 

    elif  ans==4:
    return Exit_  

            loop=False

    else:
        raw_input("please choose a correct option")

Write a function in R containing an if/else statement and rowSums(), defining how to handle NAs

I've been searching for answers and trying all I can think of, but nothing works:

I want to write a function to add the values across rows in a dataframe. It's easiest to write a function since I have so many columns and don't always have to add the same ones. Here an example of a dataframe:

ExampleData <- data.frame(Participant = 1:7,
                   Var1 = c(2, NA, 13, 15, 0, 2, NA),
                   Var2 = c(NA, NA, 1, 0, NA, 4, 2),
                   Var3 = c(6, NA, 1, 0, 1, 5, 3),
                   Var4 = c(12, NA, NA, 4, 10, 1, 4),
                   Var5 = c(10, NA, 3, 5, NA, 4, 4))

The conditions: If all values across a row are NA, the sum should be NA. If there is at least one value across a row that is a number (>= 0, or not NA), then rowSums should ignore NA's and add the values.

The best solution I've reached so far is:

addition <- function(x) {
  if(all(is.na(x))){
       NA
  }else{
       rowSums(x, na.rm = TRUE)
  }
}
addition(ExampleData[, c("Var1", "Var2", "Var3")])

The output is: [1] 8 0 15 15 1 11 5

But it should be: [1] 8 NA 15 15 1 11 5

Does anyone know how to do this? Thank you.

Try/Catch Nested If/Else Statement in PowerShell

I am trying to write a try/catch statement for my PowerShell script nested in an if/else statement. I am not getting any errors however, I think there's something wrong with my syntax. Right now, my main function of the script looks like this:

$userName = Read-Host -Prompt "Input the user's Id"

$getUser = get_user

if ($userName -eq $getUser) 
    {
        try
        {
        $courseId = Read-Host -Prompt "Input the course's ID"
        $availability = Read-Host -Prompt "Available? (Yes/No)"
        $courseRoleId = Read-Host -Prompt "Course Role? (Student/Instructor)"

        $confirmationEnrollment = putStudentCourse
        " "
        "####################################################"
        "Success!"
        "####################################################"
        }
        catch
        {
            [WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand]
            "####################################################"
            "User not found. We'll create it now!"
            "####################################################"
            " "
        }
    }
    else
    {
        $firstName = Read-Host -Prompt "First Name"
        $lastName = Read-Host -Prompt "Last Name"
        $netId = $userName
        $email = $userName + "@school.edu"
        $password = Read-Host -Prompt "Password"
        $isAvailable = Read-Host -Prompt "Available? (Yes/No)"

        $confirmationUserCreate = user_create
        " "
        "####################################################"
        "User created!"
        "####################################################"
        " "
        $courseId = Read-Host -Prompt "Input the course's ID"

        $confirmEnroll = putStudentCourse
        " "
        "####################################################"
        "User enrolled!"
        "####################################################"
    }

If the user isn't found it throws this error:

Invoke-RestMethod : The remote server returned an error: (404) Not Found.
At E:\PowerShell\Post_Student_Course.ps1:37 char:13
+     $getUser = Invoke-RestMethod -Method Get -Uri $url2 -ContentType $contentType2  ...
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

What I am trying to do is output this:

"####################################################"
"User not found. We'll create it now!"
"####################################################"
" "

Instead of the red error. Any ideas how can I fix this?

Best regards,

Recoding floats in a list

I have a list of floats, which looks like this:

ratings_dec = [13.0, 8.6, 4.9, -1.5, 6.2, 7.7, 2.0, 10.0, 7.7, 12.7]

I want to clean this data, by giving number higher than 10.0 a 10.0 and numbers lower than 0.0 (so all negative numbers) a 10.0. I'm doing this with the following if statement:

predictions_clean = []
for pred in predictions_dec:
    if pred >= 10:
        predictions_clean.append(10.0)
    if pred <= 0:
        predictions_clean.append(0.0)
    else:
        predictions_clean.append(pred)

This code seems to work, but the funny thing is that:

len(predictions_dec) 
1222
len(predictions_clean)
1816

My understanding of if statements is not that great. Where in the if statement am I doing something wrong?

Remove an If Statement after it has been fired once

Is there anyway of removing an if statement after it has been fired once?

I have a menu container that shows on page load and want it so when the user scrolls 1px it slides away. I don't though want a the browser constantly tracking a scrollTop() method because of the performance hit from this.

What's the best way to remove or cancel an if statement after it has been used once?

The code is below and I have a codepen here: http://ift.tt/2oiOFQ7

jQuery(document).ready(function($) {
  $(window).scroll(function() {
    if ($(document).scrollTop() > 1) {
      $('.menubox').css('left', '-25%');
    }
  });

  $('.mybutton').on('click', function() {
    $('.menubox').css('left', '0%');
  });
});
body {
  margin: 0;
  padding: 0;
  height: 200vh;
}

.menubox {
  top: 100;
  position: fixed;
  width: 20%;
  height: 100%;
  background: red;
  padding: 10px;
  color: white;
  transition: all 1s;
}

.mybutton {
  position: fixed;
  left: 40%;
  top: 50px;
  padding: 5px 10px;
}
<script src="http://ift.tt/1oMJErh"></script>
<div class="menubox">Menu Box</div>
<button class="mybutton">menu</button>

SQL Case Statement - how to do it

I have the below statement which works nicely in Tableau.

However, I'd like to turn this into SQL and save all the results into a temporary column name.

Does anyone know how I might do this?

Essentially, the below removes the .com/.net etc... from the domain name.

I then have another script that removes the subdomain (everything from the first . to the left of the resulting value).

If anyone can help me with these, that would be incredible as I'm not sure how to do this in SQL

IF CONTAINS([domain], ".co.uk") then LEFT([domain],LEN([domain])-6)
elseif  CONTAINS([domain], ".com") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".net") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".org") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".biz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".edu") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".ac") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".gov") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".biz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".co") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ca") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".io") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".in") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".it") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".uk") then LEFT([domain],LEN([domain])- 3)
elseif  CONTAINS([domain], ".ru") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ie") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".tv") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".info") then LEFT([domain],LEN([domain])-5)
elseif  CONTAINS([domain], ".fr") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".es") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".pl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".is") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".hu") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".xxx") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".nl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ro") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".xyz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".no") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".eu") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".me") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".cz") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".fi") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".nl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".al") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".am") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".af") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".st") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".cn") then LEFT([domain],LEN([domain])-3)
else [domain]
end

If-else without else causes recursive function to repeat

Why does the following produce the output "ayyayy" and not just "ayy" (once)?

def iftest(b: Boolean): Unit = {
  if(b) iftest(false)
  print("ayy")
}

I run it in REPL as iftest(true) which should cause it to fail on the first pass but succeed on the second (hence only one "ayy"). So why does it act like both succeed?

Is there some sort of recursive "backfolding" in scala that I don't know about?

IF END IF IN SQL STORED PROCEDURE

I am trying to create a advanced search query in which user's name,status and role are filtered at the same time (one or more can be selected). Given below is the code for the SQL Stored Procedure I want a way to have IF and END IF, so that the where condition in all the cases are mutually exclusive Currently if the first name is null, then the rest of the conditions fail

USE [qcsl]
GO
/***** Object:  StoredProcedure [dbo].[UserAdvancedSearch]    Script Date: 3/31/2017 3:25:28 PM *****/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:        Mayank
-- Create date: 2017-03-29
-- Description:   
-- =============================================
ALTER PROCEDURE [dbo].[UserAdvancedSearch]
    -- Add the parameters for the stored procedure here
    (
    @user_name varchar(50) = NULL,
 @user_last_name varchar(50) = NULL,
    @role_id varchar(50) = NULL,
    @user_status varchar(50) = NULL,
 @query varchar(2000) = NULL output
 
   

    )
    AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here

SET @query = 'select * from user_main
where 
'IF (@user_name is not null ) SET @query = @query + '
(user_first_name like '''+@user_name+''' OR user_first_name IS NULL)
'IF (@user_last_name is not null ) SET @query = @query + 'AND
(user_last_name like '''+@user_last_name+''' OR user_last_name IS NULL)
'IF (@user_status is not null ) SET @query = @query + 'AND
(user_status = '+@user_status+') 'IF (@role_id is not null) SET @query = @query + '
AND
(user_role_id_ref = '+@role_id+')'
EXEC(@query);
END

Warning : Divison by zero on woocommerce in wc-template function

function wc_get_loop_class() { global $woocommerce_loop;

$woocommerce_loop['loop']    = ! empty( $woocommerce_loop['loop'] ) ? $woocommerce_loop['loop'] + 1   : 1;
$woocommerce_loop['columns'] = ! empty( $woocommerce_loop['columns'] ) ? $woocommerce_loop['columns'] : apply_filters( 'loop_shop_columns', 4 );
if ( 0 === ( $woocommerce_loop['loop'] - 1 ) % $woocommerce_loop['columns'] || 1 === $woocommerce_loop['columns'] ) {
    return 'first';
} elseif ( 0 === $woocommerce_loop['loop'] % $woocommerce_loop['columns'] ) {
    return 'last';
} else {
    return '';
}

}

Warning: Division by zero in /home/betawebs/public_html/tech/betawp/attwp/wp-content/plugins/woocommerce/includes/wc-template-functions.php on line 249 class="post-2606 My page is giving this error pls help

See if a function has finished using a if-statement

So when the function dissmissAlert has completed (the first alertDialog disappears). I want the following alertDialog to show directly afterwards, which is created in the func saveLogin.

typealias FinishedAlert = () -> Bool


var firstPasswordSaveAlert: UIAlertController!



    @IBAction func saveLogin(_ sender: Any) {


    if loginPasswordTf.text != "" {
         showAlert()
    }
    if FinishedAlert == true {


        UserDefaults.standard.set(loginPasswordTf.text, forKey: "loginpassword")

        let alert = UIAlertController(title: "You need it to access this app", message: "Here it is: " + String(describing: UserDefaults.standard.object(forKey: "loginpassword")!), preferredStyle: UIAlertControllerStyle.alert)

        alert.addAction(UIAlertAction(title: "Got it!", style: UIAlertActionStyle.destructive, handler: nil))
        self.present(alert, animated: true, completion: nil)

    }

}        


func showAlert() {
    if loginPasswordTf.text != "" {
        self.firstPasswordSaveAlert = UIAlertController(title: "IMPORTANT", message: "It's very important that you remember your password", preferredStyle: UIAlertControllerStyle.alert)
        self.present(self.firstPasswordSaveAlert, animated: true, completion: nil)
        Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(ViewController.dismissAlert), userInfo: nil, repeats: false)
    }
}

func dismissAlert(completed: FinishedAlert) {
    // Dismiss the alert from here
    self.firstPasswordSaveAlert.dismiss(animated: true, completion: nil)


    completed()
}

How do I check if dismissAlert() completed it's tasks?

Thanks!

if statement not working in shell script

Below is my script and the val1 value is 3 and Val2 value is 0 , but defaultly the condition checks the if statement. not going to else condition. can anyone help where i missed or done wrong here?

op1=$(top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g')
op2=$(top -bn1 | grep "load average" | awk '{print$12}' |sed -e 's/,//g')
val2=${op2%.*}
val1=${op1%.*}
echo $val1
echo $val2

if [ val1 > 50 ] || [ val2 > 50 ] ; then

  echo -e "CPU Percentage on $HOSTNAME is  $op1  and Current  Load is  $op2  Which are higher than 50% usage. Kindly Login to $HOSTNAME and examine  the process. If apache process consume the more space kindly excute the below instructed command to restart all the SWLB's. \n\n Host Name    : $HOSTNAME   \n User ID          : inauat \n Path              :/inautilus/xjp/ers/servers \n Script Name : apache_all.sh  \n\n Note: If the SWLB restart dosen't resolve the problem reach Unix support  to investigate further. "| mutt -s " $HOSTNAME CPU Status Alert  " "satheesh.charles@bnymellon.com" -c "SCharles@inautix.co.in"

else
    echo  'CPU load appears normal '
fi

jeudi 30 mars 2017

ifelse in R to determine 2 conditions; one simple the other composite

Background:

I have two elements in an R function (see my R code below), type and width. The type element simply can be 1 or 2. But width can take any number.

Question:

Suppose there there two specific numbers that act as criteria for width. First number is 1. Second number is sqrt(2) / 2.

How can I say:

IF "type" is 1 AND "width" is NOT 1 AND ALSO (i.e., still type is 1) "width" is NOT sqrt(2) / 2, THEN "do ..."?

Can I use:

ifelse(type == 1 & width != 1 & width != sqrt(2)/2, do ..." ?

if statement within double for loop: specific example [duplicate]

This question already has an answer here:

I'm writing a short code which compares two dataframes- list & knownlocation. I want to know for each item in list, whether it falls within a knownlocation.

colnames(list) <- c("gene_symbol", "chromo", "start", "end")
colnames(knownlocation) <- c("snp", "chr", "s", "e")

To find this I wrote the code to make a new column in "list" saying TRUE or FALSE whether it's in any of knownlocation:

for (i in 1:nrow(list)) {
for (j in 1:nrow(knownlocation)) {
if ( (list[i, 2] == knownlocation[j, 2]) && (list[i, 3] >= knownlocation[j, 3]) && (list[i, 4] <= knownlocation[j, 4]) ) {
list[i, 5] = "TRUE" }
else { list[i, 5] = "FALSE"}
}}

This code looks fine to me and it runs with no errors. Problem is the entire list shows FALSE, even if it does fall within a location in knownlocation. Can anyone find something obviously wrong that I'm missing?

How does one use Cyrillic (or other) characters in a statement where mb_strpos doesn't apply?

Basically, if($host == 'site.com/music/') works but if($host == 'site.com/музыка/') does not (there is no PHP error, but it moves on to the "else" section).

Substituting unicode escape sequences doesn't work; PHP simply ignores the Cyrillic part (as if to simply say if($host == 'site.com//'). mb_strpos isn't an option as I need an exact match in this instance.

how can I select only all done Task in MYSQL?

I am doing a simple task in MYSQL . As Example , There is Jib(jobId) and subjid(subJobId) and UL. SubJobId is a Id refereed to JOBID and each SubJID has a ul field , I Only need those JID(JobId) whose UL is 1, if there is even 1 UL is 0. then it'll ignore.

please check the image enter image description here

Assigning values to vectors of vectors WITH DOUBLE FOR LOOPs

I want to create a loop that will add the PASSENGER's name to a SCHEDULE if the PASSENGER's destination is the same as the VEHICLE's and the timing difference between the PASSENGER and VEHICLE must be <= 30mins.

*Every VEHICLE has its own SCHEDULE.

#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

#include "Vehicle.h"
#include "Passenger.h"
#include "Scheduler.h"

int main()
{
    //Passenger Creation
    Passenger pass1("US123", "Donald Trump", "A", 23, 00);
    Passenger pass2("S432", "Jon Doe", "B", 20, 35);
    Passenger pass3("W069", "General Aladeen", "A", 22, 46);
    Passenger pass4("UK13", "Mr Bean", "C", 8, 01);

    vector<Passenger> listOfPassengers;             //Vector of PASSENGERS
    listOfPassengers.push_back(pass1);
    listOfPassengers.push_back(pass2);
    listOfPassengers.push_back(pass3);
    listOfPassengers.push_back(pass4);

    //Vehicle Creation
    Vehicle veh1("Audi", 4, "A", 22, 45);
    Vehicle veh2("Subaru", 4, "B", 20, 35);
    Vehicle veh3("Mini-cooper", 4, "C", 20, 35);

    vector<Vehicle> listOfVehicles;                 //Vector of VEHICLES
    listOfVehicles.push_back(veh1);
    listOfVehicles.push_back(veh2);
    listOfVehicles.push_back(veh3);

    //Scheduler VECTOR aka C++ dynamic array

    vector<vector<string> > schedule;                               //schedule vector OF vector

    int vehVectorNum = listOfVehicles.size();           // How many vehicles
    int pasVectorNum = listOfPassengers.size();         // How many passengers
    int count;
    int result;

    cout << "How many vehicles: " << vehVectorNum << endl;

    for (int i = 0; i < vehVectorNum; i++)
    {

        vector<string> temp;                    // [i + 1] vehicle's vector
        count = listOfVehicles[i].getVSize();

        for (int j = 0; j < pasVectorNum; j++)
        {
            if (count > 0)
            {
                if (listOfVehicles[i].getVDestination() == listOfPassengers[j].getpDestination())
                {
                    result = listOfPassengers[j].getpTimeDuration() - listOfVehicles[i].getvTimeDuration();
                    if ((result <= 30) && (result >= 0))
                    {
                        temp.push_back(listOfPassengers[j].getpName());     // assigns PASSENGER to VEHICLE
                        schedule.push_back(temp);       // assigns VEHICLE to SCHEDULE     

                        count--;
                    }
                }
                else
                {
                    continue;
                }
            }


        }
        cout << "Remaining Capacity for Vehicle" << i + 1 << ": " << count << endl;         //remaining count after each vehicle
        listOfVehicles[i].setcurrentVCap(count);        // assign count to current vehicle capacity
    }

    for (int i = 0; i < listOfVehicles.size(); i++)         //check which vehicle is not full
    {
        if (listOfVehicles[i].getcurrentVCap() != listOfVehicles[i].getVSize())
        {
            cout << listOfVehicles[i].getVName() << endl;
        }
    }
    cout << endl;


    unsigned int i;
    for (i = 0; i < schedule.size(); i++)                           // check what is in SCHEDULE
    {
        cout << "Schedule #" << i << endl;

        unsigned int j;
        for (j = 0; j < schedule[i].size(); j++)
        {
            cout << schedule[i][j] << endl;
        }
        cout << endl;
    }

    return 0;
}

However, there is a logic error as the passengers were assigned wrongly: Output

Based on my conditions, only 3 PASSENGERS should be assigned to 2 schedules - Trump and Aladeen to Schedule #0 (which belongs to Vehicle A) and Jon Doe to Schedule #1 (which belongs to Vehicle B):

Schedule #0
Donald Trump
General Aladeen

Schedule #1
Jon Doe

May I know if I am missing out something? Thx in advance!

Conditionally set a object property

Its possible to remove the .where clause if queryString is null?

I have tried ternary operator in the middle of expression, but doesn't work.

Also the equals expression dont allow: null, undefined or empty String.

CashierHistory
            .scan()
            .where('userId').equals(path['userId'])
            .where('status').equals(queryString['status']) # remove all this line in case of queryString['status'] is null
            .limit(10)
            .startKey(queryString)
            .exec(function (err, acc) {
                if (err == null) {
                    console.log(acc);
                    return cb(null, Api.response(acc));
                } else {
                    console.log(err['message']);
                    return cb(null, Api.errors(200, {5: err['message']}));
                }
            });

sorting objects with multiple conditions

I'm currently trying to sort an array of objects that is being returned in my reducer. I want to sort the apps based off of their name that is being returned, and where there are still currently some names that are null I want to list the null names at the end. Currently when I try to add an additional condition I am getting an error Cannot read property 'toLowerCase' of null which i'm expecting null items just need to move them to the end.

// Actions
export const FETCH_MYAPPS_PENDING = 'widgets/apps/FETCH_PENDING';
export const FETCH_MYAPPS_FULFILLED = 'widgets/apps/FETCH_FULFILLED';

// Reducer
const appsSort = (a, b) => {
  if (a.name != null && b.name != null) {
   if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
   if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
  }
  return 0;
};

export default function reducer(state = { data: [], pending: false }, action) {
switch (action.type) {
case FETCH_MYAPPS_FULFILLED:
  return {
    data: action.apps.sort(appsSort),
    pending: false,
    retrievedAt: Date.now(),
  };
case FETCH_MYAPPS_PENDING:
  return {
    ...state,
    pending: true,
  };
default:
  return state;
 }
}

Prolog , return a value from recursion after if statement

I would like liar_detector to return Solution = Try , where Try is a list , if test_liars returns True , else continue searching , when asked from prolog.

liar_detector(Friends,Try,Max,Solution) :-
    Try == Max -> liar_detector(Friends,Try,0,Solution) ;
    (
        add2(Try,[1,0],NewTry),
        liar_detector(Friends,NewTry,Max,Solution),
        count(1,Try,N),
        test_liars(N,Friends,Try,Flag),
        ( Flag = 'True' -> Solution = Try)
    ).

Prolog , return boolean from consecutive recursive checks

Hello everyone,

The following code does recursive checks. For each call , F gets a value of either 1 or 0 , due to a condition . I want my test_liars predicate return True if all checks had result 1 , and False if at least one call , set F's value to 0.

What test_liars actually does , is not something really eager to explain , but I can if asked.

test_liars should return True to Flag's argument, asked :

  test_liars(2,[3,2,1,4,2],[1,0,0,1,0],Flag)

given different list ,rather than [1,0,0,1,0], it must return False

   test_liars(_,[],_,_) .
   test_liars(N,[HF|TF],[HT|TT],Flag) :-
         (HT == 0 -> ( N >= HF -> F = 1 ; F = 0)
                   ;   ( N <  HF -> F = 1 ; F = 0)),
          test_liars(N,TF,TT,Flag),
          write(F),
          (F == 0 -> Flag = 'True' ; Flag = 'False').

unexpected error in PowerShell if statement

I created a script to pull JPEG snapshots from 2 IP cameras. For me to keep them organized I added some lines to check the date and create a folder matching it. The script also checks if the folder exists and if it does, should skip to the snapshot capture. Everything works fine as intended but it seems for one reason or another the script still tries to create the folder and shows and error in my PS console that the directory exists.

$chk_path = Test-Path "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"
$Make_SnapShot_Folder = New-Item -ItemType Directory -Path "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"
$Camera_A = (new-object System.Net.WebClient).DownloadFile('http://ift.tt/2nDpGFK',"C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))\Camera_A$((Get-Date).ToString('HH-mm-ss')).jpeg")
$Camera_B = (new-object System.Net.WebClient).DownloadFile('http://ift.tt/2nDpGFK',"C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))\Camera_B$((Get-Date).ToString('HH-mm-ss')).jpeg")
if (-not ($chk_path) ) {
write-host "C:\SnapShots doesn't exist, creating it"
$Make_ScrapShot_Folder
} else {
write-host "C:\SnapShots exists, Saving SnapShots"
}
Camera_A
Camera_B

Why is this haskey() condition always false?

I start out with a list of word counts:

julia> import Iterators: partition
julia> import StatsBase: countmap
julia> s = split("the lazy fox jumps over the brown dog");
julia> vocab_counter = countmap(s)
Dict{SubString{String},Int64} with 7 entries:
  "brown" => 1
  "lazy"  => 1
  "jumps" => 1
  "the"   => 2
  "fox"   => 1
  "over"  => 1
  "dog"   => 1

Then I want to compute the no. of ngrams per word and store it in a nested dictionary. The outer key would be the ngram and the inner key the word and inner-most value is the count of the ngram given the word.

I've tried:

ngram_word_counter = Dict{Tuple,Dict}()
for (word, count) in vocab_counter
    for ng in ngram(word, 2) # bigrams.
        if ! haskey(ngram_word_counter, ng)
            ngram_word_counter[ng] = Dict{String,Int64}()
            ngram_word_counter[ng][word] = 0
        end
        ngram_word_counter[ng][word] += 1  
    end
end

And that gives me the data structure I need:

julia> ngram_word_counter
Dict{Tuple,Dict} with 20 entries:
  ('b','r') => Dict("brown"=>1)
  ('t','h') => Dict("the"=>1)
  ('o','w') => Dict("brown"=>1)
  ('z','y') => Dict("lazy"=>1)
  ('o','g') => Dict("dog"=>1)
  ('u','m') => Dict("jumps"=>1)
  ('o','x') => Dict("fox"=>1)
  ('e','r') => Dict("over"=>1)
  ('a','z') => Dict("lazy"=>1)
  ('p','s') => Dict("jumps"=>1)
  ('h','e') => Dict("the"=>1)
  ('d','o') => Dict("dog"=>1)
  ('w','n') => Dict("brown"=>1)
  ('m','p') => Dict("jumps"=>1)
  ('l','a') => Dict("lazy"=>1)
  ('o','v') => Dict("over"=>1)
  ('v','e') => Dict("over"=>1)
  ('r','o') => Dict("brown"=>1)
  ('f','o') => Dict("fox"=>1)
  ('j','u') => Dict("jumps"=>1)

But notice that the values are wrong:

('t','h') => Dict("the"=>1)
('h','e') => Dict("the"=>1)

should have been:

('t','h') => Dict("the"=>2)
('h','e') => Dict("the"=>2)

Since the word the appeared twice.

After a closer look, it seems like the haskey(ngram_word_counter, ng) is always false =(

julia> ngram_word_counter = Dict{Tuple,Dict}()
for (word, count) in vocab_counter
    for ng in ngram(word, 2) # bigrams.
        println(haskey(ngram_word_counter, ng))
    end
end

[out]:

false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false

Why is this haskey() condition always false?

If statement in Postscript

How to create if function in Poscript.

If (1.ps is filename) open fucntion /1 If (2.ps is filename) open function /1

enter image description here

R 3.3.3 "Error in for loop - incompatable dimensions"

while (x < as.numeric(s_max)){
 len2<-length(subdata2)
 resize<-approx(seq_along(subdata2), subdata2, n = len2*x)$y
 len<-length(resize)
 initial<-(length(subdata1)*(scale))+step
 for (i in 1:length(initial)){
  testdata3<-testdata1[(initial[i]):len+(initial[i])]
   corl<-cor(testdata3, resize,use = "na.or.complete")
   if(corl > corr) {
    maxes<-c(corl, (len/len2), i)
    write.table(maxes,"a.txt", append = TRUE, quote = FALSE, row.names =   FALSE, col.names = FALSE)

    }
  }
 x<-(x+0.01)
 setTxtProgressBar(pb, x)

I get incompatible dimensions and when I try to fix it I get NAs for "testdata3" any help will be greatly appreciated

Javascript short circuiting in if statement

I am confused about the below if statement code. Not sure what it is exactly doing

if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}

Can someone please help me to understand this?

Is it a short-circuiting in if statement: i.e

1- if first this.props.filterURL from left side is false then it will return false. 2- if first this.props.filterURL has a value then it will return true and the second variable nextProps.filterURL will be compared to this.props.filterURL on the right most of the statement?

mercredi 29 mars 2017

run scripts if on certain page - rails

Would it be a bad idea to run an if statement on each page load to check whether or not I should run a script. For example I have a really long javascript file that only needs to be run when using forms. But currently in each of my files I have included the document.addEventListener("turbolinks:load", function() which means it runs on every page load.

In my script I am tempted to write an if statement at the beginning of the file like so:

document.addEventListener("turbolinks:load", function() {
  controller = $('body').data('controller')
  action = $('body').data('action')
  if controller == foo && action == bar 
    runScripts();
  else
    return;
  function runscripts() {
    ...

I'm still somewhat new to using javascript with rails so I don't know of another way. Any suggestions?

Changing if else from static to dynamic in javascript

I have an if else condition where, if I upload a file, it will see for the 'code name' i.e, 'abc1' in the file name and compare it to a hard coded value and the returned value will then be compared to a ProductLine. Here I am doing a two way search. how to get rid of all these if elses and make it straight like if I upload a file compare it with productLine and then return it. Below is the code.

    var findProductLineByFilename = function(filename, productLines) {
    filename = filename.replace(/( |\-|\.|_)/g, '');
    var i;
    for (i in productLines) {
        productLine = productLines[i];

        // XXX: Hard-code names
        if (productLine.code_name === 'abc1') {
            if (filename.search(/(war1)|(w1)|(abc1)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc2') {
            if (filename.search(/(w2)|(abc2)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc3') {
            if (filename.search(/(w3)|(abc3)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc4') {
            if (filename.search(/(w4)|(abc4)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc5') {
            if (filename.search(/(w5)|(abc5)/) >= 0) {
                return productLine;
            }
        }
    }
    return null;
};

Trouble Using an If Statement

I am trying to create a table that will generate numbers to round to a specified place value. The table (in HTML code) is shown below.

<head>

    <title>Rounding Worksheet</title>

    <script src = "C:\Users\bryan\Documents\Bryan\Web Pages\Math Macros\math.js"></script>

</head>

<body>

    <table border = "1">

        <col width = "25">
        <col width = "150">
        <col width = "100">
        <col width = "100">
        <col width = "50">

        <tr><td>  </td><td>Place Vaue</td><td>Value</td><td></td></tr>
        <tr><td>a.</td><td><span id = "roundingQuestion1"></span></td><td><span id = "placeValue1"></span></td><td></td></tr>
        <tr><td>b.</td><td><span id = "roundingQuestion2"></span></td><td><span id = "placeValue2"></span></td><td></td></tr>
        <tr><td>c.</td><td><span id = "roundingQuestion3"></span></td><td><span id = "placeValue3"></span></td><td></td></tr>
        <tr><td>d.</td><td><span id = "roundingQuestion4"></span></td><td><span id = "placeValue4"></span></td><td></td></tr>
        <tr><td>d.</td><td><span id = "roundingQuestion5"></span></td><td><span id = "placeValue5"></span></td><td></td></tr>
        <tr><td>e.</td><td><span id = "roundingQuestion6"></span></td><td><span id = "placeValue6"></span></td><td></td></tr>
        <tr><td>f.</td><td><span id = "roundingQuestion7"></span></td><td><span id = "placeValue7"></span></td><td></td></tr>
        <tr><td>g.</td><td><span id = "roundingQuestion8"></span></td><td><span id = "placeValue8"></span></td><td></td></tr>
        <tr><td>h.</td><td><span id = "roundingQuestion9"></span></td><td><span id = "placeValue9"></span></td><td></td></tr>
        <tr><td>i.</td><td><span id = "roundingQuestion10"></span></td><td><span id = "placeValue10"></span></td><td></td></tr>

    </table>        

    <br />
    <br />

    <button onclick="createRoundingQuestions()">Create Questions</button>

</body>

The javascript file that I am using to do this is:

var placeValueName = ["Thousandth", "Hundredth", "Tenth", "Ones", "tens", "Hundreds", "Thousands", "Ten Thousands", "Hundred Thousands"];

function getRndInteger(min, max){

return Math.floor(Math.random() * (max - min) ) + min;

}

function createRoundingQuestions(){

var j;
var x;
var numberDecimals;
var lowValue;
var highValue;

for (j = 1; j <= 10; j++){

    x = getRndInteger(0, placeValueName.length, 0);

    document.getElementById("roundingQuestion"+j).innerHTML = placeValueName[x]; 
    document.getElementById("number"+j).innerHTML = x;

    if (x >= 5){

        lowValue = Math.pow(10, x - 3);
        highValue = Math.pow(10, x - 2);
        numberDecimals = getRndInteger(0, 6);


    } else if (x >= 3) && (x < 5){

        lowValue = 1;
        highValue = 1000;
        numberDecimals = getRndInteger(1, 3);


    } else {

        lowValue = 1;
        highValue = 1000;
        numberDecimals = getRndInteger(2, 6);


    }


    document.getElementById("placeValue"+j).innerHTML = (Math.random() * (highValue - lowValue) ) + lowValue).tofixed(numberDecimals);


}

}

The first part of the javascript file works. It will add the place value (thousands, hundreds, tens, etc.) to each row of the table. However, when I include the If Statement to detemine the number and the proper number of decimal places, the output is a blank table that will not populate. I would appreciate if anyone could point out what I am doing wrong and suggest how to fix it.

PHP: retrieve value from within if statement to use within html input tags on same page

i am trying to retrieve values from an if statement, that is getting the values from a database here is the code i have;

<!DOCTYPE html>
<?PHP
    include('session.php');
    include('recipedbconfig.php');


    if(isset($_POST['submit'])) {
        $postrcpnmesrch = $_POST['rcpnmesrch'];

        if($_SERVER["REQUEST_METHOD"] == "POST") {
            $sql = "SELECT * FROM recipe_table WHERE recipe_name = '".$postrcpnmesrch."'";
            $result = mysqli_query($db, $sql);
            $row = mysqli_fetch_assoc($result);
        }
    }
?>
<html>
    <head>
        <title>Fresh Veg Admin, Edit Recipes</title>
        <link rel=stylesheet type="text/css" href="/FVRC/FVRC.css">
    </head>
    <body>
        <h1>Fresh Veg Admin, Edit Recipes</h1>
        <p>User:<b> <?PHP echo $login_session; ?></b>, logged in.</p>
        <form action="/FVRC/addeditrecipes.php">
            <button type="submit">Back</button>
        </form>
        <br/>
        <hr/>
        <table>
            <form method="POST">
                <tr>
                    <td>
                        <input type="text" placeholder="Search for recipes" name="rcpnmesrch">
                    </td>
                    <td>
                        <button type="submit">Search</button>
                    </td>
                </tr>
            </form>
        </table>
        <br/>
        <hr/>
        <form action="editrecipecheck.php" method="POST">
            <table cellspacing=0 cellpadding=5>
                <tr>
                    <td>
                    </td>
                    <td>
                        <label>Recipe Name:</label>
                    </td>
                    <td>
                        <input type="text" placeholder="Recipe Name" name="rcpnme" value="<?php echo $row['recipe_name']; ?>" required>
                    </td>
                </tr>
                <tr>
                    <td>
                        <label>Ingredient One:</label>
                    </td>
                    <td>
                        <input type="text" placeholder="Ingredient" name="ingnme1" required>
                    </td>

i need the values that the $row array contains, so it can be referenced to in the inputs:

<td>
    <input type="text" placeholder="Recipe Name" name="rcpnme" value="<?php echo $row['recipe_name']; ?>" required>
</td>

but as it is local i cant figure it out, i may just be having a brain fart moment, any help would be appreciated

all i get as an error message is this:

<br />
<b>Notice</b>:  Undefined index: recipe_name in <b>E:\Program Files\xampp\htdocs\FVRC\editrecipe.php</b> on line <b>52</b>
<br />

Swift IF statement to perform action only once

I have an IF statement and I need it to trigger when the score >= 200 but only happen once and not repeatedly.

Here's my code:

if score >= 200 {

        meteRedTimer.invalidate()
        meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)

    } else {    


    }

However this constantly starts the timer all the time when the score is => 200 and not just one timer which I understand.

If I do score = 200 this would work however there is a chance the score could jump from 190 to 210 for example depending on the game play.

How could I basically stop this IF statement once it has been triggered once?

How to write javascript code to create an application that averages Low and High daily temperatures as input by the user

 [enter image description here][1] 

I am asked to write javascript code to calculate the average low and high temperatures.

  • List item

An if statement must be used to ensure that the user enters both low and high temperatures for any given day before the form is submitted. If the user does not enter one or both of the temperatures, a message or messages must be displayed to tell the user that valid low and high temperatures must be entered.

The low and high temperature values entered from the html form must be processed into an array or arrays with loops.
Any help would be appreciated. following the html code I got. I am also attached a picture that shows the final result.

<form action="#" method="post" id="temp">

    <fieldset>

    <legend>Average Low and High Temperatures</legend>
 <div>
     <label for="lowTemp"> Low Temperature </label>
     <input type="number" name="lowTemp" id="lowTemp" required>
</div>
<div>
     <label for="highTemp"> High Temperature </label>

     <input type="number" name="highTemp" id="highTemp" required>

  <div><input type="submit" value="Add temperatures!" id="submit"></div>

    </fieldset>
 </form>       

Is the object a vector?

I am using a template typename recursive function. I would like at some point to ask if the object I am manipulating is a vector (a vector of anything). Something like the is_vector function below

template <typename TYPE>
void f(const std::vector<TYPE>& x)
{
   for (auto& element : x)
   {
      if (is_vector(element))
      {
         f(element);
      } else
      {
         g(element);
      }
   }
}

Is this feasible?

Replace Multiple If\Else with Design Pattern

Based on various threads on SO (ex. Replacing if else statement with pattern ) I understand that I can replace multiple if\else statements with the Command pattern.

My situation is a bit different.

I have a series of Commands and I need to execute each Command only if the previous command was unsuccessful.

For example, suppose I need to retrieve text from a hypothetical page - I could scrape the text directly from the page using screen scraping or I could fetch the text from the API. I would only want to fetch the text from API if screen scraping was not successful. In other words I would only execute the "fetch" command if the "scrape" command didn't work.

In this case, I would test if the scraped String is empty or equal to null and then execute the second Command. If the second command is also unsuccessful I would execute the third Command and so on.

The important point is that we only execute subsequent commands if a certain condition is true/false. The condition is always the same for each Command but the number of commands might grow in the future.

I cannot implement this via the typically suggested route (using a Map and Command interface) bec this would not execute the next Command if the first one failed (it would also be unable to check if a Command was successful or not)

What design pattern could be used to solve this problem?

how would i use if statement to add attributes to the chosen value?

I am newbie and thanks for helping me out. Am trying to create an if statement so the user would be able to enter new details and that details should be stored into the application.

I have looked online but most of the examples out there are calculations of numbers and that's not very helpful, i was hoping you guys could help me out.

Thanks

This is the code i'm working one

def add(self):
    self.carsales.append(ID ,owner,plate Number,Postcode,Price)

    if 

Java repeat part of a program with if and boolean operators

Hello I'm fairly new to java and I had troubles in a little test game. So this is just a part of the code, I want that the user can repeat the part as often as he like with an while operater.

The code is here:

else if (a == 6){
        boolean InGame = true;
        while ( InGame );

        System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
        System.out.println("Spieler Eins");
        double playerOne = scan.nextDouble();
        System.out.println("Spieler Zwei");
        double playerTwo = scan.nextDouble();

        double randomValue = Math.random() * 100.0;

        // Math.abs
        double spacingOne = Math.abs(playerOne - randomValue);
        double spacingTwo = Math.abs(playerTwo - randomValue);
        System.out.println("Die Random Zahl war " + randomValue);

        if (spacingOne < spacingTwo) {
            System.out.println("Spieler Eins hat gewonnen!");
        }

        if (spacingOne > spacingTwo) {
            System.out.println("Spieler Zwei hat gewonnen!");
        }

        if (spacingOne == spacingTwo) {
            System.out.println("Unentschieden!");
        }
        System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
        String PlayAgain = scan.nextLine();
        if  (PlayAgain == "nein");
        boolean inGame = false;

Well I have never worked alot with booleans due to me being new in java. Would nice if you could help me out.

JavaScript closing statements

Okay so my code works, however if the user correctly guesses "blue", the line prints "you got the right color!". Then the code should end. However, it brings up another a k.next(); line. How can I prevent this? If you do not understand, here is the code.

import java.util.Scanner;

public class BEassignment11
{
  public static void main (String [] args)
  {
    Scanner k = new Scanner (System.in);
    String color;
    String again;
    
    do 
    {
      
      System.out.println ("Try to guess my favorite color!");
      color = k.next();
      
      if  (color.equalsIgnoreCase ("blue"))
      {    
        System.out.println ("You got the right color!");
        
      }
      
      else
      
        System.out.println ("That is not the right color. Would you like to try again? Yes/No"); 
        again = k.next();
    }
    while (again.equalsIgnoreCase ("yes"));
    
  }
}

AWK syntax error while using the IF statement

I am very new to AWK although I have previously used the command prompt/terminal.

I have this script below where I am creating subsets of data based on Country Code and State Code. But I get a syntax error.

BEGIN{
   FS = "\t"
   OFS = "\t"
   }

 # Subset data from the states you need for all years 
 if ($5 == "IN-GA" || $5 == "IN-DD" || $5 == "IN-DN" || $5 == "IN-KA" || $5 == "IN-KL" || $5 == "IN-MH" || $5 == "IN-TN" || $5 == "IN-GJ")'{
        if (substr($17, 1, 4) == "2000"){
            print $5, $12, $13, $14, $15, $16, $17, $22, $23, $24, $25, $26, $28 > "Y2000_India_sampling_output.txt"
        }
    }   

On Cygwin, I refer to the script and I run the below lines of code and you see the syntax error immediately:

$ gawk -f sampling_India.awk sampling_relFeb-2017.txt
gawk: sampling_India.awk:20:  gawk if ($5 == "IN-GA" || $5 == "IN-DD" || $5 == "IN-DN" || $5 == "IN-KA" || $5 == "IN-KL" || $5 == "IN-MH" || $5 == "IN-TN" || $5 == "IN-GJ"){
gawk: sampling_India.awk:20:       ^ syntax error

Any thoughts?

Saving a loop's output in a vector in R

I have a .cvs file which consists of 4 columns and 120 rows. I'm attempting to go through every row and where ever i see a "1" in the third column (which here is called "Dam") , i want to save that row in a matrix called "Dam.one"

Here's my code so far:

DamType = c( "Dam.one", "Dam.two", "Dam.three", "NoDam.one", "NoDam.two", "NoDam.three")

for (i in 1:120) {
    if (mercury.raw[i,]["Dam"] == 1) {
        if (mercury.raw[i,]["Type"] == 1){
            DamType["Dam.one"] <-  mercury.raw[i,]  
}}}

I don't know what is wrong with it. Any help is appreciated.

python printing a def function

this might be a silly question but i am a little confused.

class obj:
    def move(x,y,z):
        def on(x,y):
            x = 1
            y = 0 
        if x > y:
            print True
        else:
            print False
        a = on()
        print a

this is my code for a small project i want to start on. however i am unable to print out on() when i compile it, it runs but shows no true or false can i get an explaination why and how i can over come this, thanks :)

How to turn one pin off when another is on

Currently I have pwm pins 9 and 10 set to CS20 giving them a frequency of 31 kHz. How do I make an if statements stating if pin 9 is on pin 10 must be off and vice versa?

Name "shape" does not exist in the current context

For optimization, I'm declaring children of a parent class "Shape" in an if-else structure with the name "shape" and, then, because they share a parent and its methods, coding the interaction just using "shape" instead of having it reappear several times within the if-else. I know I could just use a function, but that doesn't utilize inheritance properly and I still won't know why it didn't work.

Classes:

abstract class Shape
{
    public string shapeText { get; set; }
    public string image { get; set; }

    abstract public string GetParameterFormula();
    abstract public double GetParameter(double side);
}

class Triangle : Shape
{
    public Triangle()
    {
       image = "   ^   \n  / \\  \n /   \\ \n --- ";
       shapeText = "Triangle";
    }

    public override string GetParameterFormula()
    {
        return "'(base * height) / 2'";
    }

    public override double GetParameter(double side)
    {
        return (Math.Sqrt(Math.Pow(side, 2) * Math.Pow(side / 2.0, 2)) * side) / 2;
    }
}

class Square : Shape
{
  public Square()
  {
    image = " ___ \n|   |\n|   |\n --- ";
    shapeText = "Square";
  }

  public override string GetParameterFormula()
  {
    return "'base^2'";
  }

  public override double GetParameter(double side)
  {
    return Math.Pow(side, 2);
  }
}

class Circle : Shape
{
  public Circle()
  {
    image = "  ___\n /   \\ \n |   |\n \\   /\n  ---";
    shapeText = "Circle";
  }

  public override string GetParameterFormula()
  {
    return "'pi * r^2'";
  }

  public override double GetParameter(double rad)
  {
    return Math.PI * Math.Pow(rad, 2);
  }
}

Main:

string shapeType = "";
    double side = 0;
    while (true)
    {
      Console.WriteLine("What type of shape? - (cir/tri/sqr");
      shapeType = Console.ReadLine();
      Console.WriteLine("How long are the sides, or the radius?");
      side = Convert.ToDouble(Console.ReadLine());
      if (shapeType == "cir")
      {
        Circle shape = new Circle();
      }
      else if (shapeType == "tri")
      {
        Triangle shape = new Triangle();
      }
      else
      {
        Square shape = new Square();
      }


      Console.WriteLine("The area formula for a " + shape.shapeText + " is " + shape.GetParameterFormula() + ".");
      Console.WriteLine("The area of a " + shape.shapeText + " with sides/radius of length " + side + " is " + shape.GetParameter(side));
    }

Combining ifelse and any to create new column - R 3.3.2 Windows 7

I have a data.table and I'm trying to create a new column by checking to see if a row has particular values in any of a given set of columns.

head(d1)

   MEDREC_KEY   pat_key           drug1          drug2          drug3       drug4        drug5       drug6      drug7     drug8 drug9 drug10 drug11 drug12
1: -140665983 669723105 Anti-infectives Cephalosporins     Ethambutol   Isoniazid   Macrolides Penicillins Quinolones Rifamycin    NA     NA     NA     NA
2: -606290573  85924804 Anti-infectives   Beta-lactams Cephalosporins Penicillins   Quinolones          NA         NA        NA    NA     NA     NA     NA
3: -615873176 161009395  Cephalosporins    Penicillins             NA          NA           NA          NA         NA        NA    NA     NA     NA     NA
4: -616819481  36280536 Anti-infectives Cephalosporins     Macrolides  Quinolones           NA          NA         NA        NA    NA     NA     NA     NA
5: -625709819 720290063 Anti-infectives Cephalosporins     Ethambutol   Isoniazid Pyrazinamide  Quinolones  Rifamycin        NA    NA     NA     NA     NA
6: -637094857 720918635 Anti-infectives    Penicillins     Quinolones          NA           NA          NA         NA        NA    NA     NA     NA     NA

What I want to happen is if any of the "drug" columns == "Macrolides" AND any of the same columns == "Cephalosporins" then my new column, "correct" == 1 otherwise "correct" == 0 (or it could be logical), like so:

head(d1)
   MEDREC_KEY   pat_key           drug1          drug2          drug3       drug4        drug5       drug6      drug7     drug8 drug9 drug10 drug11 drug12 correct
1: -140665983 669723105 Anti-infectives Cephalosporins     Ethambutol   Isoniazid   Macrolides Penicillins Quinolones Rifamycin    NA     NA     NA     NA   1
2: -606290573  85924804 Anti-infectives   Beta-lactams Cephalosporins Penicillins   Quinolones          NA         NA        NA    NA     NA     NA     NA   0
3: -615873176 161009395  Cephalosporins    Penicillins             NA          NA           NA          NA         NA        NA    NA     NA     NA     NA   0
4: -616819481  36280536 Anti-infectives Cephalosporins     Macrolides  Quinolones           NA          NA         NA        NA    NA     NA     NA     NA   1
5: -625709819 720290063 Anti-infectives Cephalosporins     Ethambutol   Isoniazid Pyrazinamide  Quinolones  Rifamycin        NA    NA     NA     NA     NA   0
6: -637094857 720918635 Anti-infectives    Penicillins     Quinolones          NA           NA          NA         NA        NA    NA     NA     NA     NA   0

I've tried both of these (but am still learning how to decipher warning messages so those don't help much, especially as I am new to data.table):

> d1$correct<-ifelse(d1[,c(3:14)]=="Macrolides" | d1[,c(3:14)]=="Cephalosporins", 1, 0)
Warning messages:
1: In `[<-.data.table`(x, j = name, value = value) :
  12 column matrix RHS of := will be treated as one vector
2: In `[<-.data.table`(x, j = name, value = value) :
  Supplied 56868 items to be assigned to 4739 items of column 'correct' (52129 unused)
> 
> 
> selected_cols<-c("drug1", "drug2", "drug3", "drug4", "drug5", "drug6", "drug7", "drug8", "drug9", "drug10", "drug11", "drug12")
> d1$correct<-ifelse(d1 %in% selected_cols=="Macrolides" | d1 %in% selected_cols=="Cephalosporins", 1, 0)
Warning message:
In `[<-.data.table`(x, j = name, value = value) :
  Supplied 16 items to be assigned to 4739 items of column 'correct' (recycled leaving remainder of 3 items).

The closest I've gotten is this:

d1$correct<-apply(d1, 1, function(r) any(r %in% c("Macrolides", "Cephalosporins")))

Which will give TRUE if either of those is true across columns, but I can't figure out how to do it if both of those is true across columns. I'd prefer to not have to use a stunningly massive ifelse statement, since I have 12 columns and more combinations I'll need to make, and the NA's throw it off anyway.

I'd love a dplyr or data.table solution since those are so elegant, but at this point I'm desperate.

How to successfully get out of this do-while loop?

This code was smooth sailing until i SPECIFICALLY include the IF-STATEMENT containing a BREAK inside the DO-WHILE LOOP which SHOULD report a math error if fv1 = 0 (for anything divided by zero is undefined). However, unexpected results were printed. Please help me guys on my loop!

Off topic: I am a beginner, literally started from scratch, and by that i mean "Hello World" program. Big thanks to you'll for all the help. This site will save my grades this semester. hehe

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

const double R = 0.082054;
double f(double a,double b,double P,double T,double v);
double f(double a,double b,double P,double T,double v)
{
    double q =P*pow(v,3)-(P*b+R*T)*pow(v,2)+a*v-a*b;
    return q;
}
double fPrime(double a,double b,double P,double T,double v);
double fPrime(double a,double b,double P,double T,double v)
{
    double s =3*P*pow(v,2)-2*(P*b+R*T)*pow(v,1)+a;
    return s;
}
int main()
{
//INPUT STAGE!
cout << "Use gas constant, R: " << R << endl;

double a,b,P,T,Tc;
cout << "\nUse test value, a: ";
cin >> a;
cout << "\nUse test value, b: ";
cin >> b;
cout << "\nUse pressure, P (atm): ";
cin >> P;
cout << "\nUse absolute temperature, T (K): ";
cin >> T;

double v,v1=0,fv,fv1,N,e;
int iteration = 0;
cout << "\nUse initial guess for molal volume, v: ";
cin >> v;
cout << "\nUse maximum number of iterations, N: ";
cin >> N;
cout << "\nUse tolerance, e: ";
cin >> e;
cout << "\n";

do
{
    v = v1;
    fv = f(a,b,P,T,v);
    fv1 = fPrime(a,b,P,T,v);
    if (fv1=0)
    {
       cout << "Math Error";
       break;
    }
    v1 = v-(fv/fv1);
    cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
    iteration++;
}
while(iteration<N && abs(v1-v)>e);

return 0;
}

Two AND/OR in one bash if statement

i have a special condition to test in a bash script. I thougt about something like:

if [[ $categorie = "DG" || $categorie = "DI" ]] && [[ $client != "host1" || $client != "host2" ]]; then
    echo "requirements are met"
else
    echo "requirements not met"
fi

In Words: If categroie is DG OR DI AND client is NOT host1 OR host2 then do stuff.

Is this correct? For me it looks like it just cares about the categorie and if the categorie condition is met it's ok and prints "requirements are met" and don't care about the condition for the client at all.

Kind

Regards

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

I have sorted my dataframe so that the time is in chronological order. The column 'Group' gives rows that belong to the same group, the same name (in this case, the name is the time of the first row that belongs to the group).

A 'group' will consist of at least 2 rows. Not all rows will belong to a group.

I am trying to create a new column named 'Bucket' that will give the rows that belong to a group the value 'yes' and those rows which do not belong to a group the value '0'. I am getting an error.

The code is as follows:

data['Bucket'] = 0

if (data['Group'] == data['Group'].shift(-1)) & (data['Group'] == data['Group'].shift(1)):

    data['Bucket'] = 'Yes'

elif (data['Group'] == data['Group'].shift(-1)) & (data['Group'] != data['Group'].shift(1)):

    data['Bucket'] = 'Yes'
elif (data['Group'] != data['Group'].shift(-1)) & (data['Group'] == data['Group'].shift(1)):

    data['Bucket'] = 'Yes'
else:

    data['Bucket'] = '0'


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

How to access/get the value of a Variable inside a nested if statement to outside the main if statement

I have this code sample which I was developing. Here I have declared two variables (initialPath, lastPath) outside the main if-else statement. Inside the main If statement there is a nested if-else statement. I have initialized the variable (initialPath) inside the nested if statement. I need that value to be used outside the nested if-else statement. I have attached my code snippet. If anyone can help to solve my problem, I'd be glad :)

    FileWriter writer;
    File initialPath=null;
    File lastPath=null;

    if (clicked == 1) {


        int sf = savefile.showSaveDialog(null);

        if (sf == JFileChooser.APPROVE_OPTION) {

            initialPath=savefile.getSelectedFile(); // in here the Variable values is initialized/assigned

            try {

                if (savefile.getFileFilter().equals(filter2)) {

                    String path = savefile.getSelectedFile() + ".java";
                    File file = new File(path);
                    writer = new FileWriter(file, false);
                    System.out.println(savefile.getFileFilter());
                    writer.write(jTextPane1.getText());

                    writer.close();
                } else if (savefile.getFileFilter().equals(filter)) {

                    System.out.println("2");
                    String path = savefile.getSelectedFile() + ".txt";
                    File file = new File(path);
                    writer = new FileWriter(file, false);

                    writer.write(jTextPane1.getText());

                    writer.close();


                } else {
                    System.out.println("No format");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (sf == JFileChooser.CANCEL_OPTION) {


            clicked = 0;

        }

    } else {


        try {

            lastPath=initialPath.getParentFile(); //but in here lastPath become NULL because initialPath is NULL... 

    //I need to get the value of initialPath to this ELSE statement

            if (savefile.getFileFilter().equals(filter2)) {

                String path = savefile.getSelectedFile() + ".java";
                File file = new File(path);
                writer = new FileWriter(file, false);
                System.out.println(savefile.getFileFilter());
                writer.write(jTextPane1.getText());

                writer.close();
            } else if (savefile.getFileFilter().equals(filter)) {

                String path = savefile.getSelectedFile() + ".txt";
                File file = new File(path);
                writer = new FileWriter(file, false);

                writer.write(jTextPane1.getText());

                writer.close();


            } else {
                System.out.println("No format");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

Progressive column grouping spacing issue

I have four columns of Ident codes corresponding to a single individual with multiple entries. I need to get a list of all unique Ident codes corresponding to each individual on one line with a comma followed by a space between them. I have a VBA to remove the duplicates, but the VBA won't work - I think because the commas don't have a space after them in the final row of Ident code data that I'm asking it to look at. I feel like there is an easy solution and I'm just not seeing it. I'm VERY new to VBA and moderately good with Excel.

This is the statement I'm using to return the progressive values of codes pertaining to each person, the final row being the culmination of all of their codes in one cell

=IF(A12=A11,P11&"," &O12, O12)

See the attached file column P - when it gets to four or more codes there's no space after the comma any longer and the VBA duplicate remover doesn't work.

[Sample of my Worksheet

After I get that formula down I should be able to run this VBA to get rid of the duplicates in the line with the culmination of all the codes... I think...

Function RemoveDupes2(txt As String, Optional delim As String = " ") As String
Dim x
'Updateby20140924
With CreateObject("Scripting.Dictionary")
    .CompareMode = vbTextCompare
    For Each x In Split(txt, delim)
        If Trim(x) <> "" And Not .exists(Trim(x)) Then .Add Trim(x), Nothing
    Next
    If .Count > 0 Then RemoveDupes2 = Join(.keys, delim)
End With
End Function

I don't know what else to try, there are hundreds of thousands of these that I need to go through

Any help anyone can give me would be amazing and I would be so thankful. I found the formulas and VBA on this site and modified them to my need, but I think I don't quite understand it enough to modify it correctly.

How to modify the for() loop or if() statements to replace multiple characters in a String in my case?

My input String uid contains 10 characters, first 4 chars are “A~Z” or "0~9", last 6 chars are "0~9". I am doing fuzzy query in HBase. Following is my code. If the input String uid contains only one '?', no mater where the '?' is, it works well. For example, if uid="A01A000?00", the results are "A01A000000","A01A000100,"A01A000200""……"A01A000900",pretty good.

However, if uid contains two or more '?' in different digits, it fails. For example, if uid= "A01A000?0?", the results are "A01A000000", "A01A000101", "A01A000202", "A01A000303"…… "A01A000909", "A01A000000","A01A000101", "A01A000202", "A01A000303"…… "A01A000909"

acutually, I want the two '?' change like 00,01,02……09,10,11,12……19……90,91,92……99, not 11,22,33,44……99 like above

List<Get> gets = new ArrayList<>();  
for (String uid : uidsArr) {

    for(int k= 0; k<4 ; k++){
        if(uid.charAt(k) == '?'){
            for (int i =0; i<26; i++){
                get = new Get((uid.replace(uid.charAt(k),(char)('A' + i))).getBytes());  
                    get.setMaxVersions(versions);  
                    gets.add(get);  
            }
            for (int i =0; i<10; i++){
                get = new Get((uid.replace(uid.charAt(k),(char)(i + '0'))).getBytes());  
                    get.setMaxVersions(versions);  
                    gets.add(get);  
            }
        }   
    }

    for(int k=4; k<10; k++ ){
        if(uid.charAt(k) == '?'){
            for (int i =0; i<10; i++){
                get = new Get((uid.replace(uid.charAt(k), (char) (i + '0'))).getBytes());  
                    get.setMaxVersions(versions);  
                    gets.add(get);  
            }
        }
    }


    get = new Get(uid.trim().getBytes());  
    get.setMaxVersions(versions);  
    gets.add(get);  
}  

Result[] results = table.get(gets);  

send email based on this condition

plz some 1 help can u tell me how to send email based on this condition

explain:- this condition will only view before 45 days expire i want send email base on the condition down. Thank u ....

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{


    GridView1.Columns[4].Visible = false;


      Label a = e.Row.FindControl("Label2") as Label;
      Label b = e.Row.FindControl("Label3") as Label;

    if ((a != null) & (b!= null))
    {
        DateTime lblDate;
        if ((!DateTime.TryParse(a.Text, out lblDate)) & (!DateTime.TryParse(b.Text, out lblDate)))
        {
            // date time conversion not success 
            // you may have empty or invalid datetime 
            // do something in this case 
            return;
        }

        if (lblDate <= DateTime.Today.AddDays(45))
        {

            e.Row.Visible = true;

        }

        else
        {
            e.Row.Visible = false;

        }


          }
           }

var == value or value == var , which is standard way? [on hold]

I have seen at many place developer using to compare value == var like

if ('https' === location.protocol) {
   port = 8443;
   protocol = 'wss://';
   isSecure = true;
}

I know it does not effect , as a== b is same as b ==a but as i couldn't find anything on this so I want to know

Which is standard way and is there really any standard for this ?

How many CUDA threads satisfy IF condition?

I have a simple CUDA kernel, which checks the distance squares D2 in set of (x_inp,y_inp,z_inp) points given as an input. I want to know, HOW MANY pairs could be formed with the j-th point in case of a limitation, that their distance must be less than 1000000. I want to store number of such cases in N_OK. But the N_OK is always 1. Is there another way how to get this information?

__global__void  GPUCode( float* x_inp, float* y_inp, float* z_inp, int N)
{

 const uint bid = blockIdx.y * gridDim.x + blockIdx.x;
 const uint tid = threadIdx.x;
 const uint idx = bid * blockDim.x + tid;

 if (idx >= N) return;

 float x = x.inp[idx];
 float y = y.inp[idx];
 float z = z.inp[idx];

 for(int j = 0; j < N; j++)
 {
  int N_OK = 0;
  if (j != idx) 
   {
    float dx = (float)(x.inp[j] - x);
    float dy = (float)(y.inp[j] - y);
    float dz = (float)(z.inp[j] - z);
    float D2 = dx*dx + dy*dy + dz*dz;
    if (D2 < 1000000)
     {
      N_OK = N_OK + 1;
      printf("%f \n", D2);
     }
   }

   printf("%d \n", N_OK);

  }

 }

The condition has length > 1 and only the first element will be used in R

I am trying to find out age range from a simple data in R. But I am getting the error below. "The condition has length > 1 and only the first element will be used"

My data:

YEAR
47
31
30
41
31
32

I am trying to find out age range from YEAR column.

data$YEAR <- getAgeRange(data$YEAR)

getAgeRange function is like that:

 getAgeRange <- function(age) {
     if (age < 15) {
          age <- "Under 15"
     } else if (age >= 15 & age <= 17) {
          age <- "15-17"
     } else if (age >= 18 & age <= 24) {
          age <- "18-24"
     } else if (age >= 25 & age <= 34) {
          age <- "25-34"
     } else if (age >= 35 & age <= 44) {
          age <- "35-44"
     } else if (age >= 45 & age <= 54) {
          age <- "45-54"
     } else if (age >= 55 & age <= 64) {
          age <- "55-64"
     } else if (age >= 55 & age <= 64) {
          age <- "55-64"
     } else if (age > 65) {
          age <- "Over 65"
     }

     return(age)
}

I am getting the error below:

Warning messages:
1: In if (age < 15) { :
   the condition has length > 1 and only the first element will be used
2: In if (age >= 15 & age <= 17) { :
   the condition has length > 1 and only the first element will be used
3: In if (age >= 18 & age <= 24) { :
   the condition has length > 1 and only the first element will be used
4: In if (age >= 25 & age <= 34) { :
   the condition has length > 1 and only the first element will be used
5: In if (age >= 35 & age <= 44) { :
   the condition has length > 1 and only the first element will be used
6: In if (age >= 45 & age <= 54) { :
   the condition has length > 1 and only the first element will be used

Can I use an if statement with multiple conditions? PHP

I bet I can, but would it work like this?

function dutchDateNames($) {
        $day = explode('-', $date)[2];
        $dutchday = ($day < 10) ? substr($day, 1) : $day;

        $month = explode('-', $date)[1];
        if ($month == '01' . '02') {
            $dutchmonth = 'Januari' . 'Februari';
        }

        $dutchdate = $dutchday . ' ' . $dutchmonth . ' ' . explode('-', $date)[0];
        return $dutchdate
    }

So, if $month is 01, $dutchmonth should be Januari. If $month is 02, $dutchmonth should be Februari, and so on. I have the feeling I'm not doing this right?

for some reason my if statement is not working

i made this program for internal assesment and i still have "write to text and read from text remaining", but here for some reason , my if statement: if(q < quantity[m]) in case 2 is not working and it always runs the other one, i seriously have no idea what is wrong

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package noorhamara;

import java.io.*;
public class Noorhamara2 {

    /**
     *
     * @param args
     * @throws IOException
     */
    @SuppressWarnings("empty-statement")
    public static void main(String[] args)throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        PrintWriter writer;
        writer = new PrintWriter("C:\\Users\\hares\\Desktop\\nicebro.txt");
        int ch,ch1,ch2,n,i,j,flag=-1,flag2=0,sum=0,k=0,q,i2,max=1,m;
        String name,p;
        String item[]=new String[500];
        int quantity[]=new int[500];
        int price[]=new int[500];
        //declaring variables
             while(flag!=1 && max<=5)
            {
                System.out.print("Enter Password:- ");
                p=br.readLine();
                if(p.compareTo("1234")==0)
                {
                    flag=1;
                    break;
                }
                else
                System.out.println("Wrong password! Try again?!");
                max++;
                if(max==5)
                {

                    System.out.println("\fTry after sometime....\nwait for 10 counts..");
                    for(j=1;j<=10;j++)
                    {
                        for(k=0;k<=899999999;k++);
                        System.out.print(j+"..");
                    }
                    max=0;

                    System.out.println("\f");
                }
        }
        System.out.print("\f");
        z:while(true)
            {
                System.out.println("1.Enter Stock Items\n2.make customer bill\n3.view items remaining\n4.Exit");
                System.out.print("Please enter your choice in no.:-");
                ch1=Integer.parseInt(br.readLine());
                switch(ch1)
                {
                    case 1:
                    System.out.println("\fhow many items do you wish to feed:");
                    n=Integer.parseInt(br.readLine());
                    for(i=k;i<k+n;i++)
                    {
                        System.out.print("Please enter name of item "+(i+1)+":-");
                        item[i]=br.readLine();
                        writer.write(item[i]);
                        System.out.print("Please enter price:-");
                        price[i]=Integer.parseInt(br.readLine());
                        writer.write(item[i]);
                        System.out.print("Please enter quantity available:-");
                        quantity[i]=Integer.parseInt(br.readLine());
                        writer.write(item[i]);
                        System.out.print("\f");
                    }
                    k=k+n;
                    break;
                    case 2:
                    System.out.print("\f");
                    System.out.println("How many items");
                    i2=Integer.parseInt(br.readLine());
                    for(i=0;i<i2;i++)
                    {
                        System.out.println("enter item name:");
                        name=br.readLine();
                        for(m=0;m<k;m++)
                            {  
                                if(name.equals(item[m]))
                                flag2=1;
                            }
                        if(flag2==1)
                           { System.out.println("enter quantity:");
                             q=Integer.parseInt(br.readLine());
                             if(q < quantity[m])
                             {
                               System.out.println("This finally works");
                                 sum+=(price[m]*q);
                               quantity[m]=quantity[m]-q;
                               if(quantity[m]<10)
                                 System.out.println("quantity of "+item[m]+" is very low");
                             }
                             else if (q > quantity[m])
                              System.out.println("quantity exeeded"); 
                             else
                                System.out.println("error");
                            }
                        else
                         System.out.println("item not available in shop");
                    }

                    System.out.println("Total value of the purchase : "+sum);
                    sum=0;
                    flag2=0;
                    break;
                    case 3:
                    System.out.println("\fitem\t\t\tprice\t\t\tavailibility");
                    for(i=0;i<k;i++)
                    {
                        System.out.println(item[i]+"\t\t\t"+price[i]+"\t\t\t"+quantity[i]);
                    }
                    System.out.println("\n1.continue\n2.exit");
                    ch2=Integer.parseInt(br.readLine());
                    if(ch2==2)
                    break z;
                    System.out.print("\f");
                    break;
                    case 4:
                    System.out.println("thank you!!");
                    break z;
                }
            }
         writer.close();
        }
    }

mardi 28 mars 2017

get-aduser properties and users with null replace with space output

need to get adusers and replace the null value to a empty space so the xml file will be defined, now when its runned if user properties are empty it will not add value it will be like properties are defined in a array

# Base XML $xml = [xml]@" <?xml version="1.0" encoding="UTF-8"?> <users> </users> "@

$ad=get-aduser miljkovicd -properties name| select name| Out-Null # Template for creating nodes. $userTemplate = @" <user> <sn>{0}</sn> <givenName>{1}</givenName> <mailNickname>{2}</mailNickname> <mail>{3}</mail> <telephoneNumber>{4}</telephoneNumber> <company>{5}</company> <title>{6}</title> <employeeID>{7}</employeeID> <mobile>{8} </mobile> <facsimileTelephoneNumber>{9} </facsimileTelephoneNumber> <extensionAttribute11>{10}{11}"@`

#$base = 'ou=my users,dc=mydomain,dc=com' #$date = (Get-Date).AddDays(-1) $property=@"sn","givenName","mailNickname","mail","telephoneNumber","company","title","employeeID","mobile","extensionAttribute11","extensionAttribute12" )

$Users= Get-ADUser mil -Properties $property |ForEach{

# Create and append a child for each user $child = $xml.ImportNode(([xml]($userTemplate -f $users.cn,$_.givenname,$_.mailNickname,$_.mail,$_.telephoneNumber,$_.company,$_.cn,$_.employeeID,$_.mobile,$_.facsimileTelephoneNumber,$_.extensionAttribute11,$clean)).DocumentElement,$true) $xml.documentelement.AppendChild($child) | Out-Null

# $child = $xml.ImportNode(([xml]($userTemplate2 -f $_.title,$_.employeeID,$_.mobile,$_.mail,$_.extensionAttribute11,$_.extensionAttribute12)).DocumentElement,$true) #$xml.documentelement.AppendChild($child) | Out-Null }

Should use your own path and a variable here.

$xml.Save("c:\temp\te4.xml")

I am getting error msg as Error in if (abs(p11_p10) < 1e-04 & abs(alpha1_alpha0) < 1e-04) { : missing value where TRUE/FALSE needed

I am getting error msg as mentioned above. I am trying to do simulation and estimation and for that I have wrote the above program. Kindly help me to solve this problem.

p1=0.2;p2=0.3;p3=1-p1-p2;alpha=0.4

n=10;k=1;count=0

p11_p10=0.01

alpha1_alpha0=0.01

alpha0=0.5;p10=0.3;p11_p10=0.1;alpha1_alpha0=0.1

repeat

{

repeat{




    x1<-rgeom(n-k,p3/(1-p2))




    y1<-rnbinom(n-k,x1+1,1-p2)




    p3star<-1-alpha*p1-alpha*p2




    xstar<-rgeom(k,p3star/(1-alpha*p2))




    ystar<-rnbinom(k,xstar+1,1-alpha*p2)





    xsamp<-c(x1,xstar)




    ysamp<-c(y1,ystar)




    x=rep(0,n)




    y=rep(0,n)




    z=rep(0,n)




for(i in 1:n)




        {




          x[i]=(xsamp[i]+ysamp[i])*(alpha0^(xsamp[i]+ysamp[i]-1))




          y[i]=alpha0^(xsamp[i]+ysamp[i])




          z[i]=((xsamp[i]+ysamp[i])*(xsamp[i]+ysamp[i]-1)*
                (alpha0^(xsamp[i]+ysamp[i]-2)))




        }




          x;y;z




        num=sum(x)




        den=sum(y)




        num1=sum(z)




        term=num1/den




        if(term>0)




        {




          T1<-sum(xsamp); T2<-sum(ysamp)




        if (T1!=0 || T2!=0)




            {




            break




            }




        }




    }

print(T1)

print(T2)

count=0

repeat




    {




    count=count+1




    b1=(k/n)




    A=alpha0*(((T1+T2)^2)+n*(T1+T2))




    B=(-T1*((alpha0+1)*(T1+T2)+(n+alpha0-1)))




    C=(T1^2)





    t1_p1_alpha<-A*(p10^2)+(B*p10)+C




    t2_p1_alpha= -((p10*(T1+T2))/(T1-alpha0*(T1+T2)*p10))+(num/den)






    t1dash_wrt_p1=2*A*p10+B




    t1dash_wrt_alpha=(p10^2)*((T1+T2)^2)+n*(p10^2)*(T1+T2)-p10*T1*(T1+T2+1)




    t2dash_wrt_p1=(((-T1*(T1+T2))/(T1-alpha0*(T1+T2)*p10))^2)




    t2dash_wrt_alpha= (-((p10*(T1+T2))^2)/((T1-alpha0*(T1+T2)*p10)^2))+(num1/den)-((num^2)/(den^2))




    a<-t1_p1_alpha;b<-t1dash_wrt_p1;c<-t1dash_wrt_alpha




    d<-t2_p1_alpha;e<-t2dash_wrt_p1;f<-t2dash_wrt_alpha






    alpha1=alpha0+(1/c)*(-a-b*((a*f-d*c)/(e*c-b*f)))
    p11=p10+((a*f-d*c)/(e*c-b*f))





    p11_p10=p11-p10




    alpha1_alpha0<-alpha1-alpha0





    if(abs(p11_p10)<0.0001 & abs(alpha1_alpha0)<0.0001)




            {




             break




            print(p11)




            print(alpha1)




            }




            else




            {




            p10<-p11




            alpha0<-alpha1




            }




    if (count>50){break}




    }

}