How to convert bit column to int - sql

I want to convert a bit column to a integer column, do I need a case and convert function at the same time for this?
False = 0
True = 1

You do not need a conversion, because bit is already an integer data type:
An integer data type that can take a value of 1, 0, or NULL.
You can use bits in integer expressions without conversion. Here is a short demo:
create table demo (b bit, v int);
insert into demo (b, v) values (1,5), (0,4), (1, -2), (0, -5);
SELECT b, v, b+v AS b_plus_v FROM demo
Running this produces the following output:
B V B_PLUS_V
- - --------
1 5 6
0 4 4
1 -2 -1
0 -5 -5
EDIT : (based on this comment: "I'm using Code first EF")
Entity Framework requires that a bit column mapped to a bool field. One way to work around this requirement is introducing a computed property to your entity class to hide the "Booleanness" of the underlying column, like this:
partial class MyEntity {
// This code assumes that a bool property MyBoolProperty exists,
// and that it is mapped to the table using EF
public int MyIntProperty {
get {
return MyBoolProperty ? 1 : 0;
}
set {
MyBoolProperty = value != 0;
}
}
}

Related

Whats the difference between these two function callings in kotlin?

The first way
fun add(a: Int, b: Int): Int {
return a + b
}
fun main() {
print(add(a = 2, b = 3))
}
The second way
fun add(a: Int, b: Int): Int {
return a + b
}
fun main() {
print(add(2, 3))
}
The end result of the two functions is the same but i was wondering if there is any internal difference between the two ways of function calling.
In the first case you're explicitly stating to which field of the add() method constructor you're assigning the value.
In this way the order in which you put the values doesn't matter, as long as each value is explicitly assigned to a parameter. For example, in this case you can also write:
print(add(b=3, a=2))
still works.
As instead, in the second way you are forced to follow the order in which the fields are written in the method implementation (the first value is implicitly assigned to a, the second to b and so on)
For this example there is no difference, because you are adding the arguments in order
add(a=2,b=3): here a is going to take 2 and b is going to take 3
add(2,3): and here a is the first argument so it's going to take the first passed argument which is 2 and the same for b
But here is the difference (a + b == b + a so I add minus function to see the difference because a - b != b - a) :
fun minus(a : Int,b:Int):Int{
return a-b;
}
fun main()
{
print(minus(a=2,b=3)) // a = 2, b = 3 -> a - b = 2 - 3 = -1
print(minus(b=2,a=3)) // a = 3, b = 2 -> a - b = 3 - 2 = 1
print(minus(2,3)) // a = 2, b = 3 -> a - b = 2 - 3 = -1
}
So if you add minus(a=2,b=3) you are saying that a is going to take 2 and b is going to take 3,
and here minus(2,3) you are saying that the first parameter (a) is going to take 2 and the second parameter (b) is going to take 3
But let's say for some reason you change the order of the parameters of your function:
fun add(b : Int,a:Int):Int{
return a+b;
}
Now if you add minus(a=2,b=3) you are saying that a is going to take 2 and b is going to take 3 so nothing changes for this case and your code will work fine.
But here minus(2,3) you are saying that the first parameter (b) is going to take 2 and the second parameter (a) is going to take 3 so you will not get the same result before changing the order of the parameters of the function. So adding parameter name when you call a function is a best practice to say that you want this value for that exact argument.
Also there's other example, let's say that you have a function that has default values:
fun test(a : Int = 10, b:Int = 5):Int {
return a+b;
}
So the you can call it like that test() without passing any argument, but let's say that you want to change only b to 15, if you write test(15), a is going to take 15 not b so here you need to specify that the 15 is for b: test(b = 15)
There is no difference, the only difference is readability by using named arguments in the first example.
The fun thing about using named arguments when calling your method is that you can also change the order or even leave out some of the values if they are default i.e:
fun add(a :Int,b: Int):Int {
return a+b;
}
Can also be written with a default value like so:
fun add(a :Int = 2,b: Int = 3, c: Int = 4):Int {
return a+b+c;
}
Now you can skip some of the values like so:
fun main() {
print(add(a = 2, c = 3))
}
// So we did 2 + 3 + 3
// prints 8
// Notice we skipped b

