Complex WHERE-clause in Droidparts doesn't work - droidparts

I need complex WHERE clause.
final Where where1 = new Where("col_1", Is.IN, "1, 2, 3");
final Where where2 = new Where("col_2", Is.IN, "a, b, c");
final Where where = where1.and(where2);
but in result i got
SELECT on table 'table', selection: 'col_1 IN (?) AND (col_2 IN (?))',
selectionArgs: '[1, 2, 3, a, b, c]', columns: 'null', orderBy: 'null',
groupBy: 'null', having: 'null', distinct: 'false', limit: 'null'.
as you see all arguments are put together and result fails.

Should be
final Where where1 = new Where("col_1", Is.IN, 1, 2, 3);
final Where where2 = new Where("col_2", Is.IN, "a", "b", "c");

Related

Dynamic Programming - String, Substrings and Minimum Cost

Dear Computer Science experts,
I have a question regarding Dynamic Programming (DP). The problem is I am given a sentence of characters and a cost_list that contains a list of substrings of sentence with their costs, the goal is to find lowest cost. It is assumed that cost_list contains all the substrings in sentence.
For example, suppose I have the below parameters,
sentence = "xxxyyzz"
cost_list = [["x", 1], ["xx", 3], ["y", 3], ["yy", 1], ["z", 2]]
So sentence could be [xx][x][yy][z][z], so the total cost is 3 + 1 + 1 + 2 + 2 = 9
But I could also select the substrings in sentence in a different way and we have [x][x][x][yy][z][z], which gives us 1 + 1 + 1 + 1 + 2 + 2 = 8 and it is the lowest cost.
The question is to construct a Dynamic Programming algorithm find_lowest_cost(sentence, cost_list).
Below is my recursive function for this problem I created, I have tested and it is correct,
def find_lowest_cost(sentence, cost_list):
if len(sentence) == 0:
return 0
else:
result = []
possible_substrings = []
possible_costs = []
for c in cost_list:
current_substring = c[0]
current_cost = c[1]
if current_substring == sentence[0:len(current_substring)]:
possible_substrings.append(current_substring)
possible_costs.append(current_cost)
for i in range(0, len(possible_substrings)):
result.append(possible_costs[i] + find_lowest_cost(sentence[len(possible_substrings[i]):], cost_list))
return min(result)
sentence = "xxxyyzz"
cost_list = [["x", 1], ["xx", 3], ["y", 3], ["yy", 1], ["z", 2]]
print(find_lowest_cost(sentence, cost_list))
I am stuck on how to converting the Recursion to Dynamic Programming (DP).
Question 1: For DP table, my columns are the characters of sentence. How what should my rows be? My thinking is it can't be a rows of "x", "xx", "y", "yy" and "z" because how would we compare "yy" with, say only "y" in sentence?
Question 2: Suppose rows and columns are figured out, at the current cell, what should the current cell be built upon? My notion is the cell is built-upon the lowest value of previous cells, such as cell[row][col-1], cell[row-1][col] and cell[row-1][col-1]?
Thanks!
Once you are able to get the recursive solution then try to look for how many variable are getting changed. Analysing the recursive approach:
We need to find a solution like, what is the minimum cost when string is having length 1, then 2 so on... There would be repetitive calculation for substring from 0 to k th index so we need to store all calculated result into single dp so that we can give the answer of any k th index which has already calculated.
Below is my Java solution.
import java.util.HashMap;
public class MyClass {
private static Integer[] dp;
public static void main(String args[]) {
// cost_list = [["x", 1], ["xx", 3], ["y", 3], ["yy", 1], ["z", 2]]
HashMap<String, Integer> costmp = new HashMap();
costmp.put("x", 1);
costmp.put("xx", 3);
costmp.put("y", 3);
costmp.put("yy", 1);
costmp.put("z", 2);
String sentence = "xxxyyzz";
// String sentence = "xxyyzzxxxxyyyyxxxyxxyyyxxyyyzzzyyyxxxyyyyzzzyyyyxxxyyyzzzyyxxxxxxxxxxxxxxyyxyxyzzzzxxyyxx";
// String sentence = "xxxyyzzxxxxyyyyxxxyxxyyyxxyyyzzzyyyxxxyyyyzzzy";
dp = new Integer[sentence.length()+1];
int res = find_lowest_cost(sentence, costmp, 0);
System.out.println("find_lowest_cost = " + res);
}
private static int find_lowest_cost(String sentence, HashMap<String, Integer> costmp, int st)
{
if(st == sentence.length())
return 0;
int mincost = Integer.MAX_VALUE;
if(dp[st] != null)
return dp[st];
String str = new String();
for(int i = st;i < sentence.length(); i++)
{
str+=sentence.charAt(i);
if(!costmp.containsKey(str))
break;
int cost = costmp.get(str);
mincost = Math.min(mincost, cost+find_lowest_cost(sentence, costmp, i+1));
}
dp[st] = mincost;
return mincost;
}
}

