I am trying to create a table which is unique and has primary key. I know in sqlite we can develop Unique AUTOINCREMENT ID SQL AUTOINCREMENT, but is it possible to generate Unique GUID which is 36 chars long. The only reason to do that is to make it more unique.
This is the bit of code I use for UUIDs (I may have even found it here on Stack Overflow)...
+ (NSString *)GetUUID
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return [(NSString *)string autorelease];
}
I don't know how long the UUIDs generated are because in the ways I use it I don't care so perhaps check that by passing the result into a NSLog call.
HTH, Pedro :)
I user this code to generate guids on the iphone - category on NSString. Can't remember where I found it, but it works great.
#import "NSString_UniqueID.h"
static unichar x (unsigned int);
#implementation NSString (TWUUID)
+ (NSString*) stringWithUniqueId
{
CFUUIDRef uuid = CFUUIDCreate(NULL);
CFUUIDBytes b = CFUUIDGetUUIDBytes(uuid);
unichar unichars[22];
unichar* c = unichars;
*c++ = x(b.byte0 >> 2);
*c++ = x((b.byte0 & 3 << 4) + (b.byte1 >> 4));
*c++ = x((b.byte1 & 15 << 2) + (b.byte2 >> 6));
*c++ = x(b.byte2 & 63);
*c++ = x(b.byte3 >> 2);
*c++ = x((b.byte3 & 3 << 4) + (b.byte4 >> 4));
*c++ = x((b.byte4 & 15 << 2) + (b.byte5 >> 6));
*c++ = x(b.byte5 & 63);
*c++ = x(b.byte6 >> 2);
*c++ = x((b.byte6 & 3 << 4) + (b.byte7 >> 4));
*c++ = x((b.byte7 & 15 << 2) + (b.byte8 >> 6));
*c++ = x(b.byte8 & 63);
*c++ = x(b.byte9 >> 2);
*c++ = x((b.byte9 & 3 << 4) + (b.byte10 >> 4));
*c++ = x((b.byte10 & 15 << 2) + (b.byte11 >> 6));
*c++ = x(b.byte11 & 63);
*c++ = x(b.byte12 >> 2);
*c++ = x((b.byte12 & 3 << 4) + (b.byte13 >> 4));
*c++ = x((b.byte13 & 15 << 2) + (b.byte14 >> 6));
*c++ = x(b.byte14 & 63);
*c++ = x(b.byte15 >> 2);
*c = x(b.byte15 & 3);
CFRelease(uuid);
return [NSString stringWithCharacters: unichars length: 22];
}
#end
// Convert six-bit values into letters, numbers or _ or $ (64 characters in that set).
//------------------------------------------------------------------------------------
unichar x (unsigned int c)
{
if (c < 26) return 'a' + c;
if (c < 52) return 'A' + c - 26;
if (c < 62) return '0' + c - 52;
if (c == 62) return '$';
return '_';
}
Related
I would like to do the following:
db
.getCollection('COLLECTION')
.find({ $where : function() { return NUUID(this.Col1) != this.Col2 }})
Where Col1 contains NUUID strings and Col2 contains NUUIDs.
I would like rows where the NUUID value of Col1 (which is a string) is not equal to Col2.
I receive the error: ReferenceError: NUUID is not defined
Using https://github.com/mongodb/mongo-csharp-driver/blob/master/uuidhelpers.js , the solution is:
db
.getCollection('TestColl')
.find({$where: function(){
function CSUUID(uuid) {
var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters
var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2);
var b = hex.substr(10, 2) + hex.substr(8, 2);
var c = hex.substr(14, 2) + hex.substr(12, 2);
var d = hex.substr(16, 16);
hex = a + b + c + d;
var base64 = HexToBase64(hex);
return new BinData(3, base64);
}
function HexToBase64(hex) {
var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64 = "";
var group;
for (var i = 0; i < 30; i += 6) {
group = parseInt(hex.substr(i, 6), 16);
base64 += base64Digits[(group >> 18) & 0x3f];
base64 += base64Digits[(group >> 12) & 0x3f];
base64 += base64Digits[(group >> 6) & 0x3f];
base64 += base64Digits[group & 0x3f];
}
group = parseInt(hex.substr(30, 2), 16);
base64 += base64Digits[(group >> 2) & 0x3f];
base64 += base64Digits[(group << 4) & 0x3f];
base64 += "==";
return base64;
}
return CSUUID(this['Col1']).toString() != this['Col2'].toString()
}
})
I have tried to do a simple fft and compare the results between MATLAB and CUDA.
MATLAB:
Vector of 9 numbers 1-9
I = [1 2 3 4 5 6 7 8 9];
and use this code:
fft(I)
gives the results:
45.0000 + 0.0000i
-4.5000 +12.3636i
-4.5000 + 5.3629i
-4.5000 + 2.5981i
-4.5000 + 0.7935i
-4.5000 - 0.7935i
-4.5000 - 2.5981i
-4.5000 - 5.3629i
-4.5000 -12.3636i
And CUDA code:
int FFT_Test_Function() {
int n = 9;
double* in = new double[n];
Complex* out = new Complex[n];
for (int i = 0; i<n; i++)
{
in[i] = i + 1;
}
// Allocate the buffer
cufftDoubleReal *d_in;
cufftDoubleComplex *d_out;
unsigned int out_mem_size = sizeof(cufftDoubleComplex)*n;
unsigned int in_mem_size = sizeof(cufftDoubleReal)*n;
cudaMalloc((void **)&d_in, in_mem_size);
cudaMalloc((void **)&d_out, out_mem_size);
// Save time stamp
milliseconds timeStart = getCurrentTimeStamp();
cufftHandle plan;
cufftResult res = cufftPlan1d(&plan, n, CUFFT_D2Z, 1);
if (res != CUFFT_SUCCESS) { cout << "cufft plan error: " << res << endl; return 1; }
cudaCheckErrors("cuda malloc fail");
cudaMemcpy(d_in, in, in_mem_size, cudaMemcpyHostToDevice);
cudaCheckErrors("cuda memcpy H2D fail");
res = cufftExecD2Z(plan, d_in, d_out);
if (res != CUFFT_SUCCESS) { cout << "cufft exec error: " << res << endl; return 1; }
cudaMemcpy(out, d_out, out_mem_size, cudaMemcpyDeviceToHost);
cudaCheckErrors("cuda memcpy D2H fail");
milliseconds timeEnd = getCurrentTimeStamp();
milliseconds totalTime = timeEnd - timeStart;
std::cout << "Total time: " << totalTime.count() << std::endl;
return 0;
}
In this CUDA code i got the result:
You can see that CUDA gives 4 zero's (cells 5-9).
What am i missed?
Thank you very much for your attention!
CUFFT_D2Z is a real-to-complex FFT, so the top N/2 - 1 points in the output data are redundant - they are just the complex conjugate of the bottom half of the transform (you can see this in the MATLAB output if you compare pairs of terms which are mirrored about the mid-point).
You can fill in these "missing" terms if you need them, by just taking the complex conjugate of each corresponding term, but usually there isn't much point in doing this.
i need to recreate this within Java for Blackberry device:
char cPacketData[1024];
int thisPacketLength=( X_PACKET_SPACE*12 ) + ( 20*X_PACKET_SPACE );
(*(int *) (cPacketData)) =X_PACKET_START;
(*(int *) (cPacketData+X_PACKET_SPACE)) =thisPacketLength;
(*(int *) (cPacketData+X_PACKET_SPACE*2)) =X_PACKET_POSITION_DATA;
(*(int *) (cPacketData+X_PACKET_SPACE*3)) =positionX;
(*(int *) (cPacketData+X_PACKET_SPACE*4)) =positionY;
send(mSocket,(const char *)&cPacketData,thisPacketLength,0);
I already know that i should use
OutputStreamWriter
but i don't know how to recreate that packet in Java, can you please help?
UPDATE
Ok, think i've got it right:
char[] payload = new char[100];
int start=9999;
payload[3] = (char)((start >> 24) & 0XFF);
payload[2] = (char)((start >> 16) & 0XFF);
payload[1] = (char)((start >> 8) & 0XFF);
payload[0] = (char)((start >> 0) & 0XFF);
int len=100;
payload[X_PACKET_SPACE+3] = (char)((len >> 24) & 0XFF);
payload[X_PACKET_SPACE+2] = (char)((len >> 16) & 0XFF);
payload[X_PACKET_SPACE+1] = (char)((len >> 8) & 0XFF);
payload[X_PACKET_SPACE] = (char)((len >> 0) & 0XFF);
_out.write(payload);
Seems to work fine, kinda 'oldsKewl' way of doing - so i would appreciate if you guys have any better option.
Just to confirm, it works by doing it this way.
Resolved
Here is how i do it, so that my server side can recv the packets from BB correctly.
OutputStream _out = conn.openOutputStream();
packet[3]= (byte)(9999 >>> 24);
packet[2]= (byte)(9999 >>> 16);
packet[1]= (byte)(9999 >>> 8);
packet[0]= (byte)(9999 >>> 0);
packet[8]= (byte)(60 >>> 24);
packet[7]= (byte)(60 >>> 16);
packet[6]= (byte)(60 >>> 8);
packet[5]= (byte)(60 >>> 0);
packet[13]= (byte)(4 >>> 24);
packet[12]= (byte)(4 >>> 16);
packet[11]= (byte)(4 >>> 8);
packet[10]= (byte)(4 >>> 0);
packet[18]= (byte)(_PIN >>> 24);
packet[17]= (byte)(_PIN >>> 16);
packet[16]= (byte)(_PIN >>> 8);
packet[15]= (byte)(_PIN >>> 0);
packet[23]= (byte)(1 >>> 24);
packet[22]= (byte)(1 >>> 16);
packet[21]= (byte)(1 >>> 8);
packet[20]= (byte)(1 >>> 0);
_out.write(packet,0,60);
I get KERN_PROTECTION_FAILURE somewhere (stack trace shows it's happening in main loop but won't give me more details because it seems that memory got corrupted in previous loop. I have all the settings to see debug output correctly)
When I remove calling the following code, the symptom goes away.
(Verify receipt for in App purchasee)
- (NSString *)encode:(const uint8_t *)input length:(NSInteger)length {
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData *data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t *output = (uint8_t *)data.mutableBytes;
for (NSInteger i = 0; i < length; i += 3) {
NSInteger value = 0;
for (NSInteger j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
NSInteger index = (i / 3) * 4;
output[index + 0] = table[(value >> 18) & 0x3F];
output[index + 1] = table[(value >> 12) & 0x3F];
output[index + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
output[index + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
}
return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
}
I see there are other ways of getting base64 encoding, How do I do base64 encoding on iphone-sdk?
What I find weird is that the 'length' is computed differently.
((length +2 /3) * 4 above, and lentext*4/3+4 below.
Can anyone tell what is going on?
Beside, using the below code, I get 'receipt data-malformed' error when I pass the encoded data to apple server.
+ (NSString *) base64StringFromData: (NSData *)data length: (int)length {
int lentext = [data length];
if (lentext < 1) return #"";
char *outbuf = malloc(lentext*4/3+4); // add 4 to be sure
if ( !outbuf ) return nil;
const unsigned char *raw = [data bytes];
int inp = 0;
int outp = 0;
int do_now = lentext - (lentext%3);
for ( outp = 0, inp = 0; inp < do_now; inp += 3 )
{
outbuf[outp++] = base64EncodingTable[(raw[inp] & 0xFC) >> 2];
outbuf[outp++] = base64EncodingTable[((raw[inp] & 0x03) << 4) | ((raw[inp+1] & 0xF0) >> 4)];
outbuf[outp++] = base64EncodingTable[((raw[inp+1] & 0x0F) << 2) | ((raw[inp+2] & 0xC0) >> 6)];
outbuf[outp++] = base64EncodingTable[raw[inp+2] & 0x3F];
}
if ( do_now < lentext )
{
char tmpbuf[2] = {0,0};
int left = lentext%3;
for ( int i=0; i < left; i++ )
{
tmpbuf[i] = raw[do_now+i];
}
raw = tmpbuf;
outbuf[outp++] = base64EncodingTable[(raw[inp] & 0xFC) >> 2];
outbuf[outp++] = base64EncodingTable[((raw[inp] & 0x03) << 4) | ((raw[inp+1] & 0xF0) >> 4)];
if ( left == 2 ) outbuf[outp++] = base64EncodingTable[((raw[inp+1] & 0x0F) << 2) | ((raw[inp+2] & 0xC0) >> 6)];
}
NSString *ret = [[[NSString alloc] initWithBytes:outbuf length:outp encoding:NSASCIIStringEncoding] autorelease];
free(outbuf);
return ret;
}
I’m using this very small library for encode/decode Base64: http://imthi.com/blog/programming/iphone-sdk-base64-encode-decode.php
It does its work and I assume you use a similar version of it. Did you try to call +initialize before the first usage?
I was puzzled with one of the question in Microsoft interview which is as given below:
A function should accept a range( 3 - 21 ) and it should print all the consecutive numbers combinations to form each number as given below:
3 = 1+2
5 = 2+3
6 = 1+2+3
7 = 3+4
9 = 4+5
10 = 1+2+3+4
11 = 5+6
12 = 3+4+5
13 = 6+7
14 = 2+3+4+5
15 = 1+2+3+4+5
17 = 8+9
18 = 5+6+7
19 = 9+10
20 = 2+3+4+5+6
21 = 10+11
21 = 1+2+3+4+5+6
could you please help me in forming this sequence in C#?
Thanks,
Mahesh
So here is a straightforward/naive answer (in C++, and not tested; but you should be able to translate). It uses the fact that
1 + 2 + ... + n = n(n+1)/2,
which you have probably seen before. There are lots of easy optimisations that can be made here which I have omitted for clarity.
void WriteAsSums (int n)
{
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
if (n = (j * (j+1) - i * (i+1))/2) // then n = (i+1) + (i+2) + ... + (j-1) + j
{
std::cout << n << " = ";
for (int k = i + 1; k <= j; k++)
{
std::cout << k;
if (k != j) // this is not the interesting bit
std::cout << std::endl;
else
std::cout << " + ";
}
}
}
}
}
This is some pseudo code to find all the combinations if any exists:
function consecutive_numbers(n, m)
list = [] // empty list
list.push_back(m)
while m != n
if m > n
first = list.remove_first
m -= first
else
last = list.last_element
if last <= 1
return []
end
list.push_back(last - 1)
m += last - 1
end
end
return list
end
function all_consecutive_numbers(n)
m = n / 2 + 1
a = consecutive_numbers(n, m)
while a != []
print_combination(n, a)
m = a.first - 1
a = consecutive_numbers(n, m)
end
end
function print_combination(n, a)
print(n + " = ")
print(a.remove_first)
foreach element in a
print(" + " + element)
end
print("\n")
end
A call to all_consecutive_numbers(21) would print:
21 = 11 + 10
21 = 8 + 7 + 6
21 = 6 + 5 + 4 + 3 + 2 + 1
I tested it in ruby (code here) and it seems to work. I'm sure the basic idea could easily be implemented in C# as well.
I like this problem. Here is a slick and slightly mysterious O(n) solution:
void DisplaySum (int n, int a, int b)
{
std::cout << n << " = ";
for (int i = a; i < b; i++) std::cout << i << " + ";
std::cout << b;
}
void WriteAsSums (int n)
{
N = 2*n;
for (int i = 1; i < N; i++)
{
if (~(N%i))
{
int j = N/i;
if (j+i%2)
{
int a = (j+i-1)/2;
int b = (j-i+1)/2;
if (a>0 & a<b) // exclude trivial & negative solutions
DisplaySum(n,a,b);
}
}
}
}
Here's something in Groovy, you should be able to understand what's going on. It's not the most efficient code and doesn't create the answers in the order you cite in your question (you seem to be missing some though) but it might give you a start.
def f(a,b) {
for (i in a..b) {
for (j in 1..i/2) {
def (sum, str, k) = [ 0, "", j ]
while (sum < i) {
sum += k
str += "+$k"
k++
}
if (sum == i) println "$i=${str[1..-1]}"
}
}
}
Output for f(3,21) is:
3=1+2
5=2+3
6=1+2+3
7=3+4
9=2+3+4
9=4+5
10=1+2+3+4
11=5+6
12=3+4+5
13=6+7
14=2+3+4+5
15=1+2+3+4+5
15=4+5+6
15=7+8
17=8+9
18=3+4+5+6
18=5+6+7
19=9+10
20=2+3+4+5+6
21=1+2+3+4+5+6
21=6+7+8
21=10+11
Hope this helps. It kind of conforms to the tenet of doing the simplest thing that could possibly work.
if we slice a into 2 digit, then a = b + (b+1) = 2*b + (0+1)
if we slice a into 3 digit, then a = b + (b+1) + (b+2) = 3*b + (0+1+2)
...
if we slice a into n digit, then a = b + (b+1) +...+ (b+n) = nb + (0+1+n-1)
the last result is a = nb + n*(n-1)/2, a,b,n are all ints.
so O(N) Algorithm is:
void seq_sum(int a)
{
// start from 2 digits
int n=2;
while(1)
{
int value = a-n*(n-1)/2;
if(value < 0)
break;
// meet the quotation we deduct
if( value%n == 0 )
{
int b=value/n;
// omit the print stage
print("......");
}
n++;
}
}