Calculate sum of 2D Arrays

I want to write a program to calculate the sum of 2 matrices(2D Arrays) based on the user input.
Two matrices must have an equal number of rows and columns to be added. The sum of two matrices A and B will be a matrix that has the same number of rows and columns as do A and B.
The first line of standard input is a number of rows n and number of columns m of matrix A. Next n lines are A matrix’s elements. The next line after the empty line is a number of rows n and a number of columns m of matrix B. Next n lines are B matrix’s elements.
I want to output the result of a sum of A and B matrices or ERROR message if it’s impossible. The input contains only integers.
Example
Input:
4 5
1 2 3 4 5
3 2 3 2 1
8 0 9 9 1
1 3 4 5 6
4 5
1 1 4 4 5
4 4 5 7 8
1 2 3 9 8
1 0 0 0 1
Output:
2 3 7 8 10
7 6 8 9 9
9 2 12 18 9
2 3 4 5 7
My Code:
package processor
import java.util.*
val scanner = Scanner(System.`in`)
fun main() {
MatrixProcessor().addition()
}
class MatrixProcessor {
private fun createMatrix(): Array<Array<Int>> {
val rows = scanner.nextInt()
val columns = scanner.nextInt()
return Array(rows) {Array(columns) { scanner.nextInt()} }
}
fun addition() {
val firstMatrix = createMatrix()
val secondMatrix = createMatrix()
val sum = Array(4) { IntArray(5) }
for (i in 0 until 4) {
for (j in 0 until 5) {
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j]
}
}
printSolution(sum)
}
private fun printSolution(matrix: Array<IntArray>) {
for (array in matrix) {
for (value in array) {
print("$value ")
}
println()
}
}
}
My main problem lies with sum in the addition function since I do not know how to fill it with dynamic row and column size and currently inserted a standard value of 4 and 5.
fun addition() {
val firstMatrix = createMatrix()
val secondMatrix = createMatrix()
val sum = Array(4) { IntArray(5) }
for (i in 0 until 4) {
for (j in 0 until 5) {
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j]
}
}
printSolution(sum)
}
It looks like you're storing your matrices in row-major order: you have individual arrays representing rows, and then an outer array holding all the rows.  So the size of the outer array gives you the number of rows, and the size of any of the inner arrays (such as the first) gives you the number of columns.
So you can create the sum like this:
val sum = Array(firstMatrix.size) { IntArray(firstMatrix[0].size) }
for (i in sum.indices)
for (j in sum[0].indices)
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j]
(I've used .indices instead of an explicit range, for simplicity.)
An alternative approach is to specify the values when creating the arrays, instead of filling them in afterwards.  (It doesn't make too much difference here, as numeric arrays get a default value of 0; but it can simplify things a lot when creating arrays of a non-nullable reference type.)
val sum = Array(firstMatrix.size) { row ->
IntArray(firstMatrix[0].size) { column ->
firstMatrix[row][column] + secondMatrix[row][column]
}
}
The Array() and IntArray() constructors pass the index into the lambda; while the first version ignores it, here we call it row or columns so we can use it to index the arrays we're summing.
The above assumes that all the inner arrays have the same size.  That's probably reasonable in this case, where you've created the arrays yourself — but in general you'd probably want to verify that.
Certainly, it would be a good idea to verify that the two matrices you're adding are the same size, and throw an IllegalArgumentException with a helpful message if not.  Otherwise, you'd either get an ArrayIndexOutOfBoundsException (if the first were larger), or values would get silently truncated (if the second were larger) — both of which would be much harder to track down.
(The underlying issue here is that, like most languages, Kotlin doesn't have true two-dimensional arrays.  What it does have is arrays of arrays, which are more flexible — and therefore more dangerous.  If you were doing this properly, you'd probably wrap the array-of-arrays into your own Matrix class, which would always ensure that the data was properly rectangular, provide access to the row and column counts, and make all the necessary checks.)
From what i've understood your problem is the fact that you must set a fixed size for Array. I suggest you to use ArrayList instead to solve the problem.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-list/
With this solution you don't need to set a size for sum anymore.
Once you'll use ArrayLists you'll never get back to Arrays.

How to pass a logical R object to a data block in a Stan file

If a list of data includes a logical variable x, namely, x=TRUE or x=FALSE.
Then how to declare such a variable in a Stan file?
For example, if an R object x is an integer, then
data{
int <lower=0>x;
}
I want to know its logical version. I guess
data{
bool x;
}
and it does not work as following;
SYNTAX ERROR, MESSAGE(S) FROM PARSER:
error in 'foo' at line 16, column 0
-------------------------------------------------
14:
15:
16: bool x;
^
17:
-------------------------------------------------
PARSER EXPECTED: <one of the following:
a variable declaration, beginning with type,
(int, real, vector, row_vector, matrix, unit_vector,
simplex, ordered, positive_ordered,
corr_matrix, cov_matrix,
cholesky_corr, cholesky_cov
or '}' to close variable declarations>
Error in stanc(filename, allow_undefined = TRUE) :
failed to parse Stan model 'foo' due to the above error.
Stan does not have a proper boolean type. Like C and C++, we use integer value 0 to denote false and value 1 to denote true. To implement a boolean type in Stan, declare it as an integer with a lower bound of 0 (false) and upper bound of 1 (true).
int<lower = 0, upper = 1> c;
R distinguishes integer types from logical types, but allows a lot of conversion. For example, if we define b to be the result of comparing 1 with itself, its value is TRUE and its type is logical (logi in R):
> b = (1 == 1)
> b
[1] TRUE
> str(b)
logi TRUE
So if I write this Stan program whose behavior differs on a passed boolean,
data {
int<lower = 0, upper = 1> b;
}
parameters {
real y;
}
model {
if (b)
y ~ normal(0, 1);
else
y ~ normal(10, 10);
}
RStan is happy to coerce the boolean, so it's OK to have
fit <- sampling(model, data = list(b = b))
where the value b is a logi type in R.
I believe logicals are resolved to their integer values of 0L for FALSE and 1L for TRUE, so using int is appropriate.

Assign 3 typed numbers to a variable in Processing

I am making a paint program in Processign and want to allow the user to type 3 numbers to change int r;.
I want to know if I could do something to take three typed numbers and assign them to a single variable like int r. Such as typing 2, 5, 5, and storing them as int r =255;
You could use an array.
An array is a variable that holds multiple values.
int[] r = {1, 2, 3};
int x = r[0];
Here is the Processing array reference.
You could create your own class.
Better yet, you could create a class that keeps track of your 3 values:
class MyNumbers{
int r;
int g;
int b;
public MyNumbers(int r, int g, int b){
this.r = r;
this.g = g;
this.b = b;
}
}
Then you just create an instance of that class and pass in your values:
MyNumbers rgb = new MyNumbers(1, 2, 3);
int r = rgb.r;
Here is the Processing class reference.
You could use the color type.
If all you want to store are rgb values, consider using the existing color type in Processing:
color c = color(1, 2, 3);
int r = red(c);
Here is the Processing color reference.
You also might want to look into the ArrayList or HashMap classes.

Generate combinations ordered by an attribute

I'm looking for a way to generate combinations of objects ordered by a single attribute. I don't think lexicographical order is what I'm looking for... I'll try to give an example. Let's say I have a list of objects A,B,C,D with the attribute values I want to order by being 3,3,2,1. This gives A3, B3, C2, D1 objects. Now I want to generate combinations of 2 objects, but they need to be ordered in a descending way:
A3 B3
A3 C2
B3 C2
A3 D1
B3 D1
C2 D1
Generating all combinations and sorting them is not acceptable because the real world scenario involves large sets and millions of combinations. (set of 40, order of 8), and I need only combinations above the certain threshold.
Actually I need count of combinations above a threshold grouped by a sum of a given attribute, but I think it is far more difficult to do - so I'd settle for developing all combinations above a threshold and counting them. If that's possible at all.
EDIT - My original question wasn't very precise... I don't actually need these combinations ordered, just thought it would help to isolate combinations above a threshold. To be more precise, in the above example, giving a threshold of 5, I'm looking for an information that the given set produces 1 combination with a sum of 6 ( A3 B3 ) and 2 with a sum of 5 ( A3 C2, B3 C2). I don't actually need the combinations themselves.
I was looking into subset-sum problem, but if I understood correctly given dynamic solution it will only give you information is there a given sum or no, not count of the sums.
Thanks
Actually, I think you do want lexicographic order, but descending rather than ascending. In addition:
It's not clear to me from your description that A, B, ... D play any role in your answer (except possibly as the container for the values).
I think your question example is simply "For each integer at least 5, up to the maximum possible total of two values, how many distinct pairs from the set {3, 3, 2, 1} have sums of that integer?"
The interesting part is the early bailout, once no possible solution can be reached (remaining achievable sums are too small).
I'll post sample code later.
Here's the sample code I promised, with a few remarks following:
public class Combos {
/* permanent state for instance */
private int values[];
private int length;
/* transient state during single "count" computation */
private int n;
private int limit;
private Tally<Integer> tally;
private int best[][]; // used for early-bail-out
private void initializeForCount(int n, int limit) {
this.n = n;
this.limit = limit;
best = new int[n+1][length+1];
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= length - i; ++j) {
best[i][j] = values[j] + best[i-1][j+1];
}
}
}
private void countAt(int left, int start, int sum) {
if (left == 0) {
tally.inc(sum);
} else {
for (
int i = start;
i <= length - left
&& limit <= sum + best[left][i]; // bail-out-check
++i
) {
countAt(left - 1, i + 1, sum + values[i]);
}
}
}
public Tally<Integer> count(int n, int limit) {
tally = new Tally<Integer>();
if (n <= length) {
initializeForCount(n, limit);
countAt(n, 0, 0);
}
return tally;
}
public Combos(int[] values) {
this.values = values;
this.length = values.length;
}
}
Preface remarks:
This uses a little helper class called Tally, that just isolates the tabulation (including initialization for never-before-seen keys). I'll put it at the end.
To keep this concise, I've taken some shortcuts that aren't good practice for "real" code:
This doesn't check for a null value array, etc.
I assume that the value array is already sorted into descending order, required for the early-bail-out technique. (Good production code would include the sorting.)
I put transient data into instance variables instead of passing them as arguments among the private methods that support count. That makes this class non-thread-safe.
Explanation:
An instance of Combos is created with the (descending ordered) array of integers to combine. The value array is set up once per instance, but multiple calls to count can be made with varying population sizes and limits.
The count method triggers a (mostly) standard recursive traversal of unique combinations of n integers from values. The limit argument gives the lower bound on sums of interest.
The countAt method examines combinations of integers from values. The left argument is how many integers remain to make up n integers in a sum, start is the position in values from which to search, and sum is the partial sum.
The early-bail-out mechanism is based on computing best, a two-dimensional array that specifies the "best" sum reachable from a given state. The value in best[n][p] is the largest sum of n values beginning in position p of the original values.
The recursion of countAt bottoms out when the correct population has been accumulated; this adds the current sum (of n values) to the tally. If countAt has not bottomed out, it sweeps the values from the start-ing position to increase the current partial sum, as long as:
enough positions remain in values to achieve the specified population, and
the best (largest) subtotal remaining is big enough to make the limit.
A sample run with your question's data:
int[] values = {3, 3, 2, 1};
Combos mine = new Combos(values);
Tally<Integer> tally = mine.count(2, 5);
for (int i = 5; i < 9; ++i) {
int n = tally.get(i);
if (0 < n) {
System.out.println("found " + tally.get(i) + " sums of " + i);
}
}
produces the results you specified:
found 2 sums of 5
found 1 sums of 6
Here's the Tally code:
public static class Tally<T> {
private Map<T,Integer> tally = new HashMap<T,Integer>();
public Tally() {/* nothing */}
public void inc(T key) {
Integer value = tally.get(key);
if (value == null) {
value = Integer.valueOf(0);
}
tally.put(key, (value + 1));
}
public int get(T key) {
Integer result = tally.get(key);
return result == null ? 0 : result;
}
public Collection<T> keys() {
return tally.keySet();
}
}
I have written a class to handle common functions for working with the binomial coefficient, which is the type of problem that your problem falls under. It performs the following tasks:
Outputs all the K-indexes in a nice format for any N choose K to a file. The K-indexes can be substituted with more descriptive strings or letters. This method makes solving this type of problem quite trivial.
Converts the K-indexes to the proper index of an entry in the sorted binomial coefficient table. This technique is much faster than older published techniques that rely on iteration. It does this by using a mathematical property inherent in Pascal's Triangle. My paper talks about this. I believe I am the first to discover and publish this technique, but I could be wrong.
Converts the index in a sorted binomial coefficient table to the corresponding K-indexes.
Uses Mark Dominus method to calculate the binomial coefficient, which is much less likely to overflow and works with larger numbers.
The class is written in .NET C# and provides a way to manage the objects related to the problem (if any) by using a generic list. The constructor of this class takes a bool value called InitTable that when true will create a generic list to hold the objects to be managed. If this value is false, then it will not create the table. The table does not need to be created in order to perform the 4 above methods. Accessor methods are provided to access the table.
There is an associated test class which shows how to use the class and its methods. It has been extensively tested with 2 cases and there are no known bugs.
To read about this class and download the code, see Tablizing The Binomial Coeffieicent.
Check out this question in stackoverflow: Algorithm to return all combinations
I also just used a the java code below to generate all permutations, but it could easily be used to generate unique combination's given an index.
public static <E> E[] permutation(E[] s, int num) {//s is the input elements array and num is the number which represents the permutation
int factorial = 1;
for(int i = 2; i < s.length; i++)
factorial *= i;//calculates the factorial of (s.length - 1)
if (num/s.length >= factorial)// Optional. if the number is not in the range of [0, s.length! - 1]
return null;
for(int i = 0; i < s.length - 1; i++){//go over the array
int tempi = (num / factorial) % (s.length - i);//calculates the next cell from the cells left (the cells in the range [i, s.length - 1])
E temp = s[i + tempi];//Temporarily saves the value of the cell needed to add to the permutation this time
for(int j = i + tempi; j > i; j--)//shift all elements to "cover" the "missing" cell
s[j] = s[j-1];
s[i] = temp;//put the chosen cell in the correct spot
factorial /= (s.length - (i + 1));//updates the factorial
}
return s;
}
I am extremely sorry (after all those clarifications in the comments) to say that I could not find an efficient solution to this problem. I tried for the past hour with no results.
The reason (I think) is that this problem is very similar to problems like the traveling salesman problem. Until unless you try all the combinations, there is no way to know which attributes will add upto the threshold.
There seems to be no clever trick that can solve this class of problems.
Still there are many optimizations that you can do to the actual code.
Try sorting the data according to the attributes. You may be able to avoid processing some values from the list when you find that a higher value cannot satisfy the threshold (so all lower values can be eliminated).
If you're using C# there is a fairly good generics library here. Note though that the generation of some permutations is not in lexicographic order
Here's a recursive approach to count the number of these subsets: We define a function count(minIndex,numElements,minSum) that returns the number of subsets of size numElements whose sum is at least minSum, containing elements with indices minIndex or greater.
As in the problem statement, we sort our elements in descending order, e.g. [3,3,2,1], and call the first index zero, and the total number of elements N. We assume all elements are nonnegative. To find all 2-subsets whose sum is at least 5, we call count(0,2,5).
Sample Code (Java):
int count(int minIndex, int numElements, int minSum)
{
int total = 0;
if (numElements == 1)
{
// just count number of elements >= minSum
for (int i = minIndex; i <= N-1; i++)
if (a[i] >= minSum) total++; else break;
}
else
{
if (minSum <= 0)
{
// any subset will do (n-choose-k of them)
if (numElements <= (N-minIndex))
total = nchoosek(N-minIndex, numElements);
}
else
{
// add element a[i] to the set, and then consider the count
// for all elements to its right
for (int i = minIndex; i <= (N-numElements); i++)
total += count(i+1, numElements-1, minSum-a[i]);
}
}
return total;
}
Btw, I've run the above with an array of 40 elements, and size-8 subsets and consistently got back results in less than a second.