dimanche 31 octobre 2021

Viewing a file in python

I am trying to add a new account in my file which already consist of a username and password of other accounts, after doing it I only want to view the new added accounts or contents of the file like this but have certain distances with each other:

No. Account Name Username Password

1 Facebook admin 123admin

2 Google user 123user

Below is my code for adding a new account in my file:

 def Add_account():

    account = input("\nEnter the name of the account: ")
    username = input(f"Enter the username of your {account}: ")
    password = input(f"Enter the password of your {account}: ")
    ask = input(f"Do you want to save {account} credentials? [Y|N]: ")

    if new_ask == "Y":
        with open("info.txt", "a") as file:
            file.write("\n" + encrypt(account) + ":" + encrypt(username) + ":" + encrypt(password))
            file.close()
        
Add_account()

How can I view only the new accounts in my file?

John Guttag's Figure 8.4 class Grad Student, what should the if statement look like for an undergraduate and a graduate student?

import datetime

class Person(object):

def __init__(self, name):
    """Create a person"""
    self.name = name
    try:
        lastBlank = name.rindex(' ')
        self.lastName = name[lastBlank+1:]
    except:
        self.lastName = name
    self.birthday = None
    
def getName(self):
    """Returns self's full name"""
    return self.name

def getLastName(self):
    """Returns self's last name"""
    return self.lastName

def setBirthday(self, birthdate):
    """Assumes birthdate is of type datetime.date
       Sets self's birthday to birthdate"""
    self.birthday = birthdate

def getAge(self):
    """Returns self's current age in days"""
    if self.birthday == None:
        raise ValueError
    return (datetime.date.today() -self.birthday).days

def __lt__(self, other):
    """Returns True if self's name is lexicographicallyless than other's name, and False otherwise"""
    if self.lastName == other.lastName:
        return self.name < other.name
    return self.lastName < other.lastName

def __str__(self):
    """Returns self's name"""
    return self.name

class MITPerson(Person):

nextIDNum = 0 #identification number

def _init_(self, name):
    Person._init_(self, name)
    self.idNum = MITPerson.nextIdNum
    MITPErson.nextIdnum += 1
    
def getIdNum(self):
    return self.idNum

def _lt_(self, other):
    return self.idNum < other.idNum

class Student(MITPerson): pass

class UG(Student): def init(self, name, classYear): MITPerson.init(self, name) self.year = classYear def getClass(self): return self.year

class Grad(Student): def init(self, name, classYear): MITPerson.init(self, name) self.year = classyear def getClass(self): return self.year if Grad != p5: print("Grad student is false") passstrong text

If loop not working inside powershell function

Function RemoveDataFromFile ([string] $FileType,[string] $RecordToRemove)
{
$stupidShit=$RecordToRemove
Write-Host $stupidShit
$RemovedLines = @()
Write-Host "Entering Remove File Proc"
$FolderName="C:\Temp\GTR"
$typeToCheck = switch ($FileType) {
    "PDT" {"pdtcode" ; break}
    "DET" {"detnumber"; break}
    "ADR" {"detnumber"; break}
    "POS" {"detnumber"; break}
    "PYD" {"detnumber"; break}
    "SMN" {"detnumber"; break}
    "REL" {"pdtcode"; break}
    "DED" {"detnumber"; break}
    "ALW" {"detnumber"; break}
    "TER" {"detnumber"; break}
    "RTN" {"rtnparam01"; break}

   default {"Something else happened"; break}
   }


 $FileList = Get-ChildItem -Path $FolderName -Filter "*$FileType*"
#write-host $FileType "_" $FileList "++" $recCheck

foreach($singleFiles in $FileList)
{
Write-Host "Checking -" $singleFiles.Name "++ " $recCheck
    $data = foreach($line in Get-Content $singleFiles.FullName)
            {
           
            Write-Host "checiking"
           
            $recCheck="$typeToCheck=""$RecordToRemove"""
            Write-Host "Record Trying to check " $RecordToRemove
              Write-Host "Entering COntent to Check - " $recCheck
           Write-Host $line
           $what=($line -match $recCheck )
           Write-Host "out before loop"  $what
        
                if( $what )
                {
                Write-Host "Match Found"
                $object = New-Object -TypeName PSObject
                $object | Add-Member -Name 'Type' -MemberType NoteProperty -Value $FileType
                $object | Add-Member -Name 'FileName' -MemberType NoteProperty -Value $singleFiles.Name
                $object | Add-Member -Name 'Info' -MemberType NoteProperty -Value $line

                $RemovedLines+=$object
                }
                else
                {
                  $line
                }
              

            }
  #  $data | Set-Content $singleFiles.FullName 
}

return $RemovedLines

}

# call
$Det_RemovedLines=RemoveDataFromFile "DET" $DetRecord.EmployeeID.Trim() 

($line -match $recCheck ) is false - but is correct!!!

($line -match $recCheck ) is false but im checking detnumber="303353y" in a line cbr="detadd",detnumber="303355y",dettitle="Mrs",detsurname="Awesome123",detdatejnd= so the condition should return true but doesn't. any help would be much appreciated.

Java - assign number of character less than 4

/* * mutator method * parameter changedNumber * method checks the number of characters in the parameter * if the number of characters is less than 4 assign * listingNumber a string of 4 zeros, otherwise assign * listingNumber the value of the parameteer */

My if statement returns the error code 'bad operand types for binary operator <' I am not too sure how to set the number of character less than 4

public void setListingNumber(String changedNumber)
{
    listingNumber = changedNumber;
    
        if (changedNumber < 4) {
       
            listingNumber = "0000";
        }
        else {
            listingNumber = changedNumber;
    }
}

Why does this program only give me output the first case of an if conditional? [duplicate]

When entering values ​​that check the states, the else if in this program does not give an output unless the condition is fulfilled in the first if condition only.

#include<stdio.h>
#include"STD_TYPES.h"
#include"REG.h"
#include"BIT_MATH.h"
#define PA 40
#define PB 63
#define PC 20
#define PD 10
 
void main (void){
    int pin ;
    
    printf("Enter The Pin Number \n");
    scanf("%d",&pin);
    if (PA<=pin<=PA+7){
        for(int i=0 ;i<=7;++i){
            if(pin==PA+i){
                printf("your are in the port A and pin %d \n",i);
                break;
            }
        }
    }else if(PB<=pin<=PB+7){
        for(int i=0 ;i<=7;++i){
            if(pin==PB+i){
                printf("your are in the port B and pin %d \n",i);
                break;
            }
        }
    }else if(PC<=pin<=PC+7){
        for(int i=0 ;i<=7;++i){
            if(pin==PC+i){
                printf("your are in the port C and pin %d \n",i);
                break;
            }   
        }
    }else if(PD<=pin<=PD+7){
        for(int i=0 ;i<=7;++i){
            if(pin==PD+i){
                printf("your are in the port D and pin %d \n",i);
                break;
            }
        }
    }
}

Note that when I use if instead of else if the program runs and gives output. What's the problem?

Need Query or condition to get selected data in flutter

I am stuck in creating query for the selected items and show selected data on other page. So help me to create query or condition. when I press floating action button then I want to get selected items data on other page.

Here is Main File code:

class MenuPage extends StatefulWidget {
  const MenuPage({Key? key}) : super(key: key);

  @override
  _MenuPageState createState() => _MenuPageState();
}

class _MenuPageState extends State<MenuPage> {
  DatabaseReference db = FirebaseDatabase.instance.reference();
  User? curUser = FirebaseAuth.instance.currentUser;

  int? len;
  List<GetData>? data;

  late List<bool>? avail = List.generate(
    len!,
    (index) => false,
  );