Build an Octave struct by "rows"

I mean to use a struct to hold a "table":
% Sample data
% idx idxstr var1 var2 var3
% 1 i01 3.5 21.0 5
% 12 i12 6.5 1.0 3
The first row contains the field names.
I could enter these data by columns directly,
ds2 = struct( ...
'idx', { 1, 12 }, ...
'idxstr', { 'i01', 'i12' }, ...
'var1', { 3.5, 6.5 }, ...
'var2', { 21, 1 }, ...
'var3', { 5, 3 } ...
);
and by rows indirectly, creating a cell array, and converting to struct,
ds3 = cell2struct( ...
{ 1, 'i01', 3.5, 21.0, 5; ...
12, 'i12', 6.5, 1.0, 3 ...
}, { 'idx', 'idxstr', 'var1', 'var2', 'var3' }, 2 );
Is there a direct way to enter data by rows?
In addition,
why the different sizes?
>> size(ds2), size(ds3)
ans =
1 2
ans =
2 1
As I mentioned in your other post here, you are probably better off creating your 'table' as a struct of array fields, rather than an array of single-row structs.
However, for the sake of writing a useful answer, I will assume the reason you opted for this form to begin with may be that you already have your data as rows in 'cell' form (e.g. possibly the output of a csv2cell operation), and you'd like to convert it to such a "table".
Therefore, to create a nice "table as struct of arrays" from such a data structure, you could follow a strategy like the following:
Data = { 1, 'i01', 3.5, 21.0, 5; 12, 'i12', 6.5, 1.0, 3 };
d1 = struct( 'idx' , [Data{:,1}] ,
'idxstr', {{Data{:,2}}}, % note the 'enclosing' braces!
'var1' , [Data{:,3}] ,
'var2' , [Data{:,4}] ,
'var3' , [Data{:,5}]
);
or, using cell2struct if you prefer that syntax:
d2 = cell2struct( { [Data{:,1}],
{Data{:,2}}, % note the lack of enclosing braces here!
[Data{:,3}],
[Data{:,4}],
[Data{:,5}] },
{ 'idx', 'idxstr', 'var1', 'var2', 'var3' },
2
);
Note that you "do" need to know if a 'column' represents a numeric or string array, so that you wrap it in [] or {} respectively ... but I think knowing the data-type represented by each column is not an unreasonable requirement from a programmer.

go array initialization containing a string literal

