I have a recordset like this:
row1 = Type1, partid, partname
row2 = Type2, partid, partname
row3 = Type2, partid, partname
I want my output to be like this:
Type1: partid partname
Type2: partid partname, partid, partname
or
Type2: partid partname, partid, partname
Type1: partid partname
(depending on how the sort works out)
I have my results sorted by the Type value. I may or may not get same Types in a result, but if so the result is required to be printed as above.
I'm using .getRows() to get the recordset into an array.
I can't for the life of me figure out how to decide in the loop whether to print a break tag or a comma.
You need to check for a change in the type column. In that case, print <br /> and the type. In code:
Set r = CreateObject("ADODB.Recordset")
r.Fields.Append "t", 3
r.Fields.Append "i", 3
r.Fields.Append "n", 3
r.Open
r.AddNew : r.Fields("t") = 1 : r.Fields("i") = 10 : r.Fields("n") = 10
r.AddNew : r.Fields("t") = 2 : r.Fields("i") = 20 : r.Fields("n") = 21
r.AddNew : r.Fields("t") = 2 : r.Fields("i") = 22 : r.Fields("n") = 22
r.AddNew : r.Fields("t") = 3 : r.Fields("i") = 30 : r.Fields("n") = 31
r.MoveFirst
a = r.GetRows()
t = a(0, 0)
WScript.StdOut.Write a(0, 0)
For r = 0 To UBound(a, 2)
If t <> a(0, r) Then
WScript.StdOut.Write "<br />" & a(0, r)
t = a(0, r)
End If
WScript.StdOut.Write Join(Array("", a(1, r), a(2,r)), ",")
Next
output:
cscript 24441584.vbs
1,10,10<br />2,20,21,22,22<br />3,30,31
Related
I have seen this question earlier here and I have took lessons from that. However I am not sure why I am getting an error when I feel it should work.
I want to create a new column in existing Spark DataFrame by some rules. Here is what I wrote. iris_spark is the data frame with a categorical variable iris_spark with three distinct categories.
from pyspark.sql import functions as F
iris_spark_df = iris_spark.withColumn(
"Class",
F.when(iris_spark.iris_class == 'Iris-setosa', 0, F.when(iris_spark.iris_class == 'Iris-versicolor',1)).otherwise(2))
Throws the following error.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-157-21818c7dc060> in <module>()
----> 1 iris_spark_df=iris_spark.withColumn("Class",F.when(iris_spark.iris_class=='Iris-setosa',0,F.when(iris_spark.iris_class=='Iris-versicolor',1)))
TypeError: when() takes exactly 2 arguments (3 given)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-157-21818c7dc060> in <module>()
----> 1 iris_spark_df=iris_spark.withColumn("Class",F.when(iris_spark.iris_class=='Iris-setosa',0,F.when(iris_spark.iris_class=='Iris-versicolor',1)))
TypeError: when() takes exactly 2 arguments (3 given)
Any idea why?
Correct structure is either:
(when(col("iris_class") == 'Iris-setosa', 0)
.when(col("iris_class") == 'Iris-versicolor', 1)
.otherwise(2))
which is equivalent to
CASE
WHEN (iris_class = 'Iris-setosa') THEN 0
WHEN (iris_class = 'Iris-versicolor') THEN 1
ELSE 2
END
or:
(when(col("iris_class") == 'Iris-setosa', 0)
.otherwise(when(col("iris_class") == 'Iris-versicolor', 1)
.otherwise(2)))
which is equivalent to:
CASE WHEN (iris_class = 'Iris-setosa') THEN 0
ELSE CASE WHEN (iris_class = 'Iris-versicolor') THEN 1
ELSE 2
END
END
with general syntax:
when(condition, value).when(...)
or
when(condition, value).otherwise(...)
You probably mixed up things with Hive IF conditional:
IF(condition, if-true, if-false)
which can be used only in raw SQL with Hive support.
Conditional statement In Spark
Using “when otherwise” on DataFrame
Using “case when” on DataFrame
Using && and || operator
import org.apache.spark.sql.functions.{when, _}
import spark.sqlContext.implicits._
val spark: SparkSession = SparkSession.builder().master("local[1]").appName("SparkByExamples.com").getOrCreate()
val data = List(("James ","","Smith","36636","M",60000),
("Michael ","Rose","","40288","M",70000),
("Robert ","","Williams","42114","",400000),
("Maria ","Anne","Jones","39192","F",500000),
("Jen","Mary","Brown","","F",0))
val cols = Seq("first_name","middle_name","last_name","dob","gender","salary")
val df = spark.createDataFrame(data).toDF(cols:_*)
1. Using “when otherwise” on DataFrame
Replace the value of gender with new value
val df1 = df.withColumn("new_gender", when(col("gender") === "M","Male")
.when(col("gender") === "F","Female")
.otherwise("Unknown"))
val df2 = df.select(col("*"), when(col("gender") === "M","Male")
.when(col("gender") === "F","Female")
.otherwise("Unknown").alias("new_gender"))
2. Using “case when” on DataFrame
val df3 = df.withColumn("new_gender",
expr("case when gender = 'M' then 'Male' " +
"when gender = 'F' then 'Female' " +
"else 'Unknown' end"))
Alternatively,
val df4 = df.select(col("*"),
expr("case when gender = 'M' then 'Male' " +
"when gender = 'F' then 'Female' " +
"else 'Unknown' end").alias("new_gender"))
3. Using && and || operator
val dataDF = Seq(
(66, "a", "4"), (67, "a", "0"), (70, "b", "4"), (71, "d", "4"
)).toDF("id", "code", "amt")
dataDF.withColumn("new_column",
when(col("code") === "a" || col("code") === "d", "A")
.when(col("code") === "b" && col("amt") === "4", "B")
.otherwise("A1"))
.show()
Output:
+---+----+---+----------+
| id|code|amt|new_column|
+---+----+---+----------+
| 66| a| 4| A|
| 67| a| 0| A|
| 70| b| 4| B|
| 71| d| 4| A|
+---+----+---+----------+
There are different ways you can achieve if-then-else.
Using when function in DataFrame API.
You can specify the list of conditions in when and also can specify otherwise what value you need. You can use this expression in nested form as well.
expr function.
Using "expr" function you can pass SQL expression in expr. PFB example. Here we are creating new column "quarter" based on month column.
cond = """case when month > 9 then 'Q4'
else case when month > 6 then 'Q3'
else case when month > 3 then 'Q2'
else case when month > 0 then 'Q1'
end
end
end
end as quarter"""
newdf = df.withColumn("quarter", expr(cond))
selectExpr function.
We can also use the variant of select function which can take SQL expression. PFB example.
cond = """case when month > 9 then 'Q4'
else case when month > 6 then 'Q3'
else case when month > 3 then 'Q2'
else case when month > 0 then 'Q1'
end
end
end
end as quarter"""
newdf = df.selectExpr("*", cond)
you can use this:
if(exp1, exp2, exp3) inside spark.sql()
where exp1 is condition and if true give me exp2, else give me exp3.
now the funny thing with nested if-else is. you need to pass every exp inside
brackets {"()"}
else it will raise error.
example:
if((1>2), (if (2>3), True, False), (False))
The Code I have so far only does for 1 index however I want it to read all existing indexes within the array. element array can carry many groups of numbers for example
Array ["2,2,5" , "5,2,1"] contains 2 indexes [0] and [1]
var element = Array[0]
let splitData = element.components(separatedBy: ",")
// split data will always contain 3 values.
var value1 = splitData[0]
var value2 = splitData[1]
var value3 = splitData[2]
print("value 1 is : " + value1 + " value 2 is : " + value2 + " value 3 is: " + value3)
the output of this code when Array ["2,2,5" , "5,2,1"] is :
value 1 is : 2 value 2 is : 2 value 3 is : 5
As the output suggests how can i iterate through all indexes of Array to display each of their 3 values.
I want the output to be :
value 1 is : 2 value 2 is : 2 value 3 is : 5
value 1 is : 5 value 2 is : 2 value 3 is : 1
I believe I need to use a for loop however I am unsure how to apply it to this. I am quite new to coding. Any help will be Appreciated
for i in 0..<array.count {
var element = array[i]
let splitData = element.components(separatedBy: ",")
// split data will always contain 3 values.
var value1 = splitData[0]
var value2 = splitData[1]
var value3 = splitData[2]
print("value 1 is : " + value1 + " value 2 is : " + value2 + " value 3 is: " + value3)
}
here are two solutions you can use, depending on what is the best result for you.
1) If your goal is to transform an array like ["3,4,5", "5,6", "1", "4,9,0"] into a flattened version ["3", "4", "5", "5", "6", "1", "4", "9", "0"] you can do it easily with the flatMap operator in the following way:
let myArray = ["3,4,5", "5,6", "1", "4,9,0"]
let flattenedArray = myArray.flatMap { $0.components(separatedBy: ",") }
Then you can iterate on it like every other array,
for (index, element) in myArray.enumerated() {
print("value \(index) is: \(element)")
}
2) If you just want to iterate over it and keep the levels you can use the following code.
let myArray = ["3,4,5", "5,6", "1", "4,9,0"]
for elementsSeparatedByCommas in myArray {
let elements = elementsSeparatedByCommas.components(separatedBy: ",")
print(elements.enumerated().map { "value \($0) is: \($1)" }.joined(separator: " "))
}
Hope that helps!
How would I go about compiling values from a table using a string?
i.e.
NumberDef = {
[1] = 1,
[2] = 2,
[3] = 3
}
TextDef = {
["a"] = 1,
["b"] = 2,
["c"] = 3
}
If I was for example to request "1ABC3", how would I get it to output 1 1 2 3 3?
Greatly appreciate any response.
Try this:
s="1ABC3z9"
t=s:gsub(".",function (x)
local y=tonumber(x)
if y~=nil then
y=NumberDef[y]
else
y=TextDef[x:lower()]
end
return (y or x).." "
end)
print(t)
This may be simplified if you combine the two tables into one.
You can access values in a lua array like so:
TableName["IndexNameOrNumber"]
Using your example:
NumberDef = {
[1] = 1,
[2] = 2,
[3] = 3
}
TextDef = {
["a"] = 1,
["b"] = 2,
["c"] = 3
}
print(NumberDef[2])--Will print 2
print(TextDef["c"])--will print 3
If you wish to access all values of a Lua array you can loop through all values like so (similarly to a foreach in c#):
for i,v in next, TextDef do
print(i, v)
end
--Output:
--c 3
--a 1
--b 2
So to answer your request, you would request those values like so:
print(NumberDef[1], TextDef["a"], TextDef["b"], TextDef["c"], NumberDef[3])--Will print 1 1 2 3 3
One more point, if you're interested in concatenating lua string this can be accomplished like so:
string1 = string2 .. string3
Example:
local StringValue1 = "I"
local StringValue2 = "Love"
local StringValue3 = StringValue1 .. " " .. StringValue2 .. " Memes!"
print(StringValue3) -- Will print "I Love Memes!"
UPDATE
I whipped up a quick example code you could use to handle what you're looking for. This will go through the inputted string and check each of the two tables if the value you requested exists. If it does it will add it onto a string value and print at the end the final product.
local StringInput = "1abc3" -- Your request to find
local CombineString = "" --To combine the request
NumberDef = {
[1] = 1,
[2] = 2,
[3] = 3
}
TextDef = {
["a"] = 1,
["b"] = 2,
["c"] = 3
}
for i=1, #StringInput do --Foreach character in the string inputted do this
local CurrentCharacter = StringInput:sub(i,i); --get the current character from the loop position
local Num = tonumber(CurrentCharacter)--If possible convert to number
if TextDef[CurrentCharacter] then--if it exists in text def array then combine it
CombineString = CombineString .. TextDef[CurrentCharacter]
end
if NumberDef[Num] then --if it exists in number def array then combine it
CombineString = CombineString .. NumberDef[Num]
end
end
print("Combined: ", CombineString) --print the final product.
I have the below code I'm trying to put together and I'm running into a Run-time error '9' subscript out of range. This does work through the first run through then errors. I don't see why it won't allow for the string to go forward. From what I'm reading it should go through the application changing the X values with Y value 1 and when completed with that set to go to the next Y and start the whole process again until the end of Y. Any help would be appreciated.
Dim Cat(1 To 10) As String
Cat(1) = "010" 'SD
Cat(2) = "020" 'FD
Cat(3) = "050" 'WVID
Cat(4) = "040" 'VID
Cat(5) = "030" 'MEM
Cat(6) = "080" 'ACC
Cat(7) = "060" 'HDMI
Cat(8) = "070" 'SSD
Cat(9) = "090" 'POWER
Cat(10) = "990" 'ZRM
Dim Month(1 To 12) As String
Month(1) = "January"
Month(2) = "February"
Month(3) = "March"
Month(4) = "April"
Month(5) = "May"
Month(6) = "June"
Month(7) = "July"
Month(8) = "August"
Month(9) = "September"
Month(10) = "October"
Month(11) = "November"
Month(12) = "December"
For Y = 1 To UBound(Cat)
For X = 1 To UBound(Month)
Month(X) = Application.WorksheetFunction.SumIf(Sheets(Month(X)).Columns("AO"), Cat(Y), Sheets(Month(X)).Columns("AG"))
Next X
Cells(3 + Y, 41).Value = Application.WorksheetFunction.Sum(Month(1), Month(2), Month(3), Month(4), Month(5), Month(6), Month(7), Month(8), Month(9), Month(10), Month(11), Month(12))
Next Y
End Sub
On the first run through the loop indexed by X you are computing a conditional sum of data stored in Sheet "January". And then overwriting "January" with that value in Month(X). Let's say that that value is 42. On your next run through the loop 42 is in Month(X) so you are looking for Sheets(42), which probably isn't a valid worksheet. I would try this instead.
dim temp as double
For Y = 1 To UBound(Cat)
temp = 0# '0 as a double.
For X = 1 To UBound(Month)
temp = temp + Application.WorksheetFunction.SumIf(Sheets(Month(X)).Columns("AO"), Cat(Y), Sheets(Month(X)).Columns("AG"))
Next X
Cells(3 + Y, 41).Value = temp
Next Y
This way we don't need to store all of the sums from each sheet, since we only use them to add them all together.
below is my array and code to check if the data in textbox is inside of the array. the problem is when i run the program the value of array is always " " or no data found.. what's wrong with my code? please help me.. thank you.
a = Split((a), vbTab)
devices = Array("iPhone5", "iPhone4", "iPhone3", "iPad", "iPod", "iPhone4s", "iPhone3G", "iPhone3gs", "gt-s5360", "gt-i9505", "n7100", "gt-n7100", "i9300", "gt-i9300", "gt-p3100", "s5300", "gt-s5300", "gt-s7562", _
"gt-i8190", "s100", "p5100", "gt-p5100", "gt-s6102", "gt-i9100", "gt-p3110", "gt-p6200", "n8000", "gt-n8000", "gt-i9082", "sm-t210", "gt-n7105", "n7000", "gt-n7000", "gt-n5100", "GT-S5570", "GT-S5830i", _
"GT-S5830", "GT-I8262", "GT-P1000", "Nexus 7", "GT-I8160", "H120", "ALCATEL ONE TOUCH 918N", "HuaweiG510-0200", "MyPhone A919 Duo", "MyPhone A848i Duo", "C6603", "ALCATEL ONE TOUCH 4030E", "LG-E400", _
"GT-P6800", "ICE 350e", "GT-I9070", "ALCATEL ONE TOUCH 5021E", "Cherry w500", "GT-I8150", "LT22i", "Spark TV", "I9500", "GT-I9500", "Burst S280", "W120", "GT-P7500", "MyPhone A888 Duo", "GT-S5301", "Thunder S220", "GT-S7500", _
"GT-I8552", "SM-T211", "GT-S5282", "A818 Duo", "LT26i", "GT-S6802", "GT-S5570I", "HuaweiY210-0100", "LT26w", "HTC One", "ST23i", "ST27i", "SHW-M250S", "Cruize W280", "Titan TV S320", "B1-A71", "GT-I9152", "W110", "7038", _
"LT18i", "GT-P3113", "GT-I9000", "Cherry Sonic", "GT-S5670", "SHW-M110S", "ST26i", "SonyEricssonMT25i", "Excite_352g", "LT25i", "Lenovo A390_ROW", "ST25i", "LG-E612", "GT-I9003")
urls = Array("youtube.com", "ytimg.com", "DoubleClick.net", "google.com", "fbcdn.net", "google -analytics.com", "yimg.com", "googlesyndication.com", "facebook.com", "gstatic.com", "mywebacceleration.com", "yahoo.com", "scorecardresearch.com", _
"google.com.ph", "adnxs.com", "redtubefiles.com", "rubiconproject.com", "wattpad.net", "www.com", "youjizz.com", "bing.net", "akamaihd.net", "xvideos.com", "tumblr.com", "twitter.com", "yieldmanager.com", "sharethis.com", "wikimedia.org", _
"y8.com", "sulitstatic.com", "globe.com.ph", "googleapis.com", "tagstat.com", "quantserve.com", "addthis.com", "blogspot.com", "king.com", "cloudfront.net", "ayosdito.com", "ask.com", "openx.net", "bigspeedpro.com", "gravatar.com", _
"amasvc.com", "bing.com", "cdn.com", "yldmgrimg.net", "cedexis.com")
For intX = 0 To UBound(a)
If Text11.Text = "" Then
a(intX) = UCase(a(intX))
Text11.Text = a(intX)
ElseIf Text12.Text = "" Then
a(intX) = UCase(a(intX))
Text12.Text = a(intX)
If Len(Text12.Text) <= 17 Then
Text12.Text = ""
Else
b = Split(Text12.Text, "/")
For i = 0 To UBound(b)
Text12.Text = b(2)
Next
Text12 = InStr(Text12, urls)
If Text12 = UCase(urls) Then
Text22 = Text12
Text25 = count + 1
Else
Text26 = Text12
Text27 = othercount + 1
End If
End If
You can use ForEach to make it more effective.
Or use this function... :)
Public Function IsContained(theArray() As Variant, strSearchPharse As String, Optional IsMatch As Boolean = False, Optional IsCaseSensitive As Boolean = True) As Boolean
On Error Resume Next
If Not UBound(theArray) 0 Then End
Dim strExploded As String
Dim gsChache As Boolean
gsChache = False 'set the default value
'Checking for every array thing
For Each strExploded In theArray
If IsMatch And Not (Len(strSearchPharse) = Len(strExploded)) Then 'if its matchable...
If IsCaseSensitive And strExploded = strSearchPharse Then gsChache = True
If Not IsCaseSensitive And LCase(strExploded) = LCase(strSearchPharse) Then gsChache = True
ElseIf Not IsMatch And Not IsCaseSensitive Then 'if its not matchable, and not case sensitive
If InStr(0, LCase(strExploded), LCase(strSearchPharse)) >= 1 Then gsChache = True
Else 'if its not matchable, and Case Sensitive
If InStr(0, strExploded, strSearchPharse) >= 1 Then gsChache = True
End If
DoEvents
Next strExploded
IsContained = gsChache 'finish
End Function
How to use it?
theArray is for array variable, strSearchPharse is the text you want to search (like keyword, e.g. apple or youtube), then isMatch is is the text you want to search is need to exactly same (not case sensitive, buat it will if you enable it.), IsCaseSensitive is the text you need to search on is need to case sensitive or not.
the default setting is, Not Matchable, and Case Sensitiveable.
Sample:
XYZ = Array("Satu", "Dua", "Tiga", "Empat", "Lima", "Enam", "Tujuh", "Delapan", "Sembilan", "Sepuluh")
If IsContained(XYZ, "o", , False) Then
MsgBox "The Array contains o alphabet."
Else
MsgBox "The Array have no o alphabet."
End If
The result will show "The Array contains o alphabet." MsgBox... :)