  late List<TextEditingController>? qty = List.generate(
    len!,
    (index) => TextEditingController(),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Today's Menu"),
        centerTitle: true,
        backgroundColor: Colors.deepOrange,
      ),
      body: StreamBuilder<List<GetData>>(
        stream: DataStreamPublisher("Juices").getMenuStream(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            data = snapshot.data;
            len = data!.length;
            return SafeArea(
              child: SingleChildScrollView(
                child: Container(
                  margin: EdgeInsets.symmetric(vertical: 10.0),
                  width: double.infinity,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        width: double.infinity,
                        child: DataTable2(
                          showBottomBorder: true,
                          headingRowHeight: 40,
                          showCheckboxColumn: true,
                          sortAscending: true,
                          columnSpacing: 5,
                          dataRowHeight: 60,
                          dividerThickness: 2,
                          bottomMargin: 20.0,
                          checkboxHorizontalMargin: 5,
                          columns: [
                            DataColumn2(
                              size: ColumnSize.L,
                              label: Center(
                                child: Text(
                                  "Item Name",
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                              ),
                            ),
                            DataColumn2(
                              size: ColumnSize.S,
                              label: Center(
                                child: Text(
                                  "Price",
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                              ),
                            ),
                            DataColumn2(
                              size: ColumnSize.L,
                              label: Center(
                                child: Text(
                                  "Quantity",
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                              ),
                            ),
                          ],
                          rows: List<DataRow>.generate(
                            data!.length,
                            (index) => DataRow2(
                              selected: avail![index],
                              onSelectChanged: (bool? value) {
                                setState(() {
                                  avail![index] = value!;
                                });
                              },
                              color: MaterialStateProperty.resolveWith<Color?>(
                                (Set<MaterialState> states) {
                                  if (states.contains(MaterialState.selected)) {
                                    return Theme.of(context)
                                        .colorScheme
                                        .primary
                                        .withOpacity(0.08);
                                  }
                                  return null;
                                },
                              ),
                              cells: [
                                DataCell(
                                  Text(
                                    data![index].Juice_Name,
                                  ),
                                ),
                                DataCell(
                                  Center(
                                    child: Text(
                                      data![index].Price,
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Center(
                                    child: IncDecButton(
                                      Qty: qty![index],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          } else if (snapshot.hasError) {
            return Center(
              child: Text(
                'Add Item in Menu.',
                style: TextStyle(
                  fontSize: 18,
                ),
              ),
            );
          }
          return Center(
            child: const CircularProgressIndicator(),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        tooltip: "Proceed to Bill",
        onPressed: () {
          // When I pressed floating button I want only selected items data
        },
        child: Text("ADD"),
      ),
    );
  }
}

This is stream of GetDataPublisher This code get data from firebase.

      class DataStreamPublisher {
          final String dbChild;
          DatabaseReference database = FirebaseDatabase.instance.reference();
          User? curUser = FirebaseAuth.instance.currentUser;
        
          DataStreamPublisher(this.dbChild);
        
          Stream<List<GetData>> getMenuStream() {
            final dataStream =  database.child(curUser!.uid).child(dbChild)
               .orderByChild("Available").equalTo(true).onValue;
            final streamToPublish = dataStream.map((event) {
              final dataMap = Map<String, dynamic>.from(event.snapshot.value);
              final dataList = dataMap.entries.map((e) {
                return GetData.fromRTDB(Map<String, dynamic>.from(e.value));
              }).toList();
              return dataList;
            });
            return streamToPublish;
          }
        }

This is get data class

    class GetData {
          String Juice_Name;
          String Price;
        
          GetData({
            required this.Juice_Name,
            required this.Price,
          });
        
          factory GetData.fromRTDB(Map<String, dynamic> data) {
            return GetData(
              Juice_Name: data['Juice_Name'] ?? 'Enter Juice Name',
              Price: data['Price'] ?? 'Enter Price',
            );
          }
        }

Python dictionary; receive user input; enter error code when out of range

I am making a dictionary! I am trying to get the user to select a number between 1 - 10 to generate the Korean word for it. I am able to get the user input to print out the correct translation but I want my code to tell the user to try again if a number between 1 - 10 is not selected. Heeelp.

#1 is key
#all keys need to be unique
#Hana is value
print ("Welcome to the Korean Converter!")

user = int(input("Enter a number between 1 and 10: "))
        
koreanConversion = {
    1: "Hana",
    2: "Tul",
    3: "Set",
    4: "Net",
    5: "Ta Sut",
    6: "Yuh Sut",
    7: "Il Jop",
    8: "Yu Dulb",
    9: "Ah Hop",
   10: "Yul"

}


print (koreanConversion[user])


#else: 
 #   user = int(input("Please try again: "))
 #if (koreanConversion[user]) != [user]
  #   print("Please try again.")

dplyr median by group

I have this data frame

df1 <- data.frame(
     Type1 = c("A","A","A", "AB", "AB"),
     Type2 = c(1L,2L,2L, 1L, 1L),
     Value = c(1L, 2L, 1L, NA, NA), , Median = c(1L, 1.5, 1.5, NA, NA))

I would like to get median in a new column by Type1 and Type2 to a new variable "AB" without summarise to have a new value in existing column.

 df12 <- data.frame(
    Type1 = c("A","A","A", "AB", "AB"),
    Type2 = c(1L,2L,2L, 1L, 1L),
    Value = c(1L, 2L, 1L, NA, NA), Median = c(1L, 1.5, 1.5, 1L, 1L))

My try

df1 %>% group_by(Type1, Type2) %>% mutate(Median = ifelse(Type1 == "AB" & Type2 == 1, median(Value), Median))

How to Show Profile Picture of User on Change password form (Picture of Logged In user should be show) in HTML/PHP

I'm working on a little project, I've created and linked change password form and used update query, form is working very well, but I want to show user's image on the change password form, Below is my code, when I used session variable and add php code in form, then my already fixed image also become hidden whereas, I don't want to show fixed image I want to show user's image, Please help me to correct it. I used if else and switch statement but only else statement is executing.

<div class="container"> <h1>CHANGE YOUR PASSWORD</h1> <div class="contact-form"> <div class="profile-pic"> <?php if (isset($_SESSION['username'])){ $username = !empty($_SESSION['username']) ? $_SESSION['username'] : false; switch ($username) { case 'admin': case 'Admin': case 'ADMIN': ?> <img src="profile_pics/4.png" alt="User Icon"/> <?php break; case 'muhammad azeem': case 'Muhammad Azeem': case 'MUHAMMAD AZEEM': ?><img src="profile_pics/1.png" alt="User Icon"/> <?php break; case 'muhammad adnan': case 'Muhammad Adnan': case 'MUHAMMAD ADNAN': ?><img src="profile_pics/2.png" alt="User Icon"/> <?php break; case 'saleem raza': case 'Saleem Raza': case 'SALEEM RAZA': ?><img src="profile_pics/3.png" alt="User Icon"/> <?php break; case 'abdul raheem': case 'Abdul Raheem': case 'ABDUL RAHEEM': ?><img src="profile_pics/5.png" alt="User Icon"/> <?php break; } } else{ ?> <img src="images/1.png" alt="User Icon"/> <?php } ?> </div> <div class="signin"> <form action="process_change_password_form.php" method="POST"> <input type="text" name="current_password" class="user" value="Current Password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Current Password';}" id="1" required> <input type="text" name="new_password" class="user" value="New Password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'New Password';}" id="1" required> <input type="text" name="confirm_new_password" class="user" value="Confirm New Password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Confirm Password';}" id="1" required> <input type="submit" value="Change Password" name="submit" /> </form> </div> </div> </div> </body> </html>

Issue running bash script at if statement

I am just getting starting in AppleScript and am testing out an existing script to see if I can get it to run on my computer. The error I get is here:

Expected “,” or “]” but found unknown token.

and it highlights the ~ in my if statement:

path="/Library/Desktop Pictures/Wallpaper-Blue-3D-logolow-2846x1600.jpg"
    
    if [ -d ~/Library/Desktop\ Pictures/ ]
    then
            echo "Desktop Pictures directory already exists"
    else
            mkdir ~/Library/Desktop\ Pictures/
    fi

What am I missing? Thanks!!

How do I use Google Script If Statements?

I am familiar with Excel VBA but am new to Google Script Editing

I am trying to use a simple IF statement to insert a new line above line 2 if cells A2 & B2 are NOT Blank.

  function AddaLine() {
if (B1 == false)
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('2:2').activate();
  spreadsheet.getActiveSheet().insertRowsBefore(spreadsheet.getActiveRange().getRow(), 1);
  spreadsheet.getActiveRange().offset(0, 0, 1, spreadsheet.getActiveRange().getNumColumns()).activate();
  spreadsheet.getRange('A2').activate();
};

where cell B1 contains

=isblank(A2:B2)

or

function AddaLine() {
  if (A2, B2 != null)
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('2:2').activate();
  spreadsheet.getActiveSheet().insertRowsBefore(spreadsheet.getActiveRange().getRow(), 1);
  spreadsheet.getActiveRange().offset(0, 0, 1, spreadsheet.getActiveRange().getNumColumns()).activate();
  spreadsheet.getRange('A2').activate();
};

Every combination I can think of returns errors. Any help would be appreciated.

Is there an easier way to write this IF statement?

I'm very new to VBA and trying to learn as I go along. I'm 100% sure there is an easier way to condense this code rather than typing IF statements for each cell and corresponding cell.

Here is the code I'm using:

        Sub Test()
If Range("B1").Value > 0 Then
    Range("A1").Value = 0
End If

If Range("B2").Value > 0 Then
    Range("A2").Value = 0
End If

If Range("B3").Value > 0 Then
    Range("A3").Value = 0
End If

If Range("B4").Value > 0 Then
    Range("A4").Value = 0
End If

If Range("B5").Value > 0 Then
    Range("A5").Value = 0
End If

If Range("B6").Value > 0 Then
    Range("A6").Value = 0
End If

End Sub

Picture

The range I'm using is A1:A6 then comparing that against values of B1:B6 and saying if B1 > 0 then A1 = 0, then repeat for A2 and B2 and so on..

I know that the solution is probably painfully obvious, but I can't seem to figure out how to do it yet.

Thanks for any help provided!

Is there an easier way to combine several if statements using an array in javascript

I have a form where a user enters their address. This then checks their address against several destinations in the UK to see which city is their nearest.

I want each destination to have different prices, for example London, UK = 50, Birmingham, UK = 200 etc.

I have written a pretty rudimentary if statement which checks the city that is returned and calculates the price. However, I'm wondering if there is a neater solution to this as it feels a bit obtuse:

if(closestCities[0].cityName == "Coventry, UK") {
  travelExpenses = 10;
} else if (closestCities[0].cityName == "London, UK"){
  travelExpenses = 50;
} else if (closestCities[0].cityName == "Margate, UK"){
  travelExpenses = 100;
} else if (closestCities[0].cityName == "Bristol, UK"){
  travelExpenses = 20;
} else if (closestCities[0].cityName == "Tamworth, UK"){
  travelExpenses = 15;
} else if (closestCities[0].cityName == "Birmingham, UK"){
  travelExpenses = 200;
} else {
  travelExpenses = 30;
}

if statements for booking logic

I'm struggling to define a couple of nested if statements for a project I'm working on; a way for employees to book desks in different rooms of an office.

Model relationships:

  • Room hasMany Desks
  • Desk belongsTo Room
  • Booking hasOne Desk (vice-versa)
  • Booking hasOne User (vice-versa)

I want to provide an index of each of the room cards, each with respective clickable desks indexed in a grid within the card. The auth user can click on a desk and confirm thier booking.

There are 4 states that the rendered desk card can have; available to book, disabled due to booking already made by auth user, unavailable having been booked by another user, and booked by auth user.

The bookings table migration looks like this:

Schema::create('bookings', function (Blueprint $table) {
            $table->id();
            $table->foreignId('desk_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('room_id')->constrained()->cascadeOnDelete();
            $table->timestamps();
        });

RoomController

public function index()
        {
            return view('index', [
                'rooms' => Room::with("desks")->get(),
                'desks' => Desk::all(),
                'user' => Auth::user(),
                'bookings' => Booking::all()
            ]);
        }

The index view with the if statements in question is below:

@if ($rooms->count())
    <div class="grid grid-cols-1 gap-6 mt-5 pb-20">
        @foreach ($rooms as $room)
            <div class="bg-white h-auto rounded-xl shadow-inner">
                <div class="mx-3 my-4">
                    <div class="mt-2 text-2xl font-semibold text-gray-800 text-left pl-5">
                        
                    </div>
                    <div class="lg:grid lg:grid-cols-5 gap-5 mt-4">                 
                        @foreach ($desks->where('room_id', $room->id) as $desk)                                       
                            
                        

                          //  @if(desk_id exists in the bookings table)                                
                              //  @if(user_id of said desk belongs to auth user)
                                    <x-grid.desks.my-booking :desk='$desk' :room="$room" :user="$user" />
                                @else    
                                    <x-grid.desks.booked :desk='$desk' :room="$room" :user="$user" />
                                @endif
                            @endif
                            
                          //  @if(desk_id exists in desks table and doesn't exist in Bookings table)
                                   // @if(auth user id exists in bookings)
                                       <x-grid.desks.unavailable :desk='$desk' :room="$room" :user="$user" />
                                    @else
                                        <div x-data="{show: false}">
                                            <x-grid.desks.available :desk='$desk' :room="$room" :user="$user" />
                                        </div>
                                    @endif
                            @endif
                                        
                        @endforeach
                    </div>
                </div>
            </div>
        @endforeach
    </div>
@else
    <p class="text-center text-xl mt-10">No bookings available yet. Please check back later!</p>
@endif

I've previously attempted to write the if statements without any success, so they're written in plain english for now. Much appreciated if someone could lend a hand, thanks.

How to view the contents of a file in python

I am trying to add a new account in my file which already consist of a username and password of other accounts, after doing it I only want to view the new added accounts or contents of the file like this but have certain distances with each other:

No. Account Name Username Password

1 Facebook admin 123admin

2 Google user 123user

Below is my code for adding a new account in my file:

def Add_account():

    account = input("\nEnter the name of the account: ")
    username = input(f"Enter the username of your {account}: ")
    password = input(f"Enter the password of your {account}: ")
    ask = input(f"Do you want to save {account} credentials? [Y|N]: ")

    if new_ask == "Y":
        with open("info.txt", "a") as file:
            file.write("\n" + encrypt(account) + ":" + encrypt(username) + ":" + encrypt(password))
            file.close()
         
Add_account()

How can I view the new accounts only in my file?

check if multiple conditions exist in row in a dataframe

I have a checklist (.csv) and lots of files (.csv). I want to read files if they are in the checklist.

  1. Checklist dataframe has three columns: "Energy": np.int32,"Potential": string ,"Try": np.int32
  2. Files have meaningful names: "Energy_POtential_Try.extension", for instance: "10_MM_20.csv"

so far, I have used isin function of pandas, but it seems to read each column individually. I want my "if" condition to return "True" if specific row has all my intended Energy, Potential, and Try values.

for root, dirs, files in os.walk(CollectionDirectory, topdown=False):
for File in files:
        Energy = int(File.split("_")[-3])
        Potential = File.split("_")[-2]
        Try= int(File.split("_")[-1])
        if checklistDf.isin([Energy,Potential,Try]).any().all():
                          DfNew = pd.read_csv(File)

Selecting the components of a vector inside an if statement inside a for loop

I'm trying to check if the absolute value of each component of the vector differenza inside a for loop is greater than 0.001 by using if statements, but it seems that I'm not selecting a component because I got the error:

Warning in if (abs(differenza[i]) > 0.001) { :
  the condition has length > 1 and only the first element will be used

Which kind of mistake did I make?

lambda = 10
n = 10
p = lambda/n
K = 10
x = 0:K

denbinom = dbinom(x, n, p)
denpois = dpois(x, lambda)

differenza = denbinom - denpois

for (i in differenza) {
  if (abs(differenza[i]) > 0.001) {
    cat("Componente", i > 0.001, "\n")
  }
  if (abs(differenza[i]) <= 0.001) {
    cat("Componente", i, "ok")
  }
}

How do I compare timestamp using windows batch script if statement

am trying to compare timestamp using windows batch script if statement

ie:

var1=31-10-2021 10:20:50.20

var2=30-10-2021 12:10:40.10

am trying to get latest or higher result with if statement

any idea?

How do I associate strings with if conditions in python

  1. var1 = str(input('Choose either A or B'))
  2. var2 = 'A'
  3. if var1 == var2:
  4. print('Hello World') 
    
  5. else:
  6. print('Try something else') 
    

something seems wrong with my if-statement [closed]

I was told to code an if statement with a scanner type but it seems that I didn't got any output

import java.util.Scanner;

public class StillTraining {

    public static void main(String[] args) {
    
        Scanner deg = new Scanner (System.in);
        
        System.out.println("enter your score");
        
        int score = deg.nextInt();
        
        if (score >= 90 && score <= 100 );
                System.out.println("Your score is A");
                
        else if (score >= 80 && score > 90);
                System.out.println("Your score is B");
                
        else if (score >= 70 && score > 80);
                System.out.println("Your score is C");
                
        else if (score >= 60 && score > 70);
                System.out.println("Your score is D");
                
        else
                System.out.println("Your score is F");
        
        
    }

}

How to trigger if-else condition using buttons?

So I've got this homework to check if the score can passed the exam or not below here is my code:

import React, {useState} from 'react';
import {
  Text,
  View,
  Image,
  TextInput,
  Button,
  StyleSheet,
  Alert,
} from 'react-native';
const styles = StyleSheet.create({
  input: {
    height: 40,
    margin: 12,
    borderWidth: 1,
    padding: 10,
  },
});

class ComponentAction {
  static onPressButton() {
    if (setScore < 50) {
      Alert.alert('Sorry! You failed the test');
    } else {
      Alert.alert('Congrats! You passed the test');
    }
  }
}
const AppTextInput = () => {
  const [score, setScore] = useState('');
  return (
    <View>
      <Text>Score</Text>
      <TextInput
        placeholder="Input your score here"
        keyboardType="numeric"
        value={score}
        style={styles.input}
        onChangeText={score => setScore(score)}
      />

      <Button title="Submit" onPress={() => ComponentAction.onPressButton()} />
    </View>
  );
};
export default AppTextInput;

it kept saying they can't find the variables. I'm kinda new to React Native stuff and I really appreaciate if you guys can help me

im new in coding can you pls help me?

Input a 3-digit integer. Print the largest digit in the integer. Use % 10 to get the rightmost digit. For example, if you do 412 % 10, then the result would be the rightmost digit, which is 2. On the other hand, use / 10 to remove the rightmost digit. For example, if you do 412 / 10, then the result would be 41. You'd have to repeat Tip #1 and Tip #2 three times for this problem because the input is a 3-digit integer.

If statement not getting executed even though it is true

this if(line[2] == "Inactive") Statement is not executing.

public void Transaction(int test) throws IOException {
        Scanner reader = new Scanner(new FileReader(bankfile));
        String currentline = "";
        try {
        while((currentline = reader.nextLine())!= null) {
            String line[] = currentline.split(",");
            System.out.println(currentline);
            if(Integer.parseInt(line[0]) == test){
                System.out.println(line[2]);
                if(line[2] == "Inactive") { **This is the Problem**
                    System.out.println("This account is Inactive and cannot perform any transaction.");
                    return;
                }
                else {
                    System.out.println("Hello");
                break;
                }
            }
        }
        }
        catch(NoSuchElementException e) {
            System.out.println("Account Number is not found.");
            return;
        }
//      performTrans();
    }

It is executing the else statement even though line[2] == "Inactive"

Here is the file.

File:
2,2.0,Active
1,393.0,Inactive
3,3.0,Active
4,4.0,Active
5,5.0,Active

I want this code

Transaction(1);

to get an output "This account is Inactive and cannot perform any transaction" because account 1 is Inactive. But it is executing the else statement and not the if statement and so the output will be "Hello"

samedi 30 octobre 2021

Problem with an if statement in a for loop [closed]

I'm having issues with an if statement that is executing a condition that is not true. I'm writing a program that takes a user's input and parses through it ensuring they have only entered 0s and 1s, or rather a binary number. Here is my code:

String binStr;
for (int i=0; i < binStr.length(); i++) {
        
        if (binStr.charAt(i) == '1') {
            
            System.out.println("Heres a one.");
            count = count + 1;
            
        }
        
        if (binStr.charAt(i) == '0') {
            
            System.out.println("Heres a 0");
            count0 = count0 + 1;
        }else{
            System.out.println("You entered an invalid binary number,"
                    + "please re-enter a valid binary number.");
        }

For some reason it keeps stating that I have entered an invalid binary number even when I use only 1s or 0s. Can anyone help me figure out why this is happening. Thank you.

How can I make the following variable on SPSS?

I have a variable with values from -100 to 100. I want a new variable where -14 to 14 will be 1 and all others will be 0.

I have this so far but I get an error.

DO IF (Rad_Start_Minus_Chemo_start GT -14).
Compute         NACRT =1.
ELSE IF (Rad_Start_Minus_Chemo_start LT 14).
COMPUTE        NACRT=1
ELSE IF (Rad_Start_Minus_Chemo_start GT 14).
Compute         NACRT=0.
ELSE IF (Rad_Start_Minus_Chemo_start LT -14).
Compute         NACRT=0.
END IF.

function is not acting properly(very new)

I just started python and some help would be greatly appreciated. I have 2 issues with execution. when I run the code as posted below, its not acknowledging that the parameters for the astrick being used it 5-25, then I removed the name inside of the parenthasies for the function, the code then accepted the parameters but would not generate the astrick.

import time, sys

def runZigzag(numOfAsterisk): indent = 0 indentIncreasing = True

try: while True: print(' ' * indent, end='') print('*' * numOfAsterisk) time.sleep(0.1)

        if indentIncreasing:
            indent = indent + 1
            if indent == 20:
                indentIncreasing = False

        else:
            indent = indent - 1
            if indent == 0:
                indentIncreasing = True
except KeyboardInterrupt:
    Sys.exit()

while True:

try:
     numOfAsterisk = int(input('Enter an integer between 5 and 25\n'))
      
     
except ValueError:
     print('You must enter an integer\n')
except:
    if: 4 <= numOfAsterisk:
        print('The entered number is too low\n')
    if 26 >= numOfAsterisk:
        print('The entered number is too high')
else:
    runZigzag(numOfAsterisk) 

why would setting redirect in if and else condition wont work in php?

Am baffled by a simple code even as experienced developer. Am trying to redirect a user depending on two condition. I have a variable called $isMobile which is boolean. Now below code cannot work if i add redirect but removing redirect header, it works

This does not work

if($isMobile){
    header('Location:http://localhost/myproject/mobile/login/');
    exit();
}
else{
    header('Location:http://localhost/myproject/pc/login/');
    exit();
}
//Error: too many redirects as if both conditions are true. Weird right?

This works

if($isMobile){
    echo 'redirect to mobile folder';
}
else{
    echo 'redirect to desktop folder';
}

What makes everything stop after adding both header redirects? I need to redirect users depending on their devices. Am so stuck here guys.

Custom Number Format for Thousands, Millions, Billions, AND Trillions

I've looked everywhere and haven't found any solutions to getting numbers in the "Trillions" to format with a trailing "T".

Here is the custom number format I'm currently using: [<999950]$0.00,"K";[<999950000]$0.00,,"M";$0.00,,,"B"

Which displays these numbers as so:

Trillions

Is Google Sheets also able to make numbers in the Trillions format as $1.00T?

Thanks!

Why does this if statement not intialize or update my variable?

I'm a bit confused about declaring variables and then initializing/assigning those variables in a code block such as an if statement, then using that variable in the rest of my code.

The following example fails to assign the result of num1 + num2 to "result" in the if statement if "result" is declared and not initialized beforehand.

        int num1 = 1;
        int num2 = 2;
        int result; //declared

        if (num1 == 1)
        {
            result = num1 + num2;
        }
        Console.WriteLine(result); //Use of unassigned local variable "result"

However, declaring and initializing "result" beforehand successfully updates the "result" value in the if statement.

        int num1 = 1;
        int num2 = 2;
        int result = 0; //declared and initialized

        if (num1 == 1)
        {
            result = num1 + num2;
        }
        Console.WriteLine(result); //3

Moreover, if I change the condition in the if statement simply to "true" instead of "num1 == 1", then both of the previous examples work perfectly.

Could someone kindly explain this to me?

how to check for positive multiples of 2 using modulus operator in an if loop

I was trying to use the mod % operator in C++ but it shows the error Expression is not assignable

int i = 0;
    cin>>i;
//    for (i; i < 25; i++) {
        if (i < 25 && i % 2 = 0) {
            cout<<"test"<<i;
        } else {
            cout<<"test2"<<i;
        }
    }
    return 0;
}

A simple calculator using C about conversion of Fahrenheit to Celsius, and vice versa

Good day! I tried to make a simple calculator using C for my first project about conversion between Fahrenheit to Celsius, and vice versa. But it's not working, can someone tell me what I miss?

Here's my code:

#include <stdio.h>

int main()
{
double temp, fahrenheit, celsius;
char answer[2];

printf("Type 'CF' if you want to convert from celsius to fahrenheit, and 'FC' if you want to convert from fahrenheit to celcius: ");
fgets(answer, 2, stdin);

fahrenheit = (temp * 1.8) + 32;
celsius = (temp - 32) * 0.5556;
if(answer == "CF"){
    printf("Type the temperature here: ");
    scanf("%lf", &temp);
    printf("Answer: %f", fahrenheit);
}
else if(answer == "FC"){
    printf("Type the temperature here: ");
    scanf("%lf", &temp);
    printf("Answer: %f", celsius);
}
return 0;

}

calculator

vendredi 29 octobre 2021

c++ Is there a way to rewrite this to be a more effective?

Just trying to write this in different ways

for (int i = 0; i < HOTPLATE_ROWS - 1; ++i) {
    for (int j = 0; j < HOTPLATE_COLUMNS - 1; ++j) {
        if((i >= 1 && i <= HOTPLATE_ROWS - 1) && (j > 0 && j < HOTPLATE_COLUMNS - 1)){
            finalTemperature[i][j] = (startTemperature[i - 1][j] + startTemperature[i][j 
            - 1]);
            finalTemperature[i][j] = (finalTemperature[i][j] + startTemperature[i][j + 1] 
            + startTemperature[i + 1][j]);
            finalArray[i][j] = finalTemperature[i][j] / TOUCHING_TEMPS;
            sumOfArray = finalArray[i][j];
     }
  }

}

How to reduce cognitive complex in javascript event handler?

I have some element event handler uses if statement inside, why sonar complains this if statement causes cognitive complexity? Is there a way I can avoid this or improve this?

const handleOnBlur = () => {
    if (isEditMode) {
        setMyStuff(false);
    }
};

This is counted as code smell +2, including 1 for nesting. Why if statement causes code smell especially I don't have very complex if, else or nested if statements.

Thank you!

Add values into a data frame under conditions of other data frame

This may be a long shot, but I am trying to add values from df1 into df2 under certain conditions. Let me give examples of my data frames:

df1
Date   Time  TimeSlot          Behavior  BehaviorTime
10.30  1030  Morning Visitors  Startle   142
10.30  1030  Morning Visitors  Retreat   155
10.30  1030  Morning Visitors  Chase     187
10.31  830   Keeper Feeding    Startle   133
10.31  830   Keeper Feeding    Chase     139

df2
SessionStart       ScanTime  Val1  Val2    Temp  Weather
10/30/21 10:33:42  10:34:42  A     60-70   68    Partly Cloudy
10/30/21 10:33:42  10:35:42  B     70-80   68    Partly Cloudy
10/30/21 10:33:42  10:36:42  A     70-80   68    Partly Cloudy
10/30/21 10:33:42  10:37:42  B     70-80   68    Partly Cloudy
10/30/21 10:33:42  10:38:42  C     70-80   68    Partly Cloudy
10/31/21 08:35:23  08:36:23  A     40-50   77    Sunny
10/31/21 08:35:23  08:37:23  C     90-100  77    Sunny
10/31/21 08:35:23  08:38:23  C     90-100  77    Sunny
10/31/21 08:35:23  08:39:23  C     90-100  77    Sunny
10/31/21 08:35:23  08:40:23  C     90-100  77    Sunny

To explain a bit further, df1 is a data frame that is recording behaviors of an animal. The session started at approximately 10:30 AM (1030) on 10/30/21 (10.30). Each time a behavior occurred, the observer would record it. The "BehaviorTime" column is when the observer recorded the behavior (in seconds). So, the first observation of df1 was recorded 142 seconds into the observation session.

The second data frame, df2, is recording the environment of the observation session. Each session was about 30 minutes, and certain values were recorded at each minute (30 observations per session). Some values change, some values stay the same.

I would like to find a way to integrate the "Behavior" column from df1 into df2 during the time that it occurs. The time in df1 is approximate, while the time in df2 is accurate. Like I said, the "BehaviorTime" column represents the number of seconds into the session. So, 142 seconds (first observation in df1) after 10:33:42 (observation start time from df2) would be 10:36:24, which would mean the “Startle” value would be included in the df2 row with 10:36:42 because that time is closest to the calculated time. Essentially, it would look like this:

df3
SessionStart       ScanTime  Val1  Val2    Temp  Weather        Behavior
10/30/21 10:33:42  10:34:42  A     60-70   68    Partly Cloudy
10/30/21 10:33:42  10:35:42  B     70-80   68    Partly Cloudy
10/30/21 10:33:42  10:36:42  A     70-80   68    Partly Cloudy  Startle
10/30/21 10:33:42  10:36:42  A     70-80   68    Partly Cloudy  Retreat
10/30/21 10:33:42  10:37:42  B     70-80   68    Partly Cloudy  Chase
10/30/21 10:33:42  10:38:42  C     70-80   68    Partly Cloudy
10/31/21 08:35:23  08:36:23  A     40-50   77    Sunny
10/31/21 08:35:23  08:37:23  C     90-100  77    Sunny          Startle
10/31/21 08:35:23  08:37:23  C     90-100  77    Sunny          Chase
10/31/21 08:35:23  08:38:23  C     90-100  77    Sunny
10/31/21 08:35:23  08:39:23  C     90-100  77    Sunny
10/31/21 08:35:23  08:40:23  C     90-100  77    Sunny

I really hope this makes sense. I have tried different functions in dplyr, but I honestly don’t even know where to start. Any help is appreciated!

Using C language [closed]

  1. Write a program that determines whether or not Anna and Bob were at the restaurant at the same time. Ask the user when Anna and Bob arrived at and left the restaurant, respectively. (The user should answer in number of minutes after midnight, and assume that both arrived and left on the same day.) Determine whether or not Anna and Bob were at the restaurant at the same time, and if so, for how many minutes they overlapped. For example, if Anna arrived at 720 minutes after midnight and left 800 minutes after midnight and Bob arrived at 600 minutes after midnight and left 740 minutes after midnight, they were at the restaurant together for 20 minutes. (Note: If Bob leaves at the same time Anna arrives, then they were not at the restaurant at the same time.)

Coding convention for If statement and returning

I'm not sure if I'm overthinking this but should I do this

if (!searchList.isEmpty()) {
    String search = searchList.get(0).getText();
    return List.of(search.split("\n"));
} else {
    return null;
}

or should I do this

if (!searchList.isEmpty()) {
    String search = searchList.get(0).getText();
    return List.of(search.split("\n"));
}
return null;
        

print statement ignored when else if statement is true

I'm attempting to write an error statement to tell the user that the "Player is not in roster". I'm using an if and else-if statement but when the else-if statement is true the print gets ignored and loops back to my defined menu.

//case r allows for a player to be replaced
case 'r':
    printf("Enter a jersey number:\n");
    int replace;
    scanf("%d", &replace);
    if (replace == jerseyNumber) { 
        for (int i = 0; i < numPlayers; ++i) {
            //if the user input matches a jersey in the array the user will input a new jersey number and rating
            printf("Enter a new jersey number:\n");
            scanf("%d", &jerseyNumber[i]);
            printf("Enter a rating for the new player:\n");
            scanf("%d", &playerRating[i]);
        }
    }
    else if (replace != jerseyNumber) {
        printf("Player not in roster.");
    }
    break;

If statement comparing two array values not completing when it should be. (JavaScript)

I have an array that i have made have two of the same value, i have made a function to check the array for duplicates but for some reason it never goes into the if statement. ( if(array[i] == array[j]) ).

when i is 0 and j is 1 they should be matching.

let sessions = [
    {"title": "Lecture", "sessionTime": new Date(2021, 8, 28, 9), "staff": "example"},
    {"title": "fake", "sessionTime": new Date(2021, 8, 28, 9), "staff": "example"},
    {"title": "Lab 1", "sessionTime": new Date(2021, 8, 28, 14), "staff": "example"},
    {"title": "Lab 2", "sessionTime": new Date(2021, 9, 1, 11), "staff": "example"}
];

errorCheck1 = function(sessions) {
    for (let i = 0; i < sessions.length; i++) {
        for (let j = 0; j < sessions.length; j++) {
            if (i != j) {
                if (sessions[i].sessionTime == sessions[j].sessionTime) {
                    $("#errors").append("<li>" + sessions[i].title + " clashes with " + sessions[j].title +"</li>");
                }
            }
        }
    }
}

Trying to explain a a java nested loop which checks for a network connection

I'm trying to do a written report on some code and I found one on youtube. However I don't understand how this loop works. I understand that it must return a boolean value which then goes into another method but if someone could breakdown what is happening it would be greatly appreciated.

public class Loop {
    public static boolean isConnectedToInternet(Context context){

        ConnectivityManager connectivityManager = (ConnectivityManager)
                context.getSystemService(context.CONNECTIVITY_SERVICE);

        if (connectivityManager!=null){
            NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
            if (info!=null){
                for (int i=0;i<info.length;i++){
                    if (info[i].getState() == NetworkInfo.State.CONNECTED)
                        return true;
                }
            }
        }
        return false;
    }
}

Collect External Output (echo) and Save as a Variable for Testing

I have a command that should fail and output a specific echo.

IF the user submits:

./submit_script.sh path/1/to/file1 path/2/to/file2 --bat

THEN

  1. The script should fail
  2. Echo "Unrecognized argument. Possible arguments: cat, dog, human".

I am trying to save this echo in a variable in order to run a simple test case. Basically: WHEN the user runs the script containing the test case (see my strategies below)

./test_script.sh

THEN they receive an echo back stating: "Unrecognized argument test case: pass"

My strategies (I've tried these and every small variation I can think of):

1) Input: test_script.sh contains "echo" when saving the output of the submit_script.sh file into a variable.

Output: nothing is echoed when ./test_script.sh is run

bat_input=$(echo ./submit_script.sh path/1/to/file1 path/2/to/file2 --bat)   

if [[ "$bat_input" =~ "Unrecognized argument. Possible arguments: cat, dog, human" ]]; then                                         
    echo "Unrecognized argument test case: pass"                    
fi

2) Input: test_script.sh does not include echo when saving the output of the submit_script.sh file into a variable

Output: Echo "Unrecognized argument. Possible arguments: cat, dog, human" (not the right echo, expecting "Unrecognized argument test case: pass")

bat_input=$(./submit_script.sh path/1/to/file1 path/2/to/file2 --bat)   

if [[ "$bat_input" =~ "Unrecognized argument. Possible arguments: cat, dog, human" ]]; then                                         
    echo "Unrecognized argument test case: pass"                    
fi

3) Input: test_script.sh includes ">/dev/null 2>&1" when saving the output of the submit_script.sh file into a variable

Output: nothing is echoed when ./test_script.sh is run

bat_input=$(./submit_script.sh path/1/to/file1 path/2/to/file2 --bat >/dev/null 2>&1)  

if [[ "$bat_input" =~ "Unrecognized argument. Possible arguments: cat, dog, human" ]]; then                                         
    echo "Unrecognized argument test case: pass"                    
fi

4) Input: test_script.sh removes the quotations around the bat_input variable in the if statement

Output: Echo "Unrecognized argument. Possible arguments: cat, dog, human" (not the right echo, expecting "Unrecognized argument test case: pass")

bat_input=$(./submit_script.sh path/1/to/file1 path/2/to/file2 --bat)   

if [[ $bat_input =~ "Unrecognized argument. Possible arguments: cat, dog, human" ]]; then                                         
    echo "Unrecognized argument test case: pass"                    
fi

5) *Input: test_script.sh adds 's to the regex command in the if statement

Output: Echo "Unrecognized argument. Possible arguments: cat, dog, human" (not the right echo, expecting "Unrecognized argument test case: pass")

bat_input=$(./submit_script.sh path/1/to/file1 path/2/to/file2 --bat)   

if [[ "$bat_input" =~ *"Unrecognized argument. Possible arguments: cat, dog, human"* ]]; then                                         
    echo "Unrecognized argument test case: pass"                    
fi

In all of these cases, there is no output aside from the "Unrecognized argument. Possible arguments: cat, dog, human" echo, which I would ideally like to suppress. I don't understand why these if statements aren't triggering an echo stating ""Unrecognized argument test case: pass". Ideas? Let me know if I need to make any clarifications.

Is there a way to Write a Condition for When the User Does not Enter in an Input? [closed]

Basically in my program I'm trying to make a condition for when the user does not enter in a certain number with Input.equals.

Something like:

if(Input.equals(!== 3) {
 System.out.println("Something happens.");
}

How do I go about doing that?

Is anyone able to clean up this massive nested if statement?

I am looking to see if anyone is able to condense this code block and make it cleaner. There are multiple sheet links: 'Main Page' refers to the main page where you would go to see the steps for the worksheet and select what group of data you are working on out of three options. 'Main Page'!$BA$10 The rest of the code is basically just criteria and it looks at all possible combinations.


    =IFERROR(
    IF(('Main Page'!$BA$10=1),"",
    
    IF(AND(I472>=0,(M472+O472=0),I472<>"",'Main Page'!$BA$10=6),"",
    IF(AND(I472<0,I472<>"",'Main Page'!$BA$10=6),"Move "&TEXT(I472*-1,"#")&" unit(s) from FRZ_NET to FG",
    IF(AND(I472>0,I472<=O472,I472<>"",'Main Page'!$BA$10=6),"Move "&TEXT(IF(I472<=O472,I472,O472),"#")&" unit(s) from FG to FRZ_NET",
    IF(AND(I472>0,O472<=(1-1),M472>0,I472<>"",'Main Page'!$BA$10=6),"Move "&TEXT(IF(I472<=M472,I472,M472),"#")&" unit(s) from BLOCK_BIN to FRZ_NET",
    IF(AND(I472>0,I472<=O472,O472>0,M472=(1-1),I472<>"",'Main Page'!$BA$10=6),"Move "&TEXT(IF(I472<=O472,I472,O472),"#")&" unit(s) from FG to FRZ_NET",
    IF(AND(I472>0,I472>O472,O472>0,M472<=(1-1),I472<>"",'Main Page'!$BA$10=6),"Move "&TEXT(IF(I472>O472,O472,I472),"#")&" unit(s) from FG to FRZ_NET",
    IF(AND(I472>0,I472<=O472,O472>0,M472>0,I472<>"",'Main Page'!$BA$10=6),"Move "&TEXT(IF(I472<=O472,I472,O472),"#")&" unit(s) from FG & "&TEXT(IF(AND(I472>M472,M472>0),IF(I472-O472>=M472,M472,I472-O472)),"#")&" unit(s) from BLOCK_BIN to FRZ_NET",
    IF(AND(I472>0,I472>O472,O472>0,M472>0,I472<>"",'Main Page'!$BA$10=6),"Move "&TEXT(IF(I472>O472,O472,I472),"#")&" unit(s) from FG & "&TEXT(IF(AND(I472>O472,M472>0),IF(I472-O472>M472,M472,I472-O472)),"#")&" unit(s) from BLOCK_BIN to FRZ_NET",
    
    IF(AND(I472>=0,(M472+O472=0),I472<>"",'Main Page'!$BA$10=7),"",
    IF(AND(I472<0,I472<>"",'Main Page'!$BA$10=7),"Move "&TEXT(I472*-1,"#")&" unit(s) from FRZ_NONNET to FG",
    IF(AND(I472>0,I472<=O472,I472<>"",'Main Page'!$BA$10=7),"Move "&TEXT(IF(I472<=O472,I472,O472),"#")&" unit(s) from FG to FRZ_NONNET",IF(AND(I472>0,O472<=(1-1),M472>0,I472<>"",'Main Page'!$BA$10=7),"Move "&TEXT(IF(I472<=M472,I472,M472),"#")&" unit(s) from BLOCK_BIN to FRZ_NONNET",
    IF(AND(I472>0,I472<=O472,O472>0,M472=(1-1),I472<>"",'Main Page'!$BA$10=7),"Move "&TEXT(IF(I472<=O472,I472,O472),"#")&" unit(s) from FG to FRZ_NONNET",
    IF(AND(I472>0,I472>O472,O472>0,M472<=(1-1),I472<>"",'Main Page'!$BA$10=7),"Move "&TEXT(IF(I472>O472,O472,I472),"#")&" unit(s) from FG to FRZ_NONNET",
    IF(AND(I472>0,I472<=O472,O472>0,M472>0,I472<>"",'Main Page'!$BA$10=7),"Move "&TEXT(IF(I472<=O472,I472,O472),"#")&" unit(s) from FG & "&TEXT(IF(AND(I472>M472,M472>0),IF(I472-O472>=M472,M472,I472-O472)),"#")&" unit(s) from BLOCK_BIN to FRZ_NONNET",
    IF(AND(I472>0,I472>O472,O472>0,M472>0,I472<>"",'Main Page'!$BA$10=7),"Move "&TEXT(IF(I472>O472,O472,I472),"#")&" unit(s) from FG & "&TEXT(IF(AND(I472>O472,M472>0),IF(I472-O472>M472,M472,I472-O472)),"#")&" unit(s) from BLOCK_BIN to FRZ_NONNET",
    
    IF(AND(I472>0,M472<=(1-1),N472<=(1-1),I472<>"",'Main Page'!BA$10=2),"",
    IF(AND(I472>0,M472<=(1-1),N472<=(1-1),O472<=(1-1),I472<>"",'Main Page'!BA$10=2),"",
    IF(AND(I472<=(1-1),M472<=(1-1),N472<=(1-1),O472<=(1-1),I472<>"",'Main Page'!BA$10=2),"",
    IF(AND(I472>M472,M472>0,N472<=(1-1),I472<>"",'Main Page'!$BA$10=2),"Move "&TEXT(M472,"#")&" unit(s) from BLOCK_BIN to FG",
    IF(AND(I472>N472,N472>0,M472<=(1-1),I472<>"",'Main Page'!$BA$10=2),"Move "&TEXT(N472,"#")&" unit(s) from SCRAP to FG",
    IF(AND(I472>0,I472<=M472,I472<>"",'Main Page'!$BA$10=2),"Move "&TEXT(IF(I472<=M472,I472,M472),"#")&" unit(s) from BLOCK_BIN to FG",
    IF(AND(I472>0,I472<=N472,I472<>"",'Main Page'!$BA$10=2),"Move "&TEXT(IF(I472<=N472,I472,N472),"#")&" unit(s) from SCRAP to FG",
    IF(AND(I472>0,I472<=M472+N472,I472<>"",'Main Page'!$BA$10=2),"Move "&TEXT(IF(I472<M472,I472,M472),"#")&" unit(s) from BLOCK_BIN & "&TEXT(IF(AND(I472>M472,N472>0),IF(I472-M472=N472,N472,I472-M472)),"#")&" unit(s) from SCRAP to FG",
    IF(AND(I472>0,I472>M472+N472,I472<>"",'Main Page'!$BA$10=2),"Move "&TEXT(IF(I472>M472,M472,I472),"#")&" unit(s) from BLOCK_BIN & "&TEXT(IF(I472>N472,N472,I472-M472-N472),"#")&" unit(s) from SCRAP to FG",
    "")))))))))))))))))))))))))),"")

It renders something like this:

th {
  font-weight: bold;
}

td {
  text-align: center;
}
<table>
 <tr>
  <th>H472</td>
  <th>L472</td>
  <th>M472</td>
  <th>N472</td>
 </tr>
 <tr>
  <td>200</td>
  <td>Move 100 unit(s) from BLOCK_BIN & 99 unit(s) from SCRAP to FG</td>
  <td>100</td>
  <td>99</td>
 </tr>
</table>

javascript finding word in array

I don't see my mistake here. I want to check if one of the words (Day, Days, Hour, Hours) is included in an array of strings.

        let cardAuctionRemainingTimeString = document.querySelectorAll('.time');
        let arrayCardAuctionTimeRemaining = [];
        for (let times = 0; times < cardAuctionRemainingTimeString.length; times++) {
            let time = cardAuctionRemainingTimeString[times].textContent;
            arrayCardAuctionTimeRemaining.push(time);
        }
        await sleep(150);
        if (arrayCardAuctionTimeRemaining.includes('Hour')) {
            isActive = false;
            console.log('Above one hour');
        } else if (arrayCardAuctionTimeRemaining.includes('Hours')) {
            isActive = false;
            console.log('Above one hour');
        } else if (arrayCardAuctionTimeRemaining.includes('Day')) {
            isActive = false;
            console.log('Above one hour');
        } else if (arrayCardAuctionTimeRemaining.includes('Days')) {
            isActive = false;
            console.log('Above one hour');
        } else {
            console.log('under 1 hour');
        }

I am iterating over a few pages and push time information which is added as strings, into the array arrayCardAuctionTimeRemaining . The array can contain some strings like this: ["1 Hour", "2 Days", "2 Hours"].

I want to stop iterating if the time left is more than 59 minutes basically. But for some reason, it's not working. The code is always going into the else also if one of the words is included.

The HMLT is within a user-only section. But I upload a screen if u wish: enter image description here

How to use data.table fifelse function correctly in R?

I have the following dataset that I am working with

dt <- data.table(RequestTime = c("2011-01-01 07:00:42","2011-01-02 05:00:47","2011-01-03 07:05:02","2011-01-04 04:00:42","2011-01-05 02:00:11"), ExportTime = c("2011-01-01 07:00:50","2011-01-05 05:00:52","2011-01-01 07:06:33","2011-03-04 04:00:51","2011-01-06 02:00:22"))

Since I am working with dates, converted both columns to the correct format using:

dt$RequestTime <- as.POSIXct(dt$RequestTime)
dt$ExportTime <- as.POSIXct(dt$ExportTime)

I am trying to use ifelse conditional statement to update the value of ExportTime based on the condition if the difference between the start date and the RequestTime is less than 86400 secs (24 hrs) then I keep ExportTime the same, but if the difference is greater than 86400 seconds, then the 2nd condition applies. Here is how I go about it.

x <- dt$RequestTime
y <- dt$ExportTime
start_date <- as.Date("2011-01-01")

dt$ExportTime <- fifelse((difftime(start_date, x, units = "secs") < 86400), y, 
    y - (difftime(start_date, x, units = "secs")))

So in this case, only the 1 out of the 5 observations should remain the same. But when I run this, I am seeing that all the observations stay the same. Any help would be appreciated)

React display condition

I'm trying to display a message fetched from an API, but sometimes it's Message Packs I get, kind of like this:

Image Image

In first image, we can see "isPack" on False and i have "message" (without "s") In second image, we have "isPack" on True and i have "messages", is an array with other messages. I can stock all data and display "current_data.message" but i cant display "current_data.messages" because is an array. And .map() doesnt work (he display me : [object Object]1[object Object]1[object Object]1)

My component :

import React, { useState, useEffect, ChangeEvent } from "react";
import TutorialDataService from "../services/TutorialService";
import { Link } from "react-router-dom";
import ITutorialData from "../types/Tutorial";
import { Form, Tabs, Tab } from "react-bootstrap";
import IconLoupe from "../assets/IconLoupe.png";

const TutorialsList: React.FC = () => {
  const [tutorials, setTutorials] = useState<Array<ITutorialData>>([]);
  const [currentTutorial, setCurrentTutorial] = useState<ITutorialData | null>(
    null
  );
  const [currentIndex, setCurrentIndex] = useState<number>(-1);
  const [searchTitle, setSearchTitle] = useState<string>("");

  useEffect(() => {
    retrieveTutorials();
  }, []);

  const onChangeSearchTitle = (e: ChangeEvent<HTMLInputElement>) => {
    const searchTitle = e.target.value;
    setSearchTitle(searchTitle);
  };

  const retrieveTutorials = () => {
    TutorialDataService.getAll()
      .then((response: any) => {
        setTutorials(response.data.data.favourite_conseils);
        console.log(response.data.data.favourite_conseils);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const refreshList = () => {
    retrieveTutorials();
    setCurrentTutorial(null);
    setCurrentIndex(-1);
  };

  const setActiveTutorial = (tutorial: ITutorialData, index: number) => {
    setCurrentTutorial(tutorial);
    setCurrentIndex(index);
  };

  return (
    <div className="list row">
      <span className="font-link-bold" style=>
        <span className="font-link-blue-bold">Mes</span> Conseils
      </span>
      <br />
      <br />
      <span
        className="font-link"
        style=
      >
        Saisir vos mots-clés ou coller un texte :
      </span>
      <br />
      <br />
      <div className="col-md-8">
        <div className="input-group mb-3">
          <form action="/" method="GET" className="form">
            <input
              type="search"
              placeholder="Search"
              className="search-field"
            />
            <button type="submit" className="search-button">
              <img src={IconLoupe} alt="" />
            </button>
          </form>
        </div>
      </div>

      <div className="col-md-12">
        <Tabs
          defaultActiveKey="recents"
          id="uncontrolled-tab-example"
          className="mb-3 background-tabs"
        >
          <Tab eventKey="recents" title="Récents (7)">
            <div className="col-md-12">
              <ul className="list-group">
                {tutorials &&
                  tutorials.map((tutorial, index) => (
                    <li
                      className={
                        "conseil-card" +
                        (index === currentIndex ? "active" : "")
                      }
                      onClick={() => setActiveTutorial(tutorial, index)}
                      key={index}
                    >
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="16"
                        height="16"
                        fill="currentColor"
                        className="bi bi-grip-vertical"
                        viewBox="0 0 16 16"
                      >
                        <path d="M7 2a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zM7 5a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zM7 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm-3 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm-3 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0z" />
                      </svg>
                      <p>{tutorial.isPack ? "test" : "{tutorial.message}"}</p>
                      <div className="conseil-card-title">
                        Titre : {tutorial.title} - {tutorial.isPack ? "Pack oui" : "Pack non"}
                      </div>
                    </li>
                  ))}
              </ul>

              <button
                className="m-3 btn btn-sm btn-secondary"
                onClick={removeAllTutorials}
              >
                Modifier (Soon)
              </button>
            </div>
            <div className="col-md-12">
              {currentTutorial ? (
                <div>
                  <h4>Conseil</h4>
                  <div>
                    <label>
                      <strong>Titre:</strong>
                    </label>{" "}
                    {currentTutorial.title}
                  </div>
                  <div>
                    <label>
                      <strong>Message:</strong>
                    </label>{" "}
                      //HERE I NEED DISPLAY message or messages
                    {currentTutorial.messages.map((number) => number + 1)}
                  </div>
                  <div></div>

                  <Link
                    to={"/tutorials/" + currentTutorial.id}
                    className="badge badge-warning"
                  >
                    Edit
                  </Link>
                </div>
              ) : (
                <div>
                  <br />
                  <p>Veuillez cliquer sur un conseil...</p>
                </div>
              )}
            </div>
          </Tab>
          <Tab eventKey="favourite" title="Mes conseils favoris (3)">
            test2
          </Tab>
          <Tab eventKey="searched" title="« Rhinite allergique » (17)" disabled>
            test3
          </Tab>
        </Tabs>
      </div>
    </div>
  );
};

export default TutorialsList;

Thanks you for you're helping !

Check for Null values without IF statements

I have the following method that gets multiple optional values as parameters.

@GetMapping(path = "/search", produces = {MediaType.APPLICATION_JSON_VALUE , MediaType.APPLICATION_XML_VALUE})
public ResponseEntity<String> getCategoriesByExample(
        @RequestParam(required = false) String id,
        @RequestParam(required = false) String name,
...
){

The problem is, since all the parameters are optional, when I assign them in a object I need to check all of them for nullability in such a way that multiple IF's are necessary. If I don't, the program throws an error for assigning the variable a null value.

Category cat = new Category();
    
    if (id!=null) 
        cat.setId(UUID.fromString(id));
    
    if (name!=null) 
        cat.setName(name);
...

So is there a way for me to to check all of then without using the if statement?

use function instead of multiple if else

this is my code and I want to break it to multiple function(clean code!), for these two section (status===edited) and (status === added) or two different function for (dataindex===ReportEffectiveDate) and (dataindex=== EffectiveDate).how can I put these if else statement in a separate function then I use this function for each status. totally I want to know which way is better : I use multiple if and else if or use multiple function for this code? thanks for your help!

function handleTableRowChange(record: LoadModel, oldValue: any, newValue: any, dataIndex: string) {
  console.log(record, oldValue, newValue, dataIndex);
  const status: RowStatus = tableStore.getRowStatus(record);
  if (!!newValue) {
    if (dataIndex === 'ReportEffectiveDate') {
      if (record.EffectiveDate > record.ReportEffectiveDate) {
        record.EffectiveDate = null;
        tableStore.update(record);
        Modal.error({
          content: translate('ReportEffectiveDatecantbelessthanoldeffectivedate'),
        });
        console.log('error');
      } else if (record.EffectiveDate == record.ReportEffectiveDate) {
        record.ReportEffectiveDate = null;
        tableStore.update(record);
      }
    }
    if (dataIndex === 'EffectiveDate') {
      if (status === 'added') {
        const isValid: boolean = checkIsEffectiveDateValid(record);
        if (!isValid) {
          record.EffectiveDate = null;
          tableStore.update(record);
        }
      } else if (status === 'edited') {
        const maxEffectiveDateRecord: LoadModel = getMaxEffectiveDateRecord(record);
        if (record.EffectiveDate > maxEffectiveDateRecord.EffectiveDate) {
          if (newValue < maxEffectiveDateRecord.EffectiveDate) {
            record.EffectiveDate = oldValue;
            tableStore.update(record);
          }
        }
      }
    }
  }
}

How to check whether number is divisible by another number WITHOUT conditional check (if, ternary, etc.) in C#

I have a number, for example, X. I want to check if it is divisible by 3. If it is divisible by 3, I need to return true, otherwise false. But I am not allowed to use if condition, ternary operator, etc. Any suggestions?

IF Sentance in MySQL trigger

I am building an automatic ranking on a game server and i have to do this by manipulating the MySQL database, this is not a strong knowledge area for me so ive tried to be a bit hacky with this. i need to use the trigger function of SQL db.

CREATE TRIGGER `ranking_up` AFTER UPDATE ON `highscore` FOR EACH ROW

BEGIN

IF NEW.score >= '10' and <= '100' THEN
    UPDATE department_members
    SET rankID=1 WHERE userID = NEW.userID;
END IF;
IF NEW.score >= '100' and <= '300' THEN
    UPDATE department_members
    SET rankID=2 WHERE userID = NEW.userID;
END IF;
IF NEW.score >= '300' THEN
    UPDATE department_members
    SET rankID=3 WHERE userID = NEW.userID;
END IF;
END

I get the standard MySQL #1064 and i have tried to talk to my rubber duck... does not work it makes perfect sense for me but apparently does not work.

I am looking for the answer ofc BUT i also want to learn on my mistake here, what am i doing wrong ?

Unable to detect the roles assigned to a user using simple if-else loop in SailPoint IIQ

I am trying to write a workflow where if the user is an Employee and has Role 1 assigned, the loop will return true. Also if the User is a Contingent Worker and has the Role 2 assigned, the loop will return true. Else the loop will return "Role not provisioned". The user is an Employee and is assigned the Role 1, but still the loop return "Role not provisioned".

The flow is entering the main ELSE loop, where it is able to read the empType, but not able to read the "assignedRoles.contains()". Here is the code

How can I have conditional buttons without repeating code. React

I am trying to make it so the buttons are only visible in my create page. I have figured out how to do this although in such a way that code is repeated

if (mode != "view") {

  return (
    <>
      <section
        className={`col-md-${sectionInputArray.width} justify-content border-end mt-2 mb-2`}
      >
        <h4 className="border-bottom">{`${sectionInputArray.name}`} </h4>
        <div className="col-12"></div>
        {sectionInputArray.contents.map((input, i) => (
          <NestedDynamicInputCreation
            singleInput={input}
            formData={formData}
            setFormData={setFormData}
            options={options}
            mode={mode}
            staticVars={staticVars}
            SetStaticVars={SetStaticVars}
            i={i}
            idx={idx}
            arrayLength={arrayLength}
            sectionUID={sectionInputArray.UID}
          />
        ))} 

        {/* Button to add new field */}
        <button
          id ="TestButton1"
          className="btn btn-primary bt-btn m-3"
          type="button"
          onClick={() => {
            // console.log(`${sectionInputArray.name} section will be added`);
            // console.log({ formDataTarget: formData[sectionInputArray.UID] });

            // New Inbound Rule
            // console.log([
            //   ...formData[sectionInputArray.UID],
            //   NestedListIDSingle(sectionInputArray),
            // ]);

            let addedFormData = {
              ...formData,
              [`${sectionInputArray.UID}`]: [
                ...formData[sectionInputArray.UID],
                NestedListIDSingle(sectionInputArray),
              ],
            };

            let randomVal = Math.random()
              .toString(36)
              // .replace(/[^a-z]+/g, "")
              .substr(0, 11);

            let withRandom = {
              ...addedFormData,
              rand_value: randomVal,
            };

            // console.log({ addedFormData: addedFormData });

            setFormData(withRandom);
          }}
        >
          Add New {sectionInputArray.name}
        </button>

        {/* Button to remove section (or created form) */}
        <button
          className="btn btn-primary bt-btn m-3"
          type="button"
          onClick={() => {
            console.log(
              `${sectionInputArray.name}-${idx} section will be removed`
            );
            // formData[sectionInputArray.UID].splice(idx, 1);

            let formDataTarget = formData[sectionInputArray.UID];
            // console.log(formDataTarget);

            let newFD = formData;

            newFD[sectionInputArray.UID].splice(idx, 1);

            let randomVal = Math.random()
              .toString(36)
              // .replace(/[^a-z]+/g, "")
              .substr(0, 11);

            let withRandom = {
              ...newFD,
              rand_value: randomVal,
            };

            setFormData(withRandom);
          }}
        >
          Remove {sectionInputArray.name}
        </button>

      </section>
      </>
      
      );
    } else {
      return (

        <>
      <section
        className={`col-md-${sectionInputArray.width} justify-content border-end mt-2 mb-2`}
      >
        <h4 className="border-bottom">{`${sectionInputArray.name}`} </h4>
        <div className="col-12"></div>
        {sectionInputArray.contents.map((input, i) => (
          <NestedDynamicInputCreation
            singleInput={input}
            formData={formData}
            setFormData={setFormData}
            options={options}
            mode={mode}
            staticVars={staticVars}
            SetStaticVars={SetStaticVars}
            i={i}
            idx={idx}
            arrayLength={arrayLength}
            sectionUID={sectionInputArray.UID}
          />
        ))} 
        
        </section>
        </>
        
      )

As you can see above when it is not on the view page it will then not use the buttons as it is removed within the 'else' section.

How could i create an instance of this, when the button is conditional. I tried placing an if statement just before the button section however that did not work

why java cant recognise my Variable in conditional code?

I was wondering why this code cant recognize the int variable I wanted to use the simple condition type like ( condition ? if true : if false) but it can't see my a b c as int variable when I use (&&) operator. but when i tried the normal if condition like if(a>b && b>c); it worked well any idea ?this is what i try and not working

How to insert data using parametrized sparql query?

I have this insert query:

INSERT { $subject <http://www.google.com/go#hasState> ?state} WHERE {?state a <http://www.google.com/go#State>. }

If the state is equal to <http://www.google.com/go#State-USA> I would need to insert all the states of type <http://www.google.com/go#State>. If not, I would need to insert only the specified state, for example: <http://www.google.com/go#State-Michigan> How could I write an if-else statement inside the insert, to check what the value of ?state is, and then to run the needed insert query.

display alert if data insert late before certain day of the week

i need help. i create a system which the user need to fill in a form, but the form will only be accept if they apply it 2 days before wednesday everyweek.

this what i got so far.

$dateNow = date('Y-m-d');
if (isset($_POST['submit'])) {
      $user_id = $_POST['user_id'];
      $user_name = $_POST['user_name'];
      $position = $_POST['position'];
      $dept_code = $_POST['dept_code'];
      $dept = $_POST['dept'];
      $dept_div = $_POST['dept_div'];
      $created_dt = date('Y-m-d G:i:sa');
                
      $sql = "INSERT INTO ot_application(user_id, user_name, position, dept_code, dept, dept_div, apply_date, created_dt) VALUES ('$user_id','$user_name','$position','$dept_code','$dept','$dept_div','$dateNow','$created_dt')";

      if (mysqli_query($conn, $sql)) {
          echo "<script>alert('Borang telah dikemaskini! ')</script>";
          echo "<script>";
          echo "window.location.href = 'list_borang_kerani.php?user_id=$user_id'";
          echo "</script>";
      } else {
          echo "Error: " . $sql . "<br>" . mysqli_error($dbconfig);
      }

jeudi 28 octobre 2021

Pine Script help if statements

I am having compiling errors with this if statement and plotshape any help would be appreciated.

//Produces Green and Red BUY an SELL signal triangles
if syminfo.ticker == "EURUSD"
     bullishSetup = crosslower
     bearishSetup = crossupper
     plotshape(bullishSetup ? 1 :na, style=shape.triangleup, color=color.green,  
       size=size.tiny, location=location.belowbar, title="Bullish Signal")
     plotshape(bearishSetup ? 1 :na, style=shape.triangledown, color=color.red, 
       size=size.tiny, location=location.abovebar, title="Bearish Signal")

how to find the error part in java coding

I have a problem where java.29 error.

can anyone help me tell where is my java error?

/MyClass.java:27: error: reached end of file while parsing
}
 ^

1 error

How to compare items in array using index numbers?

How can I compare one item in array to it's next or previous item using index numbers Take the code below as example

const arr = [
  {
    name: "A",
    marks: 20,
  },
  {
    name: "B",
    marks: 25,
  },
  {
    name: "C",
    marks: 30,
  },
];

So how can I compare B with A or C in an if statement using index numbers to get something done?

how to print in python using class and print function

class HexagonInteriorAngle(object):
    def __init__(self, x):
        self.x = self
    
    def FindInteriorAngle(self):
        degrees = int((x - 2) * 180)
        interior = int(degrees / x)
    
    def Print(self):
        if x == 3:
            print(str("an interior angle of a triangle equals " + str(interior)))
        elif x == 4:
            print("an interior angle of an equilateral equals " + str(interior))
        elif x == 5:
            print("an interior angle of a pentagon equals " + str(interior))
        elif x == 6:
            print("an interior angle of a hexagon equals " + str(interior))
        elif x == 7:
            print("an interior angle of a heptagon equals " + str(interior))
        elif x == 8:
            print("an interior angle of an octagon equals " + str(interior))
        elif x == 9:
            print("an interior angle of a nonagon equals " + str(interior))
        elif x == 10:
            print("an interior angle of a decagon equals " + str(interior))
        else:
            print(str(interior))

if __name__ == "__main__":
    x = int(input("enter: "))
    hexaObj = HexagonInteriorAngle(x)
    hexaObj.FindInteriorAngle()
    hexaObj.Print()

what i want to program to do is identify what type of polygon it is based off of the number of sides (ex. 6 sides = hexagon, 5 sides = pentagon, etc) and then print what one interior angle would be for that polygon (formula to find the interior angle : (the number of sides - 2) x 180 and then taking that answer and then dividing it by the number of sides). example: hexagon. ( 6 - 2 ) x 180 = 720 720 / 6 = 120

right now i'm pretty sure the actual code part is correct because if you do this it prints fine:

class HexagonInteriorAngle(object):
    def __init__(self, x):
        self.x = self
    
    def FindInteriorAngle(self):
        degrees = int((x - 2) * 180)
        interior = int(degrees / x)
        print("interior angle " + str(interior))

if __name__ == "__main__":
    x = int(input("enter: "))
    hexaObj = HexagonInteriorAngle(x)
    hexaObj.FindInteriorAngle()

Loop stops after first iteration

I need to check if every string in a list is in titlecase. If yes return True - if not return False. I have written the following:

word_list=["ABC", "abc", "Abc"]

def all_title_case(word_list): 
   for word in word_list: 
        if not word.istitle():
            return False
        else: 
            return True 

print(all_title_case(word_list))

My problem is that it seems that the loops stops after the first string (which i guess is because of return?)

How could i make it go over the whole list?

*I am new to python

thanks a lot!

Why is my else statement triggering sometimes but not always?

I am attempting to make an adventure game with some combat in it.

However, the

else:
    print("The werewolf took " + str(damage) + " damage. " + str(werewolf_health) + " health remains.") 

trigger (and the code beneath it) only triggers sometimes. Can you help me out with why?

This is the code:

def attack():
    werewolf_health = 100
    user_health = 100
    while werewolf_health > 0:
        attack = input(">").upper()
        if "ATTACK" in attack:
            damage = rand_int()
            damage2 = rand_int_werewolf()
            if damage == 20:
                print(random.choice(sword_crit))
                damage = damage * 1.5
                werewolf_health = werewolf_health - damage
                print("The werewolf took " + str(damage) + " damage. " + str(werewolf_health) + " health remains.")
                if werewolf_health <= 0:
                    print(random.choice(werewolf_death))
                    resolution()
            elif 17 <= damage <= 19:
                print(random.choice(sword_above_avg))
                werewolf_health = werewolf_health - damage
                print("The werewolf took " + str(damage) + " damage. " + str(werewolf_health) + " health remains.")
                if werewolf_health <= 0:
                    print(random.choice(werewolf_death))
                    resolution()
            elif 6 <= damage <= 16:
                print(random.choice(sword_avg))
                werewolf_health = werewolf_health - damage
                if werewolf_health <= 0:
                    print(random.choice(werewolf_death))
                    resolution()
                else:
                    print("The werewolf took " + str(damage) + " damage. " + str(werewolf_health) + " health remains.")
                    damage2 = rand_int_werewolf()
                    if damage2 == 20:
                        print(random.choice(werewolf_crit))
                        damage2 = damage2 * 1.5
                        user_health = user_health - damage2
                        print("You take " + str(damage2) + " damage. " + "Your health drops to " + str(
                            user_health) + ".")

Python code: If statement under while loop [duplicate]

I am working on a small project after learning a few basics about Python but in this part of the code bellow it get stuck it keeps saying "Which of the above would you like to choose: " and when I enter 1 or 2 it doesn't print anything it just repeats this "Which of the above would you like to choose: ". I am still new to coding can any of you help me find the problem in here.

str = 0 

while float (str) < 3 :
    x = input ("Which of the above would you like to choose: ")
    if x == 1 :
        print ("done")
    elif x == 2 :
        print ("done")

Thanks in regards.

renaming picture with if stament

I am looking to have multiple find statements in if elif. When I run the script all file have the same name. the second elif does not seem to run. How can I change my script to get file 001_f to have a different name then 001_s

This is the basics of what I am trying to do

echo "Enter the file path" read path echo cd $path

echo "Enter the number" read TNum echo If find $path -iname "001" ; then (mkdir -vp admin) && (mv -i 01 admin) echo -e "Created \t $path/admin and Moved 001 files to admin elif find "$path"/admin -iname "001_s" ; then FileName<${CreateDate;DateFmt("%Y%m%d")}$TNum${CreateTime;DateFmt("%H%M")}S%.2nc.%e' $path/admin elif find "$path"/admin -iname "001_f" ; Then FileName<${CreateDate;DateFmt("%Y%m%d")}$TNum_${CreateTime;DateFmt("%H%M")}_F%.2nc.%e' $path/admin else echo "No admin directory" fi exit 0

How can I determine if the input of the user is either of the two string in if statement in bot composer [closed]

The code that I used is

(user.input=="MAN"||"man")

enter image description here

using for loop and if statements

The output will not stop after I input 6 ages, it wants a 7th age, but I feel like it should be i <= 6. When I change it to i <= 5 it doesn't change it to 6 ages it changes to 5 aes so I'm not sure what's wrong.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    //declare variables
    int age;

    cout << "Enter the age of 6 friends: ";
    cin >> age;

    for (int i = 1; i <= 6; ++i)
    {
        if (age >= 0 && age < 13)
        {
            cout << age << "\tChild" << endl;
        }
        if (age >= 13 && age <= 19)
        {
            cout << age << "\tTeenager" << endl;
        }
        if (age > 19)
        {
            cout << age << "\tAdult" << endl;
        }
        cin >> age; 
    }

    //terminate program
    system("pause");
    return 0;
}

Bash script to check merged branches

I have a bash script that checks for all merged branches in the repositories.
I want to add some logic to it: in case there are no merged branches (either all branches were merged or deleted) it should print according message, but I can't figure out why the condition that I'm passing to it doesn't work(?).
I have tried different conditions (-z, -n), but it doesn't work.
Thank you.

script.sh

  for repo in "${REPOS[@]}"; do
    if [ -d "$repo" ]; then
      cd "$repo" || exit
      echo "Branches that were already merged into ${BRANCH_NAME} branch in $repo repository and could be deleted:"
      for branch in $(git branch -a --merged | grep -v ${BRANCH_NAME} | grep -Evw 'test' | awk 'BEGIN{FS="remotes/origin"} {print $2}') ; do
        if [ -z "$branch" ]; then
          echo "Nothing to delete."
        else
          echo "$branch" | cut -c 2-
          cd ../ || exit
        fi
      done;
    fi;
  done;

The output I'm receiving:

------------------------------------------
     Branches that were already merged into master branch in second-private repository and could be deleted:
     
     merged_branch

------------------------------------------

     Branches that were already merged into master branch in third-private repository and could be deleted:

    It prints out empty space but I want something like this:

    **no branches to delete** (message that I want to be displayed) 

------------------------------------------

I need help in c++ change cases

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string sentence =""; 
    cin >> sentence; //aab
    int i;
    
    for (i=0;i=sentence.length();i++){ 
        if (i<=65 && i>=90) {
            sentence = sentence[i] + 32;
        }
        else if (i<=97 && i>=122){                //i=0,
            sentence = sentence [i]-32;
        }
        
        
    }

    cout << sentence;
    return 0;
}

When I enter this code for changing cases of letters it keeps asking me to enter more although I have only one cin in the code why does that happen?

I'm a beginner at c and tried creating an if else programme but it's not working

#include <stdio.h>

int main();

{char subject[];
printf("Name of the subject you've passed.\n");
scanf("%s", &subject );
if (subject == "maths" ){ 
printf("You receive 100 Rs. \n");
}else if(subject == "science"){
printf("You receive 50 Rs. \n");
}
return 0;}

I think the code is fine but i am unable to find the problem.

Failure to trigger message when e-mails are sent asynchronously

I have a method that sends e-mails (using FluentEmail), and I want to trigger a message when they're sent. They are sent asynchronously. This is my method:

using System.Net;
using System.Net.Mail;
using FluentEmail.Core;
using FluentEmail.Smtp;

public void SendEmail() {

    try {

        var sender = new SmtpSender(() => new SmtpClient(host: "smtp.office365.com") {
            EnableSsl = true,
            UseDefaultCredentials = false,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            Credentials = new NetworkCredential("my@email.com", "myPassword"),
            Port = 587
        });

        Email.DefaultSender = sender;

        var newEmail = Email
            .From("my@email.com")
            .To("their@email.com")
            .Subject("a thousand blessings upon you")
            .Body("receive these blessings");

        foreach (var company in groupedByCompany) {

            string o = company.Select(x => x.PropertyName).FirstOrDefault().ToString();
            string n = company.Select(x => x.ProperyNameTwo).FirstOrDefault().ToString();
            newEmail.AttachFromFilename($@"C:\filepath\{o + n}", "application/pdf", "this is the preview text");

        var result = newEmail.SendAsync();

        if (result.IsCompleted == true) { //this is System.Threading.Tasks.Task<FluentEmail.Core.Models.SendResponse> result

            Console.WriteLine("E-mail sent!");

        } else {

            Console.WriteLine("Could not send e-mail.");
        }

    } catch (Exception ex) {

        // handle exception
    }
}

But the e-mail is sent without any messages in Output. I see that IsCompleted will be true if one of three conditions are met:

TaskStatus.RanToCompletion

TaskStatus.Faulted

TaskStatus.Canceled

What could I use instead of IsCompleted / what am I doing wrong?

Why is classic if writing and inline if writing are not behaving the same way?

I got this code

firstId = True
       
for x in [1,2,3,4,5]:
    firstId = False if firstId else print(str(x)+ " " + str(firstId))
    
print ("What is happening here ???")

firstId = True
       
for x in [1,2,3,4,5]:
    if firstId: 
        firstId = False
    else:
        print(str(x)+ " " + str(firstId))

And strangly i have this output

2 False
3 None
4 None
5 None
What is happening here ???
2 False
3 False
4 False
5 False

From my understanding both if statement should behave the same way.But the boolean is not. I can't understand why the boolean somehow becomes None. Can someone explain what is happening?

Unable to fathom logic expression for use in if... else... statement Python

I'm attempting a little game and I need to use some logic to check usage on board positions in order to set a bool validMove flag. I appreciate this isn't expert level code and there is certainly a better way of doing it, but this is the code I have written and is what I am using. I need to check for the instance of a space or an underscore at a specific point in a list. When I check for a space the code works, when I check for an underscore the code works, but when I try checking for both conditions with an or statement, the code fails. Could an expert advise what I am doing wrong please. Many thanks.

This code checking for an underscore works...

    while not valid_move:
    # check for unoccupied position
    if board[x][y] != '_':
        valid_move = False
        print('Invalid move detected.')
        print(board[x][y])
        get_user_input()
        getCoordinates(position)
    else:
        print('Valid move...')
        valid_move = True
        # update board with player position
        board[x][y] = player

This same code checking for a space works...

    while not valid_move:
    # check for unoccupied position
    if board[x][y] != ' ':
        valid_move = False
        print('Invalid move detected.')
        print(board[x][y])
        get_user_input()
        getCoordinates(position)
    else:
        print('Valid move...')
        valid_move = True
        # update board with player position
        board[x][y] = player

This code using on or statement checking for both, fails...

    while not valid_move:
    # check for unoccupied position
    if (board[x][y] != ' ') or (board[x][y] != '_'):
        valid_move = False
        print('Invalid move detected.')
        print(board[x][y])
        get_user_input()
        getCoordinates(position)
    else:
        print('Valid move...')
        valid_move = True
        # update board with player position
        board[x][y] = player