1: https://i.stack.imgur.com/B8bvP.png* any idea why its running both the if else statements and the else statement its suppose to be checking which type of user is logged a facebook user or a email user if none are logged in then it'll do the else and go to the login view
vendredi 31 janvier 2020
Arduino NFC If Statement C++
I am trying to do an if statement with my MFRC522 module for Arduino so that it can spin some motors with a certain NFC card. I have added below some code that I have tried to get it to work with which hasn't worked. I have tried some other methods from YouTube although they haven't worked either. Any ideas?
Card Read Area
Serial.print(F("Card UID:"));
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
if("EB A6 E9 21")
Serial.print("Door Unlocked");
int motorPin = 3;
digitalWrite(motorPin, HIGH); // turns the motor ON
delay(5000);
digitalWrite(motorPin, LOW); // turns the motor OFF
Serial.println();
Full Code (Includes Bluetooth Module)
#include <SoftwareSerial.h>
#include <ArduinoBlue.h>
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above
const unsigned long BAUD_RATE = 9600;
// The bluetooth tx and rx pins must be supported by software serial.
// Visit https://www.arduino.cc/en/Reference/SoftwareSerial for unsupported pins.
// Bluetooth TX -> Arduino D8
const int BLUETOOTH_TX = 8;
// Bluetooth RX -> Arduino D7
const int BLUETOOTH_RX = 7;
int prevThrottle = 49;
int prevSteering = 49;
int throttle, steering, sliderVal, button, sliderId;
SoftwareSerial bluetooth(BLUETOOTH_TX, BLUETOOTH_RX);
ArduinoBlue phone(bluetooth); // pass reference of bluetooth object to ArduinoBlue constructor
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
// Number of known default keys (hard-coded)
// NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
#define NR_KNOWN_KEYS 8
// Known keys, see: https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] = {
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
{0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
{0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
{0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
{0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
{0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // 00 00 00 00 00 00
};
// Setup code runs once after program starts.
void setup() {
// Start serial communications.
// The baud rate must be the same for both the serial and the bluetooth.
SPI.begin();
Serial.begin(BAUD_RATE);
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
mfrc522.PCD_Init(); // Init MFRC522 card
Serial.println(F("Try the most used default keys to print block 0 of a MIFARE PICC."));
bluetooth.begin(BAUD_RATE);
delay(100);
Serial.println("setup complete");
}
void dump_byte_array(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);
}
}
bool try_key(MFRC522::MIFARE_Key *key)
{
bool result = false;
byte buffer[18];
byte block = 0;
MFRC522::StatusCode status;
// Serial.println(F("Authenticating using key A..."));
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
// Serial.print(F("PCD_Authenticate() failed: "));
// Serial.println(mfrc522.GetStatusCodeName(status));
return false;
}
// Read block
byte byteCount = sizeof(buffer);
status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
if (status != MFRC522::STATUS_OK) {
// Serial.print(F("MIFARE_Read() failed: "));
// Serial.println(mfrc522.GetStatusCodeName(status));
}
else {
// Successful read
result = true;
Serial.print(F("Success with key:"));
dump_byte_array((*key).keyByte, MFRC522::MF_KEY_SIZE);
Serial.println();
// Dump block data
Serial.print(F("Block ")); Serial.print(block); Serial.print(F(":"));
dump_byte_array(buffer, 16);
Serial.println();
}
Serial.println();
mfrc522.PICC_HaltA(); // Halt PICC
mfrc522.PCD_StopCrypto1(); // Stop encryption on PCD
return result;
}
void loop() {
button = phone.getButton();
// Returns the text data sent from the phone.
// After it returns the latest data, empty string "" is sent in subsequent.
// calls until text data is sent again.
String str = phone.getText();
// Display button data whenever its pressed.
if (button == 1) {
Serial.print("Door Locked");
}
// Display button data whenever its pressed.
if (button == 0) {
Serial.print("Door Unlocked");
int motorPin = 3;
digitalWrite(motorPin, HIGH); // turns the motor ON
delay(5000);
digitalWrite(motorPin, LOW); // turns the motor OFF
}
// Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
if ( ! mfrc522.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
return;
// Show some details of the PICC (that is: the tag/card)
Serial.print(F("Card UID:"));
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
if("Z")
Serial.print("Door Unlocked");
int motorPin = 3;
digitalWrite(motorPin, HIGH); // turns the motor ON
delay(5000);
digitalWrite(motorPin, LOW); // turns the motor OFF
Serial.println();
Serial.print(F("PICC type: "));
MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));
// Try the known default keys
MFRC522::MIFARE_Key key;
for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
// Copy the known key into the MIFARE_Key structure
for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
key.keyByte[i] = knownKeys[k][i];
}
// Try the key
if (try_key(&key)) {
// Found and reported on the key and block,
// no need to try other keys for this PICC
break;
}
// http://arduino.stackexchange.com/a/14316
if ( ! mfrc522.PICC_IsNewCardPresent())
break;
if ( ! mfrc522.PICC_ReadCardSerial())
break;
}
}
Wordpress - define variable with IF Statement
I've got an ACF Advanced custom field for currency where the user can select currency from the available USD, GBP & EUR select dropdown.
Based on the selection I want to show the currency sign.
I'm trying to define the $price_currency variable that I can then use in my output echo like this: echo '<span>' . $price_currency . '</span>';
This is my current code:
$price_currency = {
if(get_field('ktrr_ktcamp_price') == "USD");
echo '$';
} elseif(get_field('ktrr_ktcamp_price') == "GBP");
echo '£';
} elseif(get_field('ktrr_ktcamp_price') == "EUR");
echo '€';
}
But I'm getting syntax errors.
What am I doing wrong here?
How do I write an "If/else Statement" to condicionate the answer for the user?
I am having trouble writing an if/else statement that conditionate the answer of the user. I am asking the user to enter a number between 1 and 8, if the user enters a number between that range the answer will be storage on a variable, if the answer it is outside the range the program will say something like: "Invalid position." Something like this:
System.out.println("Choose a number (Between 1 to 8)");
if(---------------){
ubNum = input.nextInt();
}else{
System.out.println("Enter a valid number please");
}
What do I need to put in the if statement to accomplish it?
how to make calculator in JQuery when we add new equation that remove old eval value and replace a new button value in JQuery?
I am trying to replace the 'answer' value with new value in my 'jquery' calculator. but it does not replace the answer. rather it adds to next of the 'answer'.strong text
<input type="text" id="preview">
<input type="button" type="button" id="btn1" value="3" onclick="showValue()">
<input type="button" id="btn2" value="4">
<input type="button" id="btn4" value="*">
<input type="button" id="btn5" value="+">
<input type="button" id="btn6" value="-">
<input type="button" id="btn7" value="/">
<input type="button" id="btn3" value="=">
<input type="button" id="btn8" value="bs">
$("#btn1").click(function () {
$("#preview").val($("#preview").val() + $("#btn1").val())
});
$("#btn2").click(function () {
$("#preview").val($("#preview").val() + $("#btn2").val())
});
$("#btn4").click(function () {
$("#preview").val($("#preview").val() + $("#btn4").val())
});
$("#btn5").click(function () {
$("#preview").val($("#preview").val() + $("#btn5").val())
});
$("#btn6").click(function () {
$("#preview").val($("#preview").val() + $("#btn6").val())
});
$("#btn7").click(function () {
$("#preview").val($("#preview").val() + $("#btn7").val())
});
$("#btn8").click(function () {
$("#preview").val($('#preview').val().substring(0, $('#preview').val().length - 1));
});
$("#btn3").click(function () {
$("#preview").val((eval($("#preview").val()))
)
});
Find a partial string in a cell and return exact value using a formula?
I need some help on this. I would like to find two different partial strings in a cell using a formula. For example - if cell (A1) contains "Staples A-12345 Georgia, USA" or other cell may contain only "g345" or "g100, g000" or other times it contains both A-12345 g345 in a cell as an example.
My goal is to return a value of "GXXX" or if not present, use the "A-XXXXX".
Search A1 cell for partial text of "A-" or "G". (The "A-, must contain 7 characters" and "G, must contain 4 characters.)
- If true, C1 to return value of GXXX or if that is not present, use the other one.
- If it contains multiple codes (GXXX, GXXX) then return both values separated with a comma
- If it contains both "A-" and "G" in a cell, grab only the "G" code.
- If cell blank, return blank value.
- If cell value does not contain both "GXXX" or "A-XXXXX", copy and return the same value.
I am currently using this formula. I am unable to display the actual string.
=IFS(
ISNUMBER(SEARCH("*A-*",A1)),"TRUE",
ISNUMBER(SEARCH("*G*",A1)),"TRUE")
I got confused and stuck on this.Your time and help is greatly appreciated. Thank you.
Windows batch Script money output
Can anyone help with this please Request and accept an amount of money from the user. Note this will be in cents Output the minimum number of €2, €1, 50c, 20c, 10c, 5c, 2c and 1c coins which make up this amount
How to exclude empty line and number less than zero in python when using while loop
I am writing a simple program that executes if-else condition. my program receives from the user as input the weight of an object in kg. , a floating number, and print out the price for shipment. by using while I want to Expand the program to function and calculate the total price for multiple packages. The program should load packet weight until the user enters a blank line or a number that is 0 or less. The program will then print the total price for all the packages
the code looks like this:
def packagePrice():
weightInKg = float(input(" Enter the value of weight:"))
totalPrise = 0
while weightInKg != "" or weight <= 0:
if weightInKg <= 10:
price = 149
elif 10 < weightInKg <= 100:
price = 500
elif weightInKg > 100:
print ("Not allowed")
totalPrise+= price
print(totalPrise)
weightInKg = float(input(" Enter the value of weight:"))
packagePrice()
but it does not properly run anyone help
How to switch between multiple variables using an if-else statement in Python
How would I make a switch between multiple variables using a single switch variable? When I try this I get the following error.
a1= 'yes'
a2 = 'no'
b1 = 'hello'
b2 = 'goodbye'
switch = True
for i in range (2):
response, greeting = a1, b1 if switch else a2, b2
print("%s, the answer is: %s" %(greeting, response))
switch = not switch
Traceback:
Traceback (most recent call last):
File "/home/username/.PyCharm2019.3/config/scratches/scratch_10.py", line 10, in <module>
response, greeting = a1, b1 if switch else a2, b2
ValueError: too many values to unpack (expected 2)
Process finished with exit code 1
Is there a way I can automate moving files from into different locations using an if/ else statement in Matlab?
I have a Matlab script that looks at information in a .xsl file and a DICOM file. I have recorded information on both files that need to match. I created a script that can review the information on both files and in an if/else statement it will display "Perfect Match", "Error 1", "Error 2". After that, I typically manually move the files to their respective folders.
However, I have recently gotten a hold of a lot of files that I need to perform this validation. Instead of manually moving the files is there a way I can automate this, hopefully by coupling it with the if/else statement? Here is a snippet of the code:
if sum(~ismember(BeamMetersets,cell2mat(MOSAIQ_sel(:,10))))==0
disp('Perfect Match!!!')
else
disp('ERROR 1')
BeamMetersets
mosaiq_beam_values=cell2mat(MOSAIQ_sel(:,10))
end
else
disp('Error 2')
end
How to split a List of Dictionary into 2 seperates list of dictionaries with equality check
I am currently working on a Website which will detect the user games and the time. In my webapplication the user can set the games as finished (played). I successfully created a list of dictionary and the one game which got played to the end. I think a bit of Code illustration would help.
That is my code which should generate two seperate list of dictionaries. played_games_entries does actually work. I try it with an else but it doesn't work as I intendet. I know the problem but it is hard to explain and I dont now what my approach should be. If I am honest I am a bit confused because the if statement works and the else statement not.
def get_name_and_due(request, played_games, games_list):
open_games_entries = []
played_games_entries = []
for game in games_list:
for played_game in played_games:
due_perc = convert_due_into_percentage(game['due'], request.session.get('max_due'))
if game['game_name'] == played_game['played_game_name']:
played_games_entries.append({'name': game['game_name'], 'due': due_perc})
break
else:
pass
Here are my values for the parameters played_games and game_list.
games_list = [
{'index': '1', 'game_name': 'Temtem', 'due': '00:30:04'},
{'index': '2', 'game_name': 'The Forest', 'due': '10:00:30'},
{'index': '3', 'game_name': 'The Witcher 3: Wild Hunt', 'due': '50:15:25'},
{'index': '4', 'game_name': 'STAR WARS Jedi: Fallen Order', 'due': '18:15:00'}
]
played_games = [
{'played_game_name': 'Grand Theft Auto: San Andreas'},
{'played_game_name': 'The Witcher 3: Wild Hunt'},
{'played_game_name': 'ONE PIECE: PIRATE WARRIORS 4'}
]
And the last code would be the expected result. And to point out played_game_entries does work
open_games_entries = [
{'index': '1', 'game_name': 'Temtem', 'due': '24.44'},
{'index': '2', 'game_name': 'The Forest', 'due': '10'},
{'index': '4', 'game_name': 'STAR WARS Jedi: Fallen Order', 'due': '20'}
]
played_games_entries = [
{'index': '3', 'game_name': 'The Witcher 3: Wild Hunt', 'due': '100'}
]
I worked all day to fix it on my own but I failed. I look the problem up on the internet and SO and many suggest Set. But didn't consider this approach because it is based on list and I have an List of Dictionaries. And I am really interested in seeing a approach with an for-loop because I really think it is possible.
Best Regards
Linda
Element sometimes appears and sometimes does not, how to continue script either way?
My selenium (python) script is doing some work on a website that is a dashboard I.e the actual webpage/link does not change as I interact with elements on this dashboard. I mention this as I considered simply hopping around different links via driver.get() command to avoid some of the issues I am having right now.
At one point, the script reaches a part of the dashboard that for some reason during some of my test runs has an element and other times this element is not present. I have a few lines that interact with this element as it is in the way of another element that I would like to .click(). So when this element is not present my script stops working. This is a script that will repeat the same actions with small variations at the beginning, so I need to somehow integrate some sort of an 'if' command I guess.
My goal is to write something that does this: - If this element is NOT present skip the lines of code that interact with it and jump to the next line of action. If the element is present obviously carry on.
day = driver.find_element_by_xpath('/html/body/div[4]/table/tbody/tr[4]/td[2]/a')
ActionChains(driver).move_to_element(day).click().perform()
driver.implicitly_wait(30)
lizard2 = driver.find_element_by_xpath('/html/body/div[5]/div/div[2]/div[1]/img')
ActionChains(driver).move_to_element(lizard2).perform()
x2 = driver.find_element_by_xpath('/html/body/div[5]/div/div[2]/div[2]')
ActionChains(driver).move_to_element(x2).click().perform()
driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')
So the block that starts with 'lizard2' and goes to the ActionChains line is the block that interacts with this element that is sometimes apparent sometimes not as the script goes back and forth doing the task.
The top two lines are just the code that gets me to the phase of the dashboard that has this randomly appearing element. And the scroll command at the end is what follows. As mentioned before I need the middle part to be ignored and continue to the scroll part if this 'lizard2' and 'x2' elements are not found.
I apologize if this is confusing and not really concise, I am excited to hear what you guys think and provide any additional information/details, thank you!
I need to retrun srings based on temperature
If the temperature is 100 or above, the functions return “It is hot.”;
If the temperature is between 70 and 100, the function returns “It is warm.”;
If the temperature is between 32 and 70, the functions return “It is cool.”;
If the temperature is below 32, it returns “It is cold.”
The function feelTemp will take one value for the temperature, and then returns a category as a string.
When running the program, the user is prompted to input a temperature, then the program print one of the four categorical levels (hot, warm, cool, and cold) that the given temperature falls into.
I have tried this but getting an error in syntax.
What should I do?:
def feelTemp(t):
if t<=100:
return "It is hot."
elif t>=70 and t<=100:
return "It is warm."
elif t>=32 and t<=70:
return "It is cool."
else:
return "It is cold."
feelTemp(105)
And how to set an input field as well?
is there any way to initialize a variable , when we writing the condition of if, and then compare
if (n=2+3)==5: print(n)
I executed the above code in python but it was showing an error in "if condition" . i want to know whether there is a way to achieve this.
Problem with indexing within if-elif statements (indexer incompatible with series)
I'm trying to run the following code, but I am having trouble with the .loc function. What I am trying to do is (1) sort each row by the type of row they are, (2) use the data from 4 columns within that row as 4 different indices for another dataframe, then (3) take the product of those 4 newly indexed items and create a new column in a dataframe (TL4_tranpose) with that data.
# run through list of each child
for i in range(56):
# if, elif and else separating them into groups of theorists [Size, Material, Mass or Random]
# same method as above for fitting the pretest
# grab each subjects responses
sub_choices = TL4_transpose[['learn_1', 'learn_2', 'learn_3', 'learn_4', 'Theory', 'ParticipantID']].iloc[i]
if TL4_transpose.Theory[i] == 'Size':
Size_Learn = pd.DataFrame()
prob_Size = []
for j in range(4):
# look up the prob of that participant's choices happening at each of 8 trials
Size_Learn = Size_Learn.append([sizeModelLearn.iloc[j][sub_choices.iloc[j]]])
# take the product of participant's fit to the model; assuming independence due to no feedback
prob_Size = abs(Size_Learn.product())
TL4_transpose.loc[str(i), 'LearnProb'] = prob_Size **<-- where the error pops up **
TL4_transpose.loc[str(i), 'LearnLog'] = math.log(prob_Size)
elif TL4_transpose.Theory[i] == 'Material':
mat_prob = 2
TL4_transpose.loc[str(i), 'LearnProb'] = 'Material'
TL4_transpose.loc[str(i), 'LearnLog'] = mat_prob
elif TL4_transpose.Theory[i] == 'Mass':
mass_prob = 3
TL4_transpose.loc[str(i), 'LearnProb'] = 'Mass'
TL4_transpose.loc[str(i), 'LearnLog'] = mass_prob
elif TL4_transpose.Theory[i] == 'Random':
ran_prob = 0.2 ** 4
TL4_transpose.loc[str(i), 'LearnProb'] = 'Random'
TL4_transpose.loc[str(i), 'LearnLog'] = ran_prob
# take the log for simplification
#TL4_transpose.loc[i, 'log(test)'] = math.log(prob_Choice)
TL4_transpose
but it keeps giving me the error code:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-517-e664a51dffaf> in <module>()
19 prob_Size = abs(Size_Learn.product())
20
---> 21 TL4_transpose.loc[str(i), 'LearnProb'] = prob_Size
22 TL4_transpose.loc[str(i), 'LearnLog'] = math.log(prob_Size)
23
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in __setitem__(self, key, value)
187 key = com._apply_if_callable(key, self.obj)
188 indexer = self._get_setitem_indexer(key)
--> 189 self._setitem_with_indexer(indexer, value)
190
191 def _validate_key(self, key, axis):
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _setitem_with_indexer(self, indexer, value)
467
468 if isinstance(value, ABCSeries):
--> 469 value = self._align_series(indexer, value)
470
471 info_idx = indexer[info_axis]
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _align_series(self, indexer, ser, multiindex_indexer)
775 return ser.reindex(ax)._values
776
--> 777 raise ValueError('Incompatible indexer with Series')
778
779 def _align_frame(self, indexer, df):
ValueError: Incompatible indexer with Series
Is there a way to fix this?
Edit:
Earlier on in my notebook, I was able to run this cell:
Pretest_Probs = pd.DataFrame()
for j in range(93):
# grab participant j's data
sub_choices = PrePost[['pre1', 'pre2', 'pre3', 'pre4', 'pre5','pre6', 'pre7', 'pre8']].iloc[j]
# need blank dataframes each time you run the loop, else it'll output a single columns with (i * j) values
sub_Size_Pre = pd.DataFrame()
prob_sub_Size = []
for i in range(8):
# look up the prob of that participant's choices happening at each of 8 trials
sub_Size_Pre = sub_Size_Pre.append([sizeModelPre.iloc[i][sub_choices.iloc[i]]])
# take the product of participant's fit to the model; assuming independence due to no feedback
prob_sub_Size = abs(sub_Size_Pre.product())
# take the log for simplification
size_log_like = math.log(prob_sub_Size)
Pretest_Probs.loc[str(j), 0] = size_log_like
Pretest_Probs.head()
which does a similar process as the code with the error, but does not include the if/elif statements.
When I change
TL4_transpose.loc[str(i), 'LearnProb'] = prob_Size
to
TL4_transpose.loc[str(i)]['LearnProb'] = prob_Size
I get
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _validate_key(self, key, axis)
1789 if not ax.contains(key):
-> 1790 error()
1791 except TypeError as e:
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in error()
1784 .format(key=key,
-> 1785 axis=self.obj._get_axis_name(axis)))
1786
KeyError: 'the label [15] is not in the [index]'
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-528-d95879b9ab92> in <module>()
21 prob_Size = abs(Size_Learn.product())
22
---> 23 TL4_transpose.loc[str(i)]['LearnProb'] = prob_Size
24 TL4_transpose.loc[str(i), 'LearnLog'] = math.log(prob_Size)
25
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
1476
1477 maybe_callable = com._apply_if_callable(key, self.obj)
-> 1478 return self._getitem_axis(maybe_callable, axis=axis)
1479
1480 def _is_scalar_access(self, key):
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
1909
1910 # fall thru to straight lookup
-> 1911 self._validate_key(key, axis)
1912 return self._get_label(key, axis=axis)
1913
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _validate_key(self, key, axis)
1796 raise
1797 except:
-> 1798 error()
1799
1800 def _is_scalar_access(self, key):
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in error()
1783 raise KeyError(u"the label [{key}] is not in the [{axis}]"
1784 .format(key=key,
-> 1785 axis=self.obj._get_axis_name(axis)))
1786
1787 try:
KeyError: 'the label [15] is not in the [index]'
use ternary operator as if elseif and else
I want to check if the role is agency then the output is $agencyUsers
else if the role is officer then the output is $officeUsers
else I need to output 'No Group'
I try this but the output is 'No Group' for all users
<td></td>
How to let if statement complete even if there is a NullPointerError
I have this if statement:
if (!this.updateTime.equals(ProductionBlocking
.get(this.keyReader.getUpdateTime(this.config.configUuid.toString(),
KeyType.PLUSSTAR)))) {
...
}
Sometimes the below is null so I get a NullPointerError.
ProductionBlocking
.get(this.keyReader.getUpdateTime(this.config.configUuid.toString(),
KeyType.PLUSSTAR))`
Is there any way I can let the program run on even if there is a null pointer? Basically in this case I'd like the if to determine they arent equal.
Java Math.min(a,b) or Math.max (a,b) as a decision maker [closed]
I need to simulate an if statement (make a decision) but only by using Math.min(a,b) or Math.max(a,b) statements. It is a requirement.
Lets say "a" is a value entered by the user and "b" is a maximum value allowed already given. If "a" is less than or equal (a <= b) to the maximum "b" an action takes place, else another action is executed.
Any suggestion will be appreciated. Thanks!
Comparison Operator is not working in php [duplicate]
what ever i do, i cant get anything else other than NR, it always prints NR, it is not comparing the strings which i pass. please help
class Movie{
public $name;
private $rating;
function __construct($name, $rating){
$this -> name=$name;
$this -> setRating($rating);
}
function setRating($RATNG){
if ("G" == $RATING || $RATING == "PG" || $RATING == "PG-13" || $RATING == "R" || $RATING == "NR") {
$this -> rating = $RATING;
}else {
$this -> rating = "NR";
}
}
function getRating(){
return $this -> rating;
}
}
$movie1 = new Movie("Avengers", "PG-13");
//G, PG, PG-13, R, NR
$movie1 -> setRating("G");
echo $movie1-> getRating();
How to create a loop in Python (ADF test with p-value check)
I need a little help with creating a loop in Python. Here's the code that I'm using:
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.graphics.tsaplots import plot_pacf
%matplotlib inline
df= pd.read_csv('original_data.csv', index_col='1')
from statsmodels.tsa.stattools import adfuller
def adf_test(timeseries):
#Perform Dickey-Fuller test:
test_types = ['nc','c','ct']
for tests in test_types:
print ('\n Results of Dickey-Fuller Test type = {}:\n'.format(tests))
dftest = adfuller(timeseries,regression=tests,autolag='AIC')
dfoutput = pd.Series(dftest[0:4],index=['Test Statistic','p-value','#Lags used','#Observations used'])
# for key, value in dftest[4].items():
# dfoutput['Critical value (%s)'%key] = value
print(dfoutput)
p_value = dftest[1]
if p_value > 0.05:
print('Unit root!')
elif p_value < 0.05:
print('No unit root!')
adf_test(df['2']) #2 is the number of the column in the cvs file
n = 1
df['rates_difference'] = df['2']-df['2'].shift(n)
adf_test(df['rates_difference'].dropna())
n = 1
df['rates_difference2'] = df['rates_difference']-df['rates_difference'].shift(n)
adf_test(df['rates_difference2'].dropna())
The idea is that the code is checking if the data is stationary (p-value < 0.05) using 3 versions of ADF test. If it is not, then we have to do first difference and check again. If it is not stationary again, we have to do second difference and check p-value. So this process has to loop until the data is stationary.
Thanks in advance.
Why if condition "(skaner.next() != int)" highlights as wrong?
I wanna make a condition if somebody input a word the program will return "That is a string" if it is an integer the program will return "That is an integer ". What's wrong with my if condition ?
package folder;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner skaner = new Scanner(System.in);
while (skaner.hasNext()){
if (skaner.next() != int) {
System.out.println("That is a string" + skaner.next());
}
else {
System.out.println("That is an integer " + skaner.next());
}
}
skaner.close();
}
}
If condition in mail body phpmailer
I am using Phpmailer and I am currently emailing the data from my database. However, I need to have a color coding depending on the chosen condition. For example, if the remarks is proceed, the data cell should be in green color and red if hold. Im not really sure how to apply if loop inside an echo. Please help
while ($rowwaf = mysqli_fetch_assoc($queryres)){
$mailbody = "
Good Day!<br><br>
Please see details below<br><br>
<strong>Details:</strong><br><br>
<table class=\"table\" cellpadding=\"5\" rules=\"all\" frame=\"box\" border=\"1\">
<tr><td class=\"data\"><strong>REQUEST DATE:</strong></td><td>".$rowwaf["req_date"]."</td></tr>
<tr><td class=\"data\"><strong>ISSUE ENCOUNTERED:</strong></td><td>".$rowwaf["issue"]."</td></tr>
<tr><td class=\"data\"><strong>URGENCY:</strong> </td><td>".$rowwaf["urgency"]."</td></tr>
<tr><td class=\"data\"><strong>REQUESTOR:</strong></td><td>".$rowwaf["requestor"]."</td></tr>
<tr><td class=\"data\"><strong>REMARKS:</strong></td>
-- if condition sample--
if {
$rowwaf["remarks"] == proceed
<td style="color: green">".$rowwaf["remarks"]."</td></tr>
}
else {
$rowwaf["remarks"] == hold
<td style="color: red">".$rowwaf["remarks"]."</td></tr>
}
";
How to check if a variable equals one of two values if a clean manner in JS [duplicate]
To check if x
variable is equal to 1 or 2, i would do normally something like:
if (x === 1 || x === 2){
// ....
}
but this can get in some cases very cumbersome.
Edit :I'm working right now on this and writing the fonction name every time i think can be done in a cleaner manner:
if (
this.getNotificationStatus() === 'denied' ||
this.getNotificationStatus() === 'blocked'
)
Is there any other lighter way to write this?
THANKS
How to include a if check into a for loop
I try add a constraint expressions to a python/pyomo model: the code I tried is this:
for r_k in VAR1:
for p_v in VAR2:
for b_n in VAR3:
IF mix[b_n][p_v]() >= 0:
model.cons.add(model.func2[r_k,b_n,p_v]*q1[b_n][p_v] - model.func1[r_k,b_n,p_v] ==0)
If I leave the IF
loop away it runs fine. The code above produces a Syntax error. Only downside is it creates 1000s of extra mathematically trivial constraints that are not needed.
"mix" is only a sparsely populated "binary" dictionary (i.e. mostly zeros, a few ones in between). A constraint is only needed where there is a "1". It seems there is an issue with evaluating/calling the dictionary values within the for loops. Any idea how to resolve this would be much appreciated. Thanks.
jeudi 30 janvier 2020
How to do multiple if without nested if
if (jamholderku.equals("1")){
params.put("sesi1", jamholderku);
}else {
params.put("sesi1", jamholder);
}
if (jamholderku2.equals("1")){
params.put("sesi2", jamholderku2);
}else {
params.put("sesi2", jamholder2);
}
if (jamholderku3.equals("1")){
params.put("sesi3", jamholderku3);
}else {
params.put("sesi3", jamholder3);
Log.d("paramskutes", jamholder3);
}
if (jamholderku4.equals("1")){
params.put("sesi4", jamholderku4);
}else {
params.put("sesi4", jamholder4);
}
if (jamholderku2_1.equals("1")){
params.put("sesi2_1", jamholderku2_1);
}else {
params.put("sesi2_1", jamholder2_1);
}
if (jamholderku2_2.equals("1")){
params.put("sesi2_2", jamholderku2_2);
}else {
params.put("sesi2_2", jamholder2_2);
}
if (jamholderku2_3.equals("1")){
params.put("sesi3", jamholderku2_3);
}else {
params.put("sesi3", jamholder2_3);
}
if (jamholderku2_4.equals("1")){
params.put("sesi4", jamholderku2_4);
}else {
params.put("sesi4", jamholder2_4);
}
if (jamholderku3_1.equals("1")){
params.put("sesi2_1", jamholderku3_1);
}else {
params.put("sesi2_1", jamholder3_1);
}
if (jamholderku3_2.equals("1")){
params.put("sesi2_2", jamholderku3_2);
}else {
params.put("sesi2_2", jamholder3_2);
}
if (jamholderku3_3.equals("1")){
params.put("sesi3", jamholderku3_3);
}else {
params.put("sesi3", jamholder3_3);
}
if (jamholderku3_4.equals("1")){
params.put("sesi4", jamholderku3_4);
}else {
params.put("sesi4", jamholder3_4);
}
if (jamholderku4_1.equals("1")){
params.put("sesi2_1", jamholderku4_1);
}else {
params.put("sesi2_1", jamholder4_1);
}
if (jamholderku4_2.equals("1")){
params.put("sesi2_2", jamholderku4_2);
}else {
params.put("sesi2_2", jamholder4_2);
}
if (jamholderku4_3.equals("1")){
params.put("sesi3", jamholderku4_3);
}else {
params.put("sesi3", jamholder4_3);
}
if (jamholderku4_4.equals("1")){
params.put("sesi4", jamholderku4_4);
}else {
params.put("sesi4", jamholder4_4);
}
return params;
when the first if statement right it will not execute other if statement EX: if (jamholderku.equals("1))
== True then it will execute params.put(blablabla) but it won't execute other if statement like if (jamholderku2.equals("1"))
but if it executing if (jamholderku2.equals("1"))
it won't execute if (jamholderku3.equals("1"))
even if it was true can you please help me? because it deadline was due temorrow, i need to submit it or i get kicked from my team
Receiving no output when NOT clause is used in SQL to detect duplicate records under same values
Im new to SQL and trying to understand how i can find if similar fields exist across different values in a column:
My code:
WITH LOC_CTE AS
(SELECT DISTINCT fa.AccountKey, dce.EmailAddress , dcp.Phone , dpo.BrandName, dpo.BrandId
FROM Fact.Account fa
LEFT JOIN Dim.PetOwner dpo ON dpo.PetOwnerKey = fa.PetOwnerKey
LEFT JOIN Dim.RatingAddress dra ON dra.RatingAddressKey = fa.RatingAddressKey
LEFT JOIN Dim.CustomerEmail dce ON dce.CustomerEmailKey = fa.CurrentCustomerEmailKey
LEFT JOIN Dim.CustomerPrimaryPhone dcp ON dcp.CustomerPrimaryPhoneKey = fa.CurrentCustomerPrimaryPhoneKey
)
SELECT * FROM (
SELECT LOC_CTE.*
,row_number() over (partition by EmailAddress,Phone,BrandId order by BrandName) as seqnum
from LOC_CTE
) Q
where seqnum >= 1;
The output gives me:
AccountKeyEmailAddress Phone BrandName BrandId seqnum
389082 0160150@m**.edu 2098579** AP 4 1
430223 01co***st**e@msn.com8655677**9 AP 4 1
430224 01cor**s**e@msn.com 8655677**9 AP 4 2
531443 01mar**01@gmail.com 73278**63 AP 4 1
544454 01mu**rmyra@gmail.com 8133**793 AP 4 1
548374 03b**y13@gmail.com 30130**93 AP 4 1
216594 03d**ado@gmail.com 50363**34 AP 4 1
377919 03d**ado@gmail.com 50363**734 AP 4 2
486237 03d**ado@gmail.com 50363**734 HP 3 3
532010 041**hen@gmail.com 85749**455 AP 4 1
365925 05bla**ro*e21@gmail.com 682365**51 AP 4 1
365926 05bla**ro*e21@gmail.com 682365**51 HP 3 2
So as can be observed in my output, I am able to detect duplicate records and sequence of its duplicity. Bu what I want is that my final report also detects if the same person(email and phone number) is repeated under a different brand. For example if you notice in the last two rows of the ouput it is the same individual but under 2 different brands and brand ID. But I just want to isolate these instances and generate an output which only shows the original duplicate along with the duplicate that comes up under a different brand/brandID. How do I do this?
I tried to edit the last line of my clause and integrated a NOT clause but I did not receive any output and neither any error. My syntax may be wrong but hope this helps with the logic
where seqnum >= 1 AND NOT BrandID = BrandID ;
VB vlookup in different sheet for certain values
can you please help me with a vlookup in a different sheet only for certain values? I have tried for each, for i, different if's and so on.
I need the vba to bring in Sheet2 values from a Sheet1, but only for rows that have the value "De rediscutat" in a different column in Sheet2.
Below you have the code i wrote for this function:
Dim result As String
Dim Sheet2 As Worksheet
Set Sheet2 = ActiveWorkbook.Sheets("Sheet2")
Set MyRange = Range("X2:X800")
If MyRange = "De rediscutat" Then
Worksheets("Sheet2").Range("N2:N694").Formula = Application.WorksheetFunction.VLookup(Sheet2.Range("I2:I694"), Sheet1.Range("G2:M500"), 7, False)
End If
End Sub```
Thanks!
Using existing values exported from SAP to populate new column values through VBA
I am having trouble coming up with a VBA code creating a new column with values based on an existing column. The code I have is shown below. I tried to attach an image of the excel file I am working with, but I am new to this website so it will not let me. I am initially extracting an excel file from SAP, containing date values that are change every time the macro is run. 'Start Date' (Column J), represents the day that the activity started. From this SAP data column, I created a macro that created a new column (Column L) counting the number of days it has been since the start date. From that column, I am attempting to create three more columns.
1) A column that counts as a 1 if 6< Column L < 20 Days, and counts as a 0 for everything else
2) A column that counts as a 1 if Column L > 20 Days, and counts as a 0 for everything else
3) A column that counts as a 1 if Column L < 6 Days, and counts as a 0 for everything else
With ActiveSheet
ndt = Application.Range("D:D").Cells.SpecialCells(xlCellTypeConstants).Count 'Counts number of rows in column to see how many values there are
End With
With ActiveSheet
Set rngCategory = .Range(.Cells(2, 9), .Cells(ndt, 9)) 'setting up of array of start date column
End With
varCategory = rngCategory 'setting varCategory equal to the array made earlier
agedresults = varCategory 'setting agedresults equal to the array
For lngIdx = 1 To UBound(varCategory) 'For the number of rows in the array
startdate = varCategory(lngIdx, 1) 'start date equals the array
agedresults(lngIdx, 1) = DateDiff("d", startdate, Format(Now(), "MM/DD/YYYY")) 'aged results equals the difference in todays date and the start date value
Next lngIdx
unaged = agedresults
For lngIdx = 1 To UBound(varCategory)
If agedresults(lngIdx, 1) < 6 Then unaged(lngIdx, 1) = 1 Else unaged(lngIdx, 1) = 0
Next lngIdx
With ActiveSheet
Set rngResults = .Range(.Cells(2, 12), .Cells(ndt, 12))
.Cells(1, 12) = "Days in QM Lot"
Set agedcolumn = .Range(.Cells(2, 13), .Cells(ndt, 13))
.Cells(1, 13) = "Aged"
End With
rngResults = agedresults
agedcolumn = aged
For some reason, the days value is being populated (Column L), but the other three columns are being left blank (except for the header). Does anybody know why this would be the case? Is there something wrong with my if statement?
How to validate if one attribute value is always a value of another attribute in XML by XSD
I have an xm structure like this and I want to Validate the XMl with XSD
<recipeConfig>
<recipeStructures> <!-- recipe template/ recipeStructureTypes-->
<recipeStructureDef mnemonic="BREAD" title="Recipe.Bread"/>
<recipeStructureDef mnemonic="CAKE" title="Recipe.Bread"/>
<recipeStructureDef mnemonic="PANCAKE" title="Recipe.Bread"/>
</recipeStructures>
<preDefinedRecipes>
<preDefinedRecipe type="BREAD" name="sweet bread" ordinal="1" writerLevel="Service">
<parameterDef ref="SUGAR_QTY" value="3" />
<parameterDef ref="SALT_QTY" value="3" />
<parameterDef ref="OIL_QTY" value="1" />
</preDefinedRecipe>
</preDefinedRecipes>
</recipeConfig>
I want to check if the <preDefinedRecipe type="BREAD">
is always a value of mnemonic attribute from recipeStructureDef mnemonic= ""
I am stuck here and i dont know how to proceed.Below is my part of code form XSD
<xs:complexType name="preDefinedRecipeType">
<xs:sequence>
<xs:element type="preDefinedRecipeParameterDefType" name="parameterDef" maxOccurs="unbounded" minOccurs="0"/>
</xs:sequence>
<xs:attribute type="xs:string" name="type" use="required"/>
<xs:attribute type="xs:string" name="name" use="required"/>
<xs:attribute type="xs:byte" name="ordinal" use="required"/>
<xs:attribute type="xs:string" name="writerLevel" use="required"/>
</xs:complexType>
Thanks in advance for the help
if condition true, print 1st sentence and then print 2nd sentence it condition true
I have a diff result like below from Python's diff lib-
- "text": "abc xyz efg "
+ "text": "abc xyz efg"
- "header": true,
? ^^^
+ "header": false,
? ^^^^
- "text": "1.1 bacdefg"
- },
- {
- "header": false,
- "This is one example sentence which needs to be extracted."
? -------------- -
+ "This is one example sentence which needs to be extracted."
? + ++++++++++
- "This is one example sentence which needs to be extracted."
? -------------- -
+ "This is one example sentence which needs to be extracted."
? ++++++++++ +
+ "header": true,
+ "text": "some text"
I need to extract lines on three ways-
- which starts with "-" and the following line starts with "?" in a list named updated
- which starts with "+" and no "?" in the consecutive sentence in a list named deleted
- which starts with "-" and no "?" in the consecutive sentence in a list named inserted
header : true / false can be ignored
I am new to Python and I somehow managed to parse two PDFs to JSONs and do a diff using difflib but unable to write a for loop and if condition to look for the consecutive lines of only text fields.
EDIT-
diffile=[]
diff = difflib.Differ()
for line in diff.compare(f1_text, f2_text):
#json.dump(line,f, indent=2)
if line.startswith(("-", "+", "?")):
diffile.append(line)
updated=[]
for i in range(len(diffile) - 1):
value = diffile[i:i+2]
for line in value:
if line.startswith (("-")) and line.startswith ("?"):
updated.append (line)
I did the above but I am not able to extract only the next line starting with "?" after "-". It is giving me all the lines starting with "?".
Error ifelse statement, fread and within function: If you wish to 'recycle' the RHS please use rep()
I'm trying to do the following ifelse statement. My purpose is to create a new column in which I can identify individuals that have the same value in four columns.
example<-data.frame(replicate(4,sample(1:2,20,rep=TRUE)))
within(example,example$X <- ifelse(example$X1!=example$X2,NA,
ifelse(example$X2!=example$X3,NA,
ifelse(example$X3!=example$X4,NA,example$X1))))
In my case, the four columns are years. I want to identify panel individuals. With my data the code is the following:
within(educ_1,educ_1$X <- ifelse(educ_1$N2014!=educ_1$N2015,NA,
ifelse(educ_1$N2015!=educ_1$N2016,NA,
ifelse(educ_1$N2016!=educ_1$N2017,NA,educ_1$N2014))))
However, I'm getting the following error:
Error in
[<-.data.table
(*tmp*
, , nl, value = list(educ_1 = list(PER_ID = c(9.95048326217056e-313, : Supplied 67 items to be assigned to 14191305 items of column 'educ_1'. If you wish to 'recycle' the RHS please use rep() to make this intent clear to readers of your code.
One thing though is that I used fread function to import the data, since it is about 14millions observations then I thought it would be more efficient.
Any thoughts or suggestions about the syntax or the error? What should I do?. Why does it work with simple statements but not with my own data?
Thanks for your help :)
Problem in taking difference in timestamp
I have a timestamp column for 30 seconds resolution for 10 days. I want to take a difference between them, but difference between them should be zero when date changes. I have written below code but it is not giving me the solution i require
for i in range(len(df1)-1):
if (df1.iloc[i+1, 22] == df1.iloc[i, 22]):
df1.ix[i+1, ['Time']] = df1.iloc[i+1, 24] - df1.iloc[i, 24]
else:
df1.ix[i+1, ['Time']] = np.nan
I have seperated date and time into sepereate columns df1.iloc[i+1, 22] is the date column, df1.iloc[i+1, 24] is the time column
How can i Proceed?
Google Sheets multiple conditions with nested If statements?
I'm really struggling with this formula, but I think I'm overthinking it. I'm not sure what's the proper way to write this:
What I want to happen is: If cell A1 = John AND cell B1 = Buyer then take the dollar amount in C1 and multiply it by 10% ELSE If cell A1 = John AND cell B1 = Seller then take the amount in C1 and multiple it by 25% BUT If A1 is NOT equal to John, then return a currency value of $0
I sincerely appreciate any help. Thank you! Lisa
Way to check if a thread is null or not (in Java), does operand position makes difference [duplicate]
NOTE: I went through these but didn't get my answer Best way to check for null values in Java? and (obj == null) vs (null == obj)?
I was studying this Android [Java] official documentation on Background Tasks -> Run code on a thread pool thread -> Interrupt running code, and the null check code in the sample is:
if (null != thread) {
thread.interrupt();
}
which is different from what we usually see/use:
if (object != null) {
//do something;
}
So, my question is that:
Does it make any difference (like helping avoid null pointer or something) if we write "null != thread" instead of "thread != null" or Google Official documentation is just randomly swapping the operands without any benefit?
EDIT:
- I am asking about != and not ==. In case of ==, the programmer may do assignment(=) instead of comparison(==). But that is not the case in !=.
- I am talking about Java and not C language. So, that assignment and comparison confusion doesn't apply here.
Any possible way to check for a condition without using any of control statements in R
if(x == y){
text <- "string_1"
}else if(x < y){
text <- "string_2"
}else if(x > y){
text <- "string_3"
}
Is there any possible way that i could get rid of these clauses ? Can we use any mathematical operation to find out?
Using If statement in a pandas data set [duplicate]
I have been trying to use an if statement for a pandas dataset, but I keep getting this error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
My code:
if (df['Year'] == 2013):
print(df['Name'])
Angular 5 - How to build an object with several key's and values
Im trying to build an object that is going to have a key and its values:
const codeRed = this.orderInProgressCmsModel.orderStatusColorRed.split(",");
const codeGreen = this.orderInProgressCmsModel.orderStatusColorGreen.split(",");
const testObj = { colorName: "", colorCodes: []};
Im doing the following to add the information to the object itself:
testObj.colorName = "red";
testObj.colorCodes = codeRed;
testObj.colorName = "green";
testObj.colorCodes = codeGreen;
Doing it this way though will only add the last two into my object as its overwriting.
The purpose is that im trying to refactor the following code to avoid using so many if's and trying to get the same result with a more logical approach if possible:
if(codeRed.some(s => s.includes(code))){
this.orderStatusColor = JSON.parse('{"color": "red"}');
}
if (codeGreen.some(s => s.includes(code))){
this.orderStatusColor = JSON.parse('{"color": "green"}');
}
if (codeBlack.some(s => s.includes(code))){
this.orderStatusColor = JSON.parse('{"color": "black"}');
}
Suggestion to Reduce Number of code lines - Unix
I am trying to update the file permission oftest_1.txt
available as content inside the main file test.txt
based on the value available in the variable IN
. Below script will help to modify the content as per my requirement. But I need to reduce the number of lines of code. so could you suggest any way to reduce the number of lines and achieve the same output.
Code
#!/bin/bash
IN=750
Input=test.txt
Char_one=$(echo $IN | cut -c 1)
Char_two=$(echo $IN | cut -c 2)
Char_three=$(echo $IN | cut -c 3)
if [[ "$Char_one" == "7" ]]; then
Char_one="rwx"
elif [[ "$Char_one" == "6" ]]; then
Char_one="rw-"
elif [[ "$Char_one" == "5" ]]; then
Char_one="r-x"
elif [[ "$Char_one" == "4" ]]; then
Char_one="r--"
elif [[ "$Char_one" == "3" ]]; then
Char_one="-wx"
elif [[ "$Char_one" == "2" ]]; then
Char_one="rwx"
elif [[ "$Char_one" == "1" ]]; then
Char_one="-w-"
elif [[ "$Char_one" == "0" ]]; then
Char_one="---"
fi
if [[ "$Char_two" == "7" ]]; then
Char_two="rwx"
elif [[ "$Char_two" == "6" ]]; then
Char_two="rw-"
elif [[ "$Char_two" == "5" ]]; then
Char_two="r-x"
elif [[ "$Char_two" == "4" ]]; then
Char_two="r--"
elif [[ "$Char_two" == "3" ]]; then
Char_two="-wx"
elif [[ "$Char_two" == "2" ]]; then
Char_two="rwx"
elif [[ "$Char_two" == "1" ]]; then
Char_two="-w-"
elif [[ "$Char_two" == "0" ]]; then
Char_two="---"
fi
if [[ "$Char_three" == "7" ]]; then
Char_three="rwx"
elif [[ "$Char_three" == "6" ]]; then
Char_three="rw-"
elif [[ "$Char_three" == "5" ]]; then
Char_three="r-x"
elif [[ "$Char_three" == "4" ]]; then
Char_three="r--"
elif [[ "$Char_three" == "3" ]]; then
Char_three="-wx"
elif [[ "$Char_three" == "2" ]]; then
Char_three="rwx"
elif [[ "$Char_three" == "1" ]]; then
Char_three="-w-"
elif [[ "$Char_three" == "0" ]]; then
Char_three="---"
fi
while IFS= read -r line;
do
j=1
perm_1=$(echo $line | awk '{print $1}' | cut -c 2-4)
perm_2=$(echo $line | awk '{print $1}' | cut -c 5-7)
perm_3=$(echo $line | awk '{print $1}' | cut -c 8-10)
Def_Chmod=$(echo "$line" | sed -i "$j s/$perm_1$perm_2$perm_3/$Char_one$Char_two$Char_three/;" "$Input")
j=$((j+1))
done <"$Input"
test.txt
-rwxrwxr-x test_1.txt
Output
Content of the test.txt
file after the execution of the above code.
-rwxr-x--- test_1.txt
Is there any turnery operator for just single if condition in dart?
In dart we have plenty of turnery operators. But do we have one turnery operator just for if condition?
Example
In condition
if(num == 1){
print(true);
} else {
print(false);
}
In turnery
print(num == 1 ? true : false );
So do we have any turnery operator just for true condition like above example?
if(num == 1){
print(true);
}
mercredi 29 janvier 2020
How would i find a location of an item using VLOOKUPS?
on Sheet 1 i have a list of items and when they have been delivered to a certain location On Sheet 2 i have a list of items and i need to find out where that item is.
For Example: on sheet 1 item 1 has been delivered to Location A then delivered to location B and item 3 has been delivered to location A but not taken to Location B. On sheet 2 it should tell me that item 1 is currently at Loaction B and item 3 is currently At location A (The "Item" Name will be mixed with Text, Numbers and Dashes. Ie. A-B34 )
Sheet 1
Column A = Item Column B = Delivered to Location A Column C - Delivered to Location B
A B C
+------------+------------+------------+ 1 | Item 1 | 28-01-2020 | 29-01-2020 | +------------+------------+------------+ 2 | Item 3 | 28-01-2020 | | +------------+------------+------------+ 3 | Item 4 | 28-01-2020 | | +------------+------------+------------+ 4 | Item 2 | 28-01-2020 | 29-01-2020 | +------------+------------+------------+
Sheet 2
Column A = Item Column B = Location
A B
+------------+------------+ 1 | Item 1 | Location B | +------------+------------+ 2 | Item 2 | location A | +------------+------------+ 3 | Item 4 | Location B | +------------+------------+
Thanks in advance
Optimize multiple if conditions for flag check
[Flags]
public enum PatternTypes
{
A = 1,
B = 2,
C = 4,
D = 8,
E = 16,
F = 32,
G = 64
}
patternsToFind
[this is PatternTypes
]: it is contain flags value to find number of pattern like A | B | E
that will return us A, B and E
pattern result in list
if patternsToFind.HasFlag(A) {find pattern A and add to list result}
if patternsToFind.HasFlag(B) {find pattern B and add to list result}
if patternsToFind.HasFlag(C) {find pattern C and add to list result}
if patternsToFind.HasFlag(D) {find pattern D and add to list result}
if patternsToFind.HasFlag(E) {find pattern E and add to list result}
like this, I have 20 pattern so what should i use to optimize it? Alternate to multiple if conditions. Either i have to write it 20 times.
input is a int and variable is a string, I want a action if the string is greater that the int in the if statement. python3.8
input
is a int and variable is a string, I want a action if the string is greater than the int in the if statement. I'm using python 3.8
name = input ("What is your name?")
print(name)
# print ("Yes or No")
age= input ("how old are you?")
if age >= 50:
print (name, "You are looking good for your age!")
else:
print(name, "You are getting old.")
print("Peace Out")
unable to append using if statement
I have three lists. I would like to append the list object onto 'filtered' list if the object contains "HP" or "LP." The output places all items of filenames onto 'filtered' instead. Unsure why this is occuring. Your insight would be appreciated!
filenames = ['HP PLEAS 56s Jazz.wav', 'HP PLEAS 57s groupLaughing.wav', 'HP
PLEAS 57s Guitar_2.wav', 'PLEAS 56s Jazz.wav']
filtered = []
original = []
for x in filenames:
if "LP" or "HP" in x:
filtered.append(x)
else:
original.append(x)
How to go up to a specific value, then go down and up again?
I'm a biologist and I'm building an incubator for cell cultures for an hypothesis that we want to test. We have already built the incubator, but I'm having trouble with the code. I want the incubator to go up to 21.5C, then go down to 20.5C and go up again to 21.5C, over and over.
I'm using an arduino, a temp sensor and a relay to detect the temperature and turn of and turn on the heating element.
The way I have my code, when I turn on the incubator, the relay turns on the heating element until the temp sensor detects 21.5C and then the realy turns off the heating element, but as soon as the temp goes down, it turns on the heating element again, so it stays at 21.5C all the time. I don't know how to make it cool down to 20.5C and go up to 21.5C again. Could you help me or point me to the right direction?
This is my code:
#include <math.h>
int pinOut = 10;
double Thermistor(int RawADC) {
double Temp;
Temp = log(10000.0*((1024.0/RawADC-1)));
Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
Temp = Temp - 273.15;
return Temp;
}
void setup() {
pinMode(10, OUTPUT);
Serial.begin(9600);
}
void loop() {
int val;
double temp;
val=analogRead(0);
temp=Thermistor(val);
Serial.print("Temperature = ");
Serial.print(temp);
Serial.println(" C");
if (temp >= 21.5){
digitalWrite(pinOut, HIGH);
}
else {
digitalWrite(pinOut, LOW);
}
delay(1000);
}
How can I nest an If statement in a substr function in R
I am trying to pull apart a numeric field into two parts so I can merge with another data set. The number of characters is 6 or 7 characters long. I was able to get the last characters easily enough, but now I need either the first one or two characters of the field, depending on how long it is. This was my stab at it, but I received a number of errors. Is it possible to nest an If statement like this? Or do I need to swap it and run an If statement in a loop with different assignment statements?
df$new_field <- as.numeric(substr(df$GEOID, 1 ,if(nchar(df$GEOID)=6){
return(1)
}
else{
return(2)
}))
how to add two or more images to the same slide in for loop python-pptx
I'm trying to add images into one slide using python pptx package.
How to add two images to one slide in python pptx
But I have difficulties with when I do this in a for loop;
let's say we have a bunch of pictures in the directory and we want to resize and add the current slide as we go along with the pictures in directory. When I have eagle
or hawk
in the directory resize & position them and put them into current slide and move the next one!
What I am getting is that each picture in different slides;
Here is my code look like;
from pptx import Presentation
from pptx.util import Inches
from pptx.util import Inches
img_path = 'r/D/test'
eagle_1.png, eagle_2.png .... eagle_5.png
hawk_1.png, hawk_2.png .... hawk_5.png
def ppt_generator(img_path):
prs = Presentation()
blank_slide_layout = prs.slide_layouts[6]
#slide = prs.slides.add_slide(blank_slide_layout)
for images in glob.glob(img_path + '/*.png'):
if 'eagle' in str(images):
slide = prs.slides.add_slide(content_slide_layout)
slide = slide.shapes.add_picture(images , left=Inches(0), top=Inches(0), width=Inches(3), height = Inches(3))
if 'hawk' in str(images):
slide = prs.slides.add_slide(content_slide_layout)
slide = slide.shapes.add_picture(images , left=Inches(2), top=Inches(2), width=Inches(3), height = Inches(3))
prs.save('eagle_hawk.pptx')
What I want to have is that for each eagle_1 and hawk_1 should be in the same slide and so on!
How can I do that?
PHP If Statement last value duplicating
I have a php if statement. For some reason it is duplicating multiple times the last statement. Also, I can't add anything after this section. It only multiplies the last statement if I add something after the if statement. I start the new statement with echo ' '; however, it still adds the last statement into the new section.
<?php
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo '<div class="object">';
if (empty($row['facebook'])) {
echo '';
}
else {
echo '<a class="fab fa-facebook" href='.$row['facebook'].' target="_blank">';
}
if (empty($row['twitter'])) {
echo '';
}
else {
echo '<a class="fab fa-twitter" href='.$row['twitter'].' target="_blank">';
}
if (empty($row['linkedin'])) {
echo '';
}
else {
echo '<a class="fab fa-linkedin" href='.$row['linkedin'].' target="_blank">';
}
if (empty($row['youtube'])) {
echo '';
}
else {
echo '<a class="fab fa-youtube" href='.$row['youtube'].' target="_blank">';
}
if (empty($row['instagram'])) {
echo '';
}
else {
echo '<a class="fab fa-instagram" href='.$row['instagram'].' target="_blank">';
}
if (empty($row['pinterest'])) {
echo '';
}
else {
echo '<a class="fab fa-pinterest" href='.$row['pinterest'].' target="_blank">';
}
echo '</div>';
}
}
mysqli_close($conn);
?>
Trying to use CalculateField in Python IDE to populate new field in geodatabase based on values in existing field
I am struggling with some code that I am writing to update a geodatabase feature class called "Grabs_WCVI". I have a new field called "SubModCat" that I want to populate with a ranking system using an if elif else statement based on values in an existing field called "BType". The values for BType can range from 1/1a/1b/2/2a/2b/3/3a/3b. I haven't used codeblocks before and I'm finding that the IDE accepts my local variables, but won't run my CalculateField function after, so there must be an error in there...
Here is my code so far:
# Set environment settings
arcpy.env.workspace = "C:\Users\gillespiek\Grabs_DataCleaning\All_BoP_Grabs_only.gdb"
# Set local variables
inTable = "Grabs_WCVI"
fieldName = "SubModCat"
expression = "newValue(!Btype!)"
codeblock = """def newValue(field):
val1 = [‘1’, ‘1a’, ‘1b’]
val2 = [‘2’, ‘2a’, ‘2b’]
if field in val1:
return 1
elif field in val2:
return 2
elif field == ‘3a’:
return 3
elif field == ‘3b’:
return 4
else:
return 0"""
# Execute CalculateField
arcpy.CalculateField_management(inTable, fieldName, expression, "PYTHON_9.3",
codeblock)
Can anyone see where I'm going astray? Any advice is greatly appreciated :
Is it bad practice to make a simple if-else statement not on one single line in Python?
At my internship I have noticed that another coworker of mine has manipulated one of my functions from doing this...
if isSinglesMatch:
name1 = GetName(1, “BUG”)
name2 = GetName(2, "BUG")
else:
name1 = GetName(1, "Short")
name2 = GetName(2, "Short")
to this...
name1 = GetName(1, "BUG" if isSinglesMatch else "Short")
name2 = GetName(2, "BUG" if isSinglesMatch else "Short")
I see that his code is shorter, but is there any advantage like it being interpreted faster? Is it bad to keep it the way I had it in the first place, because in my opinion it is easier to debug my code (there are a few extra variable assignments that I left out of this example).
No one at my internship has told me that I should change the way I do things, I just noticed that this is the way my coworker likes to do it.
Can I search a cell for specific text using IFS formula, and return text to current cell?
I was able to do this with a single IF formula, but cannot exactly figure out how to do it with IFS to search the same cell for different strings of text.
Here is the formula I am using for the single IF statement:
=IF(SEARCH("silver",B5),"silver","N/A")
It is searching cell B5 for the term "silver" and then if found it returns "silver". If not it returns N/A. I would like to be able to search cell B5 for different terms ("black","red","blue") using the IFS formula.
Thank you in advance!
how do i get recipient.count as value to add to if statement to change color on outlook calendar in vba?
I'm trying to get this code I found online that I modified to get my recipients.count value so I can add it into a if statement that will determine if there is one, two declines and change the calendar to a specific color based on the recipients declined count. I get the Compile Error: Can't assign to read-only property. If you can provide some help with this issue as I'm new to vba scripting and would like to get this to work. I'm using windows 10 with outlook 2016.
Sub CheckDeclines(oRequest As MeetingItem)
' only check declines
If oRequest.MessageClass <> "IPM.Schedule.Meeting.Resp.Neg" Then
Exit Sub
End If
Dim oAppt As AppointmentItem
Set oAppt = oRequest.GetAssociatedAppointment(True)
Dim myAttendees As Integer
Dim objAttendees As Outlook.recipients
Set objAttendees = oAppt.recipients
For x = 1 To objAttendees.Count
If objAttendees(x).Type = olRequired Then
oAppt.Categories = "Declined;"
objAttendees.Count = myAttendees
End If
Next
If myAttendees = 1 Then
oAppt.Categories = "Declined;"
oAppt.Categories = "Yellow Category"
Else
If myAttendees = 2 Then
oAppt.Categories = "Declined;"
oAppt.Categories = "Orange Category"
Else
oAppt.Categories = "Declined;"
oAppt.Categories = "Red Category"
End If
End If
oAppt.Display
End Sub
Using if and elif the right way
I have the following dataframe:
df1=pd.DataFrame([1,2,3], columns=["a"])
which results in:
a
0 1
1 2
2 3
I want to create column b where each value is a multiple (x2,x3,x4) of the respective number in column a. Desired output is like that:
a b
0 1 2
1 2 6
2 3 12
I try the following statement but obviously the behavior is not as expected.
for num in df1["a"]:
if a == 1:
df1["b"]=df1["a"]*2
elif a == 2:
df1["b"]=df1["a"]*3
elif a ==3:
df1["b"]=df1["a"]*4
when I run the above I get:
a b
0 1 2
1 2 4
2 3 6
help much appreciated
Creating new columns based on existing columns in R
This is a sample of my dataframe. It comes from a survey where the original question was: "Where are you located? Mark all that apply."
Code Option1 Option2 Option3 Option4
101 A C NA NA
102 B D NA NA
103 A B D NA
104 D NA NA NA
105 A B C D
I would like to transform this data so that each column is one of the locations and you get a 0/1 if you're located in any of the 4 locations:
Code A B C D
101 1 0 1 0
102 0 1 0 1
103 1 1 0 1
104 0 0 0 1
105 1 1 1 1
I tried using ifelse statements, but I kept getting errors. Any suggestions? Thanks!
Filling in a zero for all empty time bins for each cluster (region) as part of an ambulance response/posting analysis
I have a my data from an agencies ambulance responses. I have created clusters for locations they respond from and created time bins to divide the time into manageable bins. I then grouped the data by cluster and then by bin and have the number of incident per cluster per bin aggregated into a column as well. I need to fill in zeros for all the time bins where no incidents occurred in the incident count column. I have tried a nested for loop with an if else to make it work. It runs too slowly and I am trying to find a way to switch to a nested list comprehension with the if else statements.
count_values = ers_bin_groupby['no_of_incidents'].values
vals = ers_unique
"ers_unique" is a list of all the unique time bins for each cluster
def fill_missing(count_values,vals):
smoothed_regions=[]
ind=0 # ind iterates over count_values only
for p in range(0,posts):
smoothed_bins=[]
for i in range(max(minute_bin_create_times)):
if i in vals[p]:
smoothed_bins.append(count_values[ind])
ind+=1
else:
smoothed_bins.append(0)
smoothed_regions.extend(smoothed_bins)
print(p)
return smoothed_regions
This is my attempt at a list comprehension with if statement
def fill_missing2(count_values, vals):
smoothed_regions = []
ind = 0 #ind iterates over count_values only
smoothed_regions =[[count_values[ind] ind+=1 if i in vals[p] else 0
for i in range(max(minute_bin_create_times))]
for p in range(0,posts)]
I can't figure out if I still need the "ind+=1" to make it progress through the count_values
Here is an example of the groupby data I am working with there are 20 posts and over 500,000 time bins
post_area time_bin
0 7 1
59 1
104 1
113 1
117 1
147 1
249 1
255 1
This is an example of the ers_unique list [[7, 59, 104, 113, 117, 147, 249, 255, 277, 283, 292, 310, 312, 358, 393, 406, 480, 537, 550, 553, 622,
MySQL Else If Statement not Executing
No matter what MySQL PROCEDURE I create, the 2nd ELSE IF statement returns zero results. Each Select statement when ran separately returns a result. I don't see an issue with my syntax. I apologize if it is a simple fix. Please help.
DELIMITER $$
CREATE PROCEDURE TEST(type VARCHAR(7), cat TINYINT)
BEGIN
IF type = 'coffee' THEN
Select * FROM specific_coffee WHERE id=cat;
ELSEIF type = 'goodies' THEN
Select * FROM non_coffee_products WHERE id=cat;
END IF;
END $$
Comparing Cells with IF Statement with 3rd Outcome
I'm making a Rugby Predictor spreadsheet for a specific game my friend created. Take the following example:
Wales 35 Italy 10
So in this game, if you predict the winner you get 2 points.
However, you can predict a Draw which would get you 3 points.
I have outputted the winner of the above game into a field in itself, for arguments sake, lets say it's in the cell G5.
I'm trying to compare the cells containing people predictions to give you points. Lets say the persons prediction is in the cell C10.
Below is my attempt at the code, which works for a Draw predicition.
=IF(AND(C10="Draw",G$5="Draw"),"3", IF(C10=G$5, "2", "0"))
However, the logic should be:
IF Prediction is correct output 2, IF Prediction is wrong output 0, IF Prediction = "Draw" AND correct output 3
Can someone help me with the logic in Excel? Please let me know if you need further clarity.
Conditional statement on None in Python
PFB the program. In that we have a condition block if curr > max_v or max_v == None:
. This is giving an error
TypeError: '>' not supported between instances of 'int' and 'NoneType'
However, if I change the condition to max_v == None or curr > max_v:
it works fine. What is the issue here. Please advice.
arr_ele = []
for arr_i in range(6):
arr_t = [int(arr_temp) for arr_temp in input().strip().split()]
arr_ele.append(arr_t)
length = len(arr_ele[0])
max_v = None
curr = 0
for i in range(length-2):
for j in range(length-2):
curr = arr_ele[i][j] + arr_ele[i][j+1] + arr_ele[i][j+2] + \
arr_ele[i+1][j+1] + \
arr_ele[i+2][j] + arr_ele[i+2][j+1] + arr_ele[i+2][j+2]
if curr > max_v or max_v == None:
max_v = curr
print(max_v)
validate multiple variables without writing multiple if else statements
Lets say we have 3 variables and I want to check them empty or not without using multiple if else blocks.
let firstName = "adem"
let lastName = "corona"
let email = "adamcorons@gmai.com"
If(firstName === " " && lastName !== " " && email !== " "){
Console.log("first name empty")
} else if .......
What is the best way of solving this? Thanks a lot
how can i make a new Dataframe use for and if function in python
First of all i'm sorry i'm not good at English. but i'll do my best exaplain what i faced problem. if you help me i will very Thank you.
i want make a new dataframe using by another dataframe
for example
month product_no sale_price quantity sale_rate
6 a1 100 2 10%
6 a2 200 1 20%
6 a3 150 2 30%
6 a4 50 4 0%
7 a1 100 1 0%
7 a2 200 3 20%
8 a3 150 4 30%
8 a4 50 2 50%
i want make like this. using for and if function.
month 6 7 8
sale unique_product quantity 3 1 2
sale quantity 5 3 6
gmv 700 600 700
non_sale unique_product quantity 4 1 0
sale quantity 1 1 0
gmv 200 100 0
i tried like this. but it's not working
sale = []
non_sale = []
months = [6,7,8,9,10,11,12]
for i in months :
if made_data[(made_data.month == i) & (made_data.sale_rate== 0)] :
non_sale.append(len(made_data[(made_data.month == i) & (made_data.sale_rate == 0)].product_no.unique()))
elif made_data[(made_data.month== i) & (made_data.sale_rate!= 0)] :
sale.append(len(made_data[(made_data.month== i) & (made_data.sale_rate== 0)].product_no.unique()))
Inline if statement inside foreach loop
Is there any way you can do something like this without using the usual If syntax?
foreach (var cell in ws.Cells[header_row, 1, header_row, ws.Dimension.End.Column])
{
cell.Address == "SomeValue" ? break : continue;
}
Visual Studio doesn't seem to allow an inline If statement with this kind of results.
What am I doing wrong? Or is it actually not possible?
Thanks.
React Checkbox to trigger regex expression
I'm working on a small search component that highlights text if it matches a word search (just for better understanding, I know there are libraries out there that do this.)
I can't seem to get my RegExp to trigger the i (case sensitive) parameter upon clicking a checkbox.
Attaching my code - built using create-react-app.
import React, { useState } from "react";
import './highlighter.css';
const Highlighter = (props) => {
const [value, setValue] = useState("");
const [searchValue, setSearchValue] = useState("");
const [checked, setChecked] = useState(false);
const [sensitive, setSensitive] = useState("i");
let highlight = null;
const handleChange = (event) => {
setValue(event.target.value);
};
console.log(value);
const handleSearchChange = (event) => {
setSearchValue(event.target.value);
};
console.log(searchValue);
const getHighlightedText = (value, searchValue) => {
let regex = new RegExp(`(${searchValue})`, `g${sensitive}`);
console.log(regex);
const parts = value.split(regex);
//console.log(parts);
highlight = <span> { parts.map((part, i) =>
<span key={i} style={part === searchValue ? { backgroundColor: 'Yellow' } : {} }>
{ part }
</span>)
} </span>;
}
const checkedTest = () => {
if(checked === true) {
setSensitive(" ") // makes it case sensitive
console.log(sensitive);
setChecked(true);
} else {
setSensitive("i")
console.log(sensitive);
setChecked(false);
}
}
return (
<>
<form className="text-search-form">
<textarea className="source-text" value={value} onChange={handleChange}/>
<input className="search-term" value={searchValue} onChange={handleSearchChange} onKeyPress={getHighlightedText(value, searchValue)} />
<label htmlFor="caseSensitive">case sensitive?
<input
type="checkbox"
className="case-sensitive"
name="caseSensitive"
defaultChecked={checked}
onClick={getHighlightedText(value, searchValue)}
onChange={checkedTest}
/>
</label>
</form>
<div className="result">{highlight}</div>
</>
);
};
export default Highlighter;
Expected result: When checkbox is NOT checked, regex expression searches the textarea and finds all copies of the searched word in the input. Upon clicking the checkbox, make the search case sensitive.
I'm newer to react, so if you see a better approach please let me know.
P.S. trying to use functional components
Use if statement to modify row value
I have a dataframe ddd
with a field date
containing messy date values as text:
ddd= pd.DataFrame([["80's of 1900"], ["80's of the 19th century"], ["90's of the 18th century"], ["1955"], ["1822"]], columns=['date'])
In [2]: ddd
Out[2]:
index date
0 80's of 1900
1 80's of the 19th century
2 90's of the 18th century
3 1955
4 1822
What I'm trying to do is to transform text values to a year like in row 3 and 4 for further analyses. To do so in wrote a for loop with an if statement to differentiate rows like 0 and 1, 2.
So far, I have a code that makes a numpy array of indexes where the field date
contains 's of
to iterate over those rows:
selected_index = ddd[ddd["date"].str.contains('\'s of')].index.values
And a for loop with some regex to rearrange numbers in the string and to change '80's of 1900' to 1980 and '90's of the 18th century' to 1790:
for index in selected_index:
if ddd.at[index, 'date'].str.contains('th century')]:
num = re.findall('[0-9]', ddd.at[index, 'date'])
num2 = ''.join(num)
num3 = str(num2)[2:4]
num4 = int(num3) - 1
num5 = str(num4)
num6 = str(num2)[:2]
ddd.at[index, 'date'] = num5 + num6
else:
num = re.findall('[0-9]', ddd.at[index, 'date'])
num2 = ''.join(num)
num3 = str(num2)[:2]
num4 = str(num2)[2:4]
ddd.at[index, 'date'] = num4 + num3
But I get the following error:
AttributeError: 'str' object has no attribute 'str'
Expected output:
index date
0 1980
1 1880
2 1790
3 1955
4 1822
Thank you in advance for your suggestions!
Loop with increment VBA Macro Excel
this is my first post on the community and i'm hoping for it to be useful for me as well for other members.
I know that this question has been asked many times on this forum, but everyone got a different situation.
I'm trying to create a Macro that would calculate the number of hours from a range of cells. If they match the number i put on my condition then it's good to go, if not i want to display a msgbox or catch the error.
A quick look of the excel template
This is the code of my existing Macro, but i only managed to calculate the first range, i want to add a loop that would calculate the number of hours for every existing column: Which could be variant from 1 day to 31 days depending on the person using the excel template.
The number of projects could vary too "Code OTP" from 1 to 10 projects.
Sub SommeEnVBA_1b()
MaColonne = 2 '(= colonne "B")
MaPremiereLigne = 8
MaDerniereLigne = 1000
Dim i As Integer
MaSomme = 0
For UneLigne = MaPremiereLigne To MaDerniereLigne
MaSomme = MaSomme + Cells(UneLigne, MaColonne).Value
Next UneLigne
If MaSomme = "8,8" Then
MsgBox "Les heures entrées sont correctes : " & MaSomme
Else
MsgBox "Les heures entrées sont incorrectes"
End If
End Sub
If statement in react function
I have 2 inputs with minimum and maximun number range, and I'm trying to use if statement so if user puts in the minimun input value that is higher from the maximun input, it will reset the input to be equal to the maximum. Why it's not working in the function minRangeInputChange?
class Generator extends React.Component {
constructor (props) {
super(props)
this.state = {
onView: '0',
minNum: 0 ,
maxNum: 100
}
}
btnClick = () => {
const { minNum, maxNum } = this.state;
const min = Math.ceil(minNum);
const max = Math.floor(maxNum);
const x = Math.floor(Math.random() * (max - min + 1)) + min;
return this.setState({ onView : x });
}
minRangeInputChange = (event) => {
const { minNum, maxNum } = this.state;
if (minNum > maxNum) {
return this.setState({ minNum: maxNum });
} else {
return this.setState({ minNum: event.target.value });
console.log(minNum);
}
}
maxRangeInputChange = (event) => {
const { maxNum } = this.state;
this.setState({ maxNum: event.target.value });
}
render() {
return (
<div className="container">
<Instructions />
<Range
max={this.state.maxNum}
min={this.state.minNum}
minChange={this.minRangeInputChange}
maxChange={this.maxRangeInputChange}
/>
<Generate currentClick={this.btnClick} />
<View show={this.state.onView} />
</div>
);
}
}
export default Generator;
The Range Component:
class Range extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div className="range">
<h3>Minimum</h3>
<input
type="number"
value={this.props.minNum}
onChange={this.props.minChange}
required
/>
<h3>Maximum</h3>
<input
type="number"
value={this.props.maxNum}
onChange={this.props.maxChange}
required
/>
</div>
);
}
}
export default Range;
Make script wait for an input number [duplicate]
When I use i=input nothing happens (no error, the robot just won't read the pressed 1 and go to the first loop). My guess is that input only waits for the user to press enter. Is there an equivalent for the user to press a specific number, to activate the if-loops below?
i=...?
if(i==1)
current_pose = dType.GetPose(api)
dType.SetPTPCmdEx(api, 2, x1, y1, z1, current_pose[3], 1)
i=i+1
if(i==2)
current_pose = dType.GetPose(api)
dType.SetPTPCmdEx(api, 2, x2, y2, z2, current_pose[3], 1)
i=i-1
conditional statement for logical output
I want to modify the following R code based on the logical output of the function.
is_x_prime = function(x){
vapply(x, function(z) sum(t / 1:t == t %/% 1:t), integer(1L)) == 2L
}
so that if the output is:
if(TRUE)
{ cat("The number", x," is prime.")}
else
{ cat("The number", x," is not prime.")}
I was not able to combine them.
Thanks
mardi 28 janvier 2020
If statement for Boolean comparison in C# [closed]
I'm writing a simple code to get value from local storage, check if it's true then execute some piece of code and if it's false, then don't execute the code. Although I'm receiving value as false, yet it goes into the loop and executes the code.enter image description here
If function for execution
How can I use if function to compare it to my timer and if lands to specific time it will execute my renaming command. If time == 12:00am then execute then it will wait again for next scheduled time.
javascript if statement does not work with razor
i have failed to validate if statement as shown in code below ,while i can get the value of "@Model.FreelancerProposals.Where(a => a.IsAssigned == true)"in html but cant validate if statement using the same value in javascript, what is your advice for this scenario.
<script>
if(@Model.FreelancerProposals.Where(a => a.IsAssigned == true).Count() > 0)
{
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
// Set the date we're counting down to
/**/
var countDownDate = new Date("@Model.FreelancerProposal.DateofRecord.Month, @Model.FreelancerProposal.DateofRecord.Day, @Model.FreelancerProposal.DateofRecord.Year @Model.FreelancerProposal.DateofRecord.Hour:@Model.FreelancerProposal.DateofRecord.Minute:@Model.FreelancerProposal.DateofRecord.Second").getTime();
countDownDate=addDays(countDownDate,@Model.FreelancerProposal.DaysRequired) /**/
// Update the count down every 1 second
var x = setInterval(function () {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "يوم " + hours + "س "
+ minutes + "د " + seconds + "ث ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "إنتهى الوقت المدد";
}
}, 1000);
}
</script>
What does !() mean in javascript
I just saw this construction for the first time in javascript
if (someConditionIsMet && !(anotherCondition && oneMoreCondition)) {
return something
}
There is a !() inside of the if-conditional statement. I'm wondering what exactly that does. Is it just a way of grouping several conditions together and making sure they all evaluate a certain way before triggering logic? If so, is this merely to simplify the appearance or is there some logical advantage here?
Returning certain rows which meet a criteria - Google Apps Script
What I am trying to do is: I have a list, with N being a date and O being a checkbox. I need to get the rows which =N < Today()
&& O=False
, then return A:B
of those corresponding rows. I've tried it every which way, and I can't get it to work. Any suggestions?
function msg1(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var wscl = ss.getSheetByName('Connection List');
var contact = wscl.getRange("A2:B").getValues();
var msg1date = wscl.getRange("N2:N").getValues();
var msg1sent = wscl.getRange("O2:O").getValues();
var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
var now = new Date();
var yesterday = new Date(now.getTime() - MILLIS_PER_DAY);
for(var i=0;i<msg1sent.length;i++){
if(msg1sent =="FALSE"&& msg1date < yesterday){
var row=i+1;
}
}
}
How can I validate if a given number is integer or not in Javascript?
I'm currently validating a form with JavaScript in which the user has to type their id number . I already figure out how to validate if the value is numeric, but I'm struggling to find a way to validate if the given number is integer or not. Thanks for helping me out.
if statement GoogleSHeet
i have transferred this xls into G SHeets but the IFs dont work in Cells U9 onwards. I know the tick boxes dont work because of no WIngdings in Google however if we enter R for a student in cells E9, F9 G9 etc, eventually U9 should say Pass. More R's along the row means U9 should say Merit etc
https://drive.google.com/file/d/117n553pXdiaC7MEOZ3xGphmrXJn50L_s/view?usp=sharing
How to append an item in a list for use later in a If-statement
I'am creating a text-based game, and I have a problem when I try to add a Knife to pass to the Forest. My idea is that the gamer, need to use the 'C' option to add a Knife to the inventory. And use that Knife to pass to the forest in 'B' option. Any solution please?
a1 = input('What you want to do? \nCheck some rock around you(A) \nGo to the Forest(B) \nSee around of the beach in the island(C) \n\n')
obj = []
def addknife():
obj.append('Knife')
if a1.capitalize() == 'A':
print()
print('It is nothing else than a rock.')
elif a1.capitalize() == 'C':
print()
print('Walking for the beach, you encountered a Knife.')
addknife()
print(obj)
elif a1.capitalize() == 'B':
if 'Knife' in obj:
print('You can go to the forest.')
else:
print('The plants do not allow you to pass.')```
Problem when writing a loop for a dataframe
I have a dataframe with two columns 'ENTRYP' and 'Status'. If the value of ENTRYP is less than or equal to 0.02, it should change the 'status' to 'ENT_EXT'. Every time it crosses that range it should add count to the Status. For example: movement1, ent_ext1, movement2, ent_Ext2. I have written the below code but it is throwing the below error
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
h_count = 0
current = "ENT_EXT"
current == "MOVING"
status_halt = []
for idx in df2.index:
if (df2["ENTRYP"][idx] <= 0.02):
if current == "MOVING":
h_count += 1
status_halt.append(f"ENT_EXT{h_count}")
current = "ENT_EXT"
elif (df2["ENTRYP"][idx] > 0.02):
if current == "ENT_EXT":
m_count += 1
status_halt.append(f"MOVING_{m_count}")
current = "MOVING"
df2["Status"] = status_halt
I have added the snippet of the dataframe and required output.
Please let me know how to proceed https://i.stack.imgur.com/K0Qsj.png
Can only compare identically-labeled Series objects error with if statement - Python
I'm attempting to run an if statement to match the country of origin of marathon winners to theirs countrie's gdp data. I am getting the error 'Can only compare identically-labeled Series objects'.
if df['Winner Country'] == gdp_data['Country']:
if df['YEAR'] == 1970 :
df['gdp'] = gdp_data['1970 gdp/cap']
gdp_data example:
Country 1970 gdp/cap
Kenya 98
df example:
YEAR Winner_Name Winner_Country Time Gender
1977 Dan Cloeter USA 2:17:52 M
I intend to assign a gdp value to df based off both country and year(I only included partial data, there are extra columns for each year in the gdp_data datarame).
How do I make a formula with Mulitple IF statements in seperate cells?
I want to make a formula that sums IF C36:C160 = "Text" and if E36:H160 = "Some other text"/2
Hope this makes sense!
-SUM.IF(E36:H160;"*LAURAS*";A36:A160)/2
basicly this with the added C36:C160="Mad"
Dplyr, filtering groups if any value in vector list exists
I want to filter out by a grouping variable if any of a vector of values in a variable exist in the group, i.e. there may be no groups where any variable is (Value V) V1, V2 or V3.
E.g. There may remain no groups wherein a tree which is susceptible to disease strain/ injury type V1, V2 or V3 is present.
However, my calls keep being interpreted: There may remain no trees in a group which is susceptible to disease strain/injury type V1, V2 or V3.
Example 1:
df %>% group_by(tree_group) %>%
filter(any(!(tree_condition %in% c("Significant","Severe","Dead or dying")))) %>%
filter(any(!(injury_type_1 %in% c("Significant","Severe","Dead or dying")))) %>%
filter(any(!(injury_type_2 %in% c("Significant","Severe","Dead or dying")))) %>%
filter(any(!(injury_type_3 %in% c("Significant","Severe","Dead or dying"))))
Example 2:
df %>% group_by(tree_group) %>%
filter(!(any(tree_condition %in% c("Significant","Severe","Dead or dying")))) %>%
filter(!(any(injury_type_1 %in% c("Significant","Severe","Dead or dying")))) %>%
filter(!(any(injury_type_2 %in% c("Significant","Severe","Dead or dying")))) %>%
filter(!(any(injury_type_3 %in% c("Significant","Severe","Dead or dying"))))
Both example 1 and example 2 yield the same result - damaged trees being removed from the groups, not incident groups being removed from the call.
I also tried, without succeeding, to create a variable (DAMAGED) to mark all trees in the group with 1, for susceptible if one member was susceptible, and else 0:
df %>%
group_by(tree_group) %>% mutate(if (tree_condition %in% c("Significant","Severe","Dead or dying")){
DAMAGED=1
} else if(injury_type_1 %in% c("Significant","Severe","Dead or dying")) {
DAMAGED=1
} else if(injury_type_2 %in% c("Significant","Severe","Dead or dying")) {
DAMAGED=1
} else if(injury_type_3 %in% c("Significant","Severe","Dead or dying")) {
DAMAGED=1
} else {
DAMAGED=0
})
However, this throws an condition as:
1: In if (tree_condition %in% c("Significant", "Severe", "Dead or dying")) { :
the condition has length > 1 and only the first element will be used
2: In if (injury_type_1 %in% c("Significant", "Severe", "Dead or dying")) { :
the condition has length > 1 and only the first element will be used
3: In if (injury_type_2 %in% c("Significant", "Severe", "Dead or dying")) { :
the condition has length > 1 and only the first element will be used
4: In if (injury_type_3 %in% c("Significant", "Severe", "Dead or dying")) { :
the condition has length > 1 and only the first element will be used