I want to set a variable in Python to true or false. But the words true and false are interpreted as undefined variables:
#!/usr/bin/python
a = true;
b = true;
if a == b:
print("same");
The error I get:
a = true
NameError: global name 'true' is not defined
What is the python syntax to set a variable true or false?
Python 2.7.3
First to answer your question, you set a variable to true or false by assigning True or False to it:
myFirstVar = True
myOtherVar = False
If you have a condition that is basically like this though:
if <condition>:
var = True
else:
var = False
then it is much easier to simply assign the result of the condition directly:
var = <condition>
In your case:
match_var = a == b
match_var = a==b
that should more than suffice
you cant use a - in a variable name as it thinks that is match (minus) var
match=1
var=2
print match-var #prints -1
Python boolean keywords are True and False, notice the capital letters. So like this:
a = True;
b = True;
match_var = True if a == b else False
print match_var;
When compiled and run, this prints:
True
you have to use capital True and False not true and false
as Poke said:
If you have a condition that is basically like this though:
if <condition>:
var = True
else:
var = False
then it is much easier to simply assign the result of the condition
directly:
var = <condition>
but if you want to reverse it you can use:
var = <condition> is False
Related
I have the following table created in a Dashboard:
Name Exist in AD Exist in EDR Exist in ASDF
A TRUE TRUE TRUE
B TRUE TRUE TRUE
C FALSE FALSE TRUE
Every field cames from a different tables. I would like to calculate in a dashboard a new column with the following result:
New Column = AND (Exist in AD,(OR(Exist in EDR,Exist in ASDF))
You can use the following DAX:
New Column =
var nameVar = table[Name]
var existAD = CONTAINS(AD, AD[columnNameAD], nameVar)
var existEDR = CONTAINS(EDR, EDR[columnNameEDR], nameVar)
var existASDF = CONTAINS(ASDF, ASDF[columnNameASDF], nameVar)
return existAD && (existsEDR || existsASDF)
Caintais returns true if Name of the variable in the Row exists in other table in that column.
At the end I put it logic together..
I've got a bunch of documents with disparate styles that I've been adding to a long Macro that finds and replaces these styles with the correct ones. Right now, I'm just adding to a list as I find a wrong style. For example, there can be Heading 1, heading 1, H1, or h1. I want to write a find and replace function for each of those for the moment. What would be cooler is if I could write a catch all macro for these sorts of things using Regex: (h|H).{6}\s1 (not the best Regex writer, so bear with that). Ideally that would catch anything the variations of heading 1 (though it would not catch the h1, H1 cases, though I could add that easily enough.
I know that VBA supports Regex. I've added the reference to it. I also know how this would work for replacing specific text. I'm not replacing text though. ONLY formatting. I haven't played around with it too much. I just want to know if I can use the Regex when working specifically with a style. Here's what the functions look like right now:
Selection.Find.ClearFormatting
Selection.Find.Style = ActiveDocument.Styles("Heading 1")
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Style = ActiveDocument.Styles("SSC TOC 2")
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
I simply recorded that. Now, would I be able to put Regex in place of that string, like so:
Selection.Find.ClearFormatting
Selection.Find.Style = ActiveDocument.Styles(someRegex function (h|H).{6}\s1)
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Style = ActiveDocument.Styles("SSC TOC 2")
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Basically just using a function someRegex function (h|H).{6}\s1 in place of the string literal. Is there any way to do this? Would appreciate any guidance or help!
You could use something along the lines the following macro to delete all unused user-defined Styles (except Linked Styles) in a document, and to clean up the various H1, etc. Styles you mentioned:
Sub CleanUpStyles()
Application.ScreenUpdating = False
Dim Doc As Document, bDel As Boolean, bHid As Boolean
Dim Rng As Range, StlNm As String, i As Long
bHid = ActiveWindow.View.ShowHiddenText
ActiveWindow.View.ShowHiddenText = True
Set Doc = ActiveDocument
With Doc
For i = .Styles.Count To 1 Step -1
With .Styles(i)
If .BuiltIn = False And .Linked = False Then
bDel = True: StlNm = .NameLocal
For Each Rng In Doc.StoryRanges
With Rng
With .Find
.ClearFormatting
.Format = True
.Style = StlNm
.Execute
End With
If .Find.Found = True Then
If StlNm Like "[Hh]*#" Then
If StlNm <> "Heading " & Right(StlNm, 1) Then
.Style = "Heading " & Right(StlNm, 1)
bDel = True
End If
Else
bDel = False
End If
Exit For
End If
End With
Next
If bDel = True Then .Delete
End If
End With
Next
End With
ActiveWindow.View.ShowHiddenText = bHid
Application.ScreenUpdating = True
End Sub
Sub UpdateDMDCLCSIM()
Dim SIM_DM_DCLC As Worksheet
Dim TextFileUpdated As Date
Set SIM_DM_DCLC = ThisWorkbook.Sheets(Sheet52.Name)
TextFileUpdated = DateValue(FileDateTime("\\networkshare\dept\DCGSI\Extracts\SIM_DM_DCLC.csv"))
Application.DisplayAlerts = False
Application.StatusBar = "Importing latest DM DCLC SIM Data..."
With SIM_DM_DCLC.QueryTables.Add(Connection:= _
"TEXT;\\networkshare\dept\DCGSI\Extracts\SIM_DM_DCLC.csv" _
, Destination:=SIM_DM_DCLC.Range("$A$1"))
.Name = "SIM_DM_DCLC"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 936
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
'Change to MySQL date format.
SIM_DM_DCLC.Range("I:K", "P:T").Replace Chr(84), " "
SIM_DM_DCLC.Range("I:K", "P:T").Replace Chr(90), ""
SIM_DM_DCLC.Range("I:K", "P:T").NumberFormat = "yyyy-mm-dd hh:mm:ss"
Okay so this opens a csv that is downloaded to a network share and fixes some dates. The dates in the original file are formatted YYYY-MM-DDTHH:MM:SSZ and this is supposed to strip the T and Z from those dates in the appropriate columns. The issue I am having is that for some strange reason it is processing column L in the file and I can't figure out why.
So I looked up some code for regex replace in VBA and tried to refactor the code to use the following code to try and fix the issue:
Sub UpdateDMDCLCSIM()
On Error GoTo ErrorHandler
Dim SIM_DM_DCLC As Worksheet
Dim TextFileUpdated As Date
Set SIM_DM_DCLC = ThisWorkbook.Sheets(Sheet52.Name)
TextFileUpdated = DateValue(FileDateTime("\\networksharem\dept\DCGSI\Extracts\SIM_DM_DCLC.csv"))
Application.DisplayAlerts = False
Application.StatusBar = "Importing latest DM DCLC SIM Data..."
With SIM_DM_DCLC.QueryTables.Add(Connection:= _
"TEXT;\\networkshare\dept\DCGSI\Extracts\SIM_DM_DCLC.csv" _
, Destination:=SIM_DM_DCLC.Range("$A$1"))
.Name = "SIM_DM_DCLC"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 936
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
'Change to MySQL date format.
Set regex = CreateObject("VBScript.RegExp")
regex.Pattern = "/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z)$/"
For Each cell In SIM_DM_DCLC.UsedRange
If cell.Value <> "" Then cell.Value = regex.Replace(cell.Value, "/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/")
Next cell
Pretty sure that the 5017 - Application-defined or object-defined error I am getting on the regex.Replace means I have something wrong with the regex piece. Just not sure what it is.
Well you have to check to an actual match and not just a blank; here is the updated and appropriate section of code.
'Change to MySQL date format.
Set regex = CreateObject("VBScript.RegExp")
regex.Pattern = "^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z)$"
For Each cell In SIM_DM_DCLC.UsedRange
If cell.Value = regex.Pattern Then cell.Value = regex.Replace(cell.Value, "^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$")
Next cell
I know that in PHP I can do something like this:
if ($foo == true && $bar == true) {
// Both true
} elseif ($foo == false && $bar == false) {
// Both false
}
How could I do that in Sass? Or can I... The docs are sparse on this topic http://sass-lang.com/documentation/file.SASS_REFERENCE.html#_6
I tried something like this:
#if $foo == false $bar == false {
// Both false
}
Doesn't give error but it only evaluates the $foo.
This also wont work:
#if $foo == false && $bar == false {
// Both false
}
Nor this:
#if $foo == false AND $bar == false {
// Both false
}
Thanks!
From ยง6.4.4 - Boolean Operations:
SassScript supports and, or, and not operators for boolean values.
This looks really ugly, it there a way to make it look more pythonic?
if self.cleaned_data['string1_val'] == '' and latestSI.string1_val is None :
if self.cleaned_data['string2_val'] == '' and latestSI.string2_val is None :
return False
elif self.cleaned_data['string2_val'] == latestSI.string2_val :
return False
else:
return True
elif self.cleaned_data['string1_val'] == latestSI.string1_val :
if self.cleaned_data['string2_val'] == '' and latestSI.string2_val is None :
return False
elif self.cleaned_data['string2_val'] == latestSI.string2_val :
return False
else:
return True
else:
return True
def eq(x,y):
return x == ('' if y is None else y)
if eq(self.cleaned_data['string1_val'],latestSI.string1_val):
return not eq(self.cleaned_data['string2_val'],latestSI.string2_val)
Hm. It looks like the question has changed. With the addition of the final else: True, the logic can be changed to
return not (eq(self.cleaned_data['string1_val'],latestSI.string1_val)
and eq(self.cleaned_data['string2_val'],latestSI.string2_val))
All your issues stem from Nones. Clean them up and your logic becomes trivial.
cd1 = self.cleaned_data['string1_val']
lsi1 = latestSI.string1_val
cd2 = self.cleaned_data['string2_val']
lsi2 = latestSI.string2_val
if lsi1 is None:
lsi1 = ''
if lsi2 is None:
lsi2 = ''
return not (cd1 == lsi1 and cd2 == lsi2)
I think this expression is equivalent (I can't test it, since I don't have access to the rest of your code). But, it's really long and hard to understand, I'd rather leave it untouched if I were you:
if (self.cleaned_data['string1_val'] == latestSI.string1_val) or (not self.cleaned_data['string1_val'] and not latestSI.string1_val):
return (not self.cleaned_data['string2_val'] or not latestSI.string2_val) and self.cleaned_data['string2_val'] != latestSI.string2_val
else:
return True
The inner if/elif/else chains can be replaced with the and-operator and or-operator. This substitution should be almost automatic whenever you see return True and return False for the body of each alternative.
Also, there are multiple references to self.cleaned_data that can be factored-out with:
cleaned = self.cleaned_data