I'm trying to initialize a byte array as a mix of numbers and a string. I've managed to do it using a pair of appends, or by splitting the string into individual chars, but for the sake of readability is there a way to do it as a single initializer containing a string?
// method 1, with two appends
a := []byte{1, 2}
a = append(a, []byte("foo")...);
a = append(a, 3, 4);
// method 2, splitting the string into chars
b := []byte{1, 2, 'f', 'o', 'o', 3, 4)
What you did in your first attempt in 3 lines is probably more readable that any one-liners:
(You can try all the examples on the Go Playground.)
// Doing one-by-one:
a := []byte{1, 2}
a = append(a, []byte("foo")...)
a = append(a, 3, 4)
fmt.Println(a)
// Using individual chars:
a = []byte{1, 2, 'f', 'o', 'o', 3, 4}
fmt.Println(a)
// Using a single string literal:
a = []byte("\x01\x02foo\x03\x04")
fmt.Println(a)
// Using several "nested" appends:
a = append(append([]byte{1, 2}, []byte("foo")...), 3, 4)
fmt.Println(a)
Except if you create a helper function:
func concat(s ...[]byte) []byte {
var res []byte
for _, v := range s {
res = append(res, v...)
}
return res
}
And then using it:
// With a utility function:
a = concat([]byte{1, 2}, []byte("foo"), []byte{3, 4})
fmt.Println(a)
// With a utility function, formatted differently:
a = concat(
[]byte{1, 2},
[]byte("foo"),
[]byte{3, 4},
)
fmt.Println(a)
You could also do it using a single keyed composite literal and a single copy() call to "insert" the string:
// With keyed literal and copy:
a = []byte{1, 2, 5: 3, 4}
copy(a[2:], "foo")
fmt.Println(a)
Still I don't think it's more readable or worth it.
Concat optimization
As per comments left below, #EliasVanOotegem benchmarked the solution above (using append on an empty slice) and compared it to summing the total capacity of the byte slice required and allocating that memory in one go. The latter turns out to be slightly more efficiend (~20%), so I'll include that version below:
func concat(s ...[]byte) []byte {
c := 0
for _, v := range s {
c += len(v)
}
res := make([]byte, 0, c) // allocate everything
for _, v := range s {
res = append(res, v...)
}
return res
}
I personally would use the following optimized version which does not require slice header assignments as it uses the builtin copy():
func concat(s ...[]byte) []byte {
size := 0
for _, v := range s {
size += len(v)
}
res, i := make([]byte, size), 0
for _, v := range s {
i += copy(res[i:], v)
}
return res
}
I think I misunderstood what you are trying initially. You could write it as a string with hex embedded:
c := []byte("\x01\x02foo\x03\x04")
FWIW : it is possible to remove the cast to []byte(...) in the append call :
a := []byte{65, 66}
a = append(a, "foo"...)
a = append(a, 67, 68)
fmt.Printf("%s", a)
// outputs : ABfooCD
see it on play.golang.org

How to use sortby in Java in Spark

I have two rdd, and would like to merge together, I have the following question,
I tried the following using union, but union does not sort at all, but I don't know how to use sortby here?
List<Integer> data1 = Arrays.asList(1, 3, 5);
List<Integer> data2 = Arrays.asList(2, 4, 6, 8);
JavaRDD<Integer> rdd1 = sc.parallelize(data1);
JavaRDD<Integer> rdd2 = sc.parallelize(data2);
JavaRDD<Integer> rdd = rdd1.union(rdd2);
rdd.sortBy(w->w._1, false); //compile error
Another question, is there any good way to return the merged the list sorted?
Try below:
List<Integer> data1 = Arrays.asList(1, 3, 5);
List<Integer> data2 = Arrays.asList(2, 4, 6, 8);
JavaRDD<Integer> rdd1 = sc.parallelize(data1);
JavaRDD<Integer> rdd2 = sc.parallelize(data2);
JavaRDD<Integer> rdd = rdd1.union(rdd2);
int noofpartitions = 1;
JavaRDD<Integer> rddSorted = rdd.sortBy(f -> f, true, noofpartitions);
rddSorted.collect().forEach(f -> System.out.println(f));
sortBy take three parameters: 1. the function 2. a boolean - true represents ascending order, false-descending order, 3. number of partitions
It will print :
1
2
3
4
5
6
8
The way you have used is the right one. see this for more details How to merge two presorted rdds in spark?

Reorder string characters in Swift

So, let's say I have a String that is: "abc" and I want to change each character position so that I can have "cab" and later "bca". I want the character at index 0 to move to 1, the one on index 1 to move to 2 and the one in index 2 to 0.
What do I have in Swift to do this? Also, let's say instead of letters I had numbers. Is there any easier way to do it with integers?
Swift 2:
extension RangeReplaceableCollectionType where Index : BidirectionalIndexType {
mutating func cycleAround() {
insert(removeLast(&self), atIndex: startIndex)
}
}
var ar = [1, 2, 3, 4]
ar.cycleAround() // [4, 1, 2, 3]
var letts = "abc".characters
letts.cycleAround()
String(letts) // "cab"
Swift 1:
func cycleAround<C : RangeReplaceableCollectionType where C.Index : BidirectionalIndexType>(inout col: C) {
col.insert(removeLast(&col), atIndex: col.startIndex)
}
var word = "abc"
cycleAround(&word) // "cab"
In the Swift Algorithms package there is a rotate command
import Algorithms
let string = "abcde"
var stringArray = Array(string)
for _ in 0..<stringArray.count {
stringArray.rotate(toStartAt: 1)
print(String(stringArray))
}
Result:
bcdea
cdeab
deabc
eabcd
abcde

Resources