Objective-C(iPhone SDK) - Code for Chemical Equation Balancer help - iphone

-(IBAction) balancer: (id) sender{
double M[4][4];
M[0][0] = 6.0;
M[0][1] = 0.0;
M[0][2] = -1.0;
M[0][3] = 0.0;
M[1][0] = 12.0;
M[1][1] = 0.0;
M[1][2] = 0.0;
M[1][3] = 2.0;
M[2][0] = 6.0;
M[2][1] = 2.0;
M[2][2] = -2.0;
M[2][3] = 1.0;
M[3][0] = 0.0;
M[3][1] = 0.0;
M[3][2] = 0.0;
M[3][3] = 0.0;
int rowCount = 4;
int columnCount = 4;
int lead = 0;
for (int r = 0; r < rowCount; r++) {
if (lead >= columnCount)
break;
int i = r;
while (M[i][lead] == 0) {
i++;
if (i == rowCount) {
i = r;
lead++;
if (lead == columnCount){
break;
}
}
}
double temp[4] ;
temp[0] = M[r][0];
temp[1] = M[r][1];
temp[2] = M[r][2];
temp[3] = M[r][3];
M[r][0] = M[i][0];
M[r][1] = M[i][1];
M[r][2] = M[i][2];
M[r][3] = M[i][3];
M[i][0] = temp[0];
M[i][1] = temp[1];
M[i][2] = temp[2];
M[i][3] = temp[3];
double lv = M[r][lead];
for (int j = 0; j < columnCount; j++)
M[r][j] = M[r][j] / lv;
for (int f = 0; f < rowCount; f++) {
if (f != r) {
double l = M[f][lead];
for (int j = 0; j < columnCount; j++)
M[f][j] = M[f][j] - l * M[r][j];
}
}
lead++;
}
NSString* myNewString = [NSString stringWithFormat:#"%g",M[0][3]];
label1.text = myNewString;
}
This is returning NaN, while it should be returning .16666667 for M[0][3]. Any suggestions on how to fix this?

you are making a division to obtain the values for M[r][j], you should check that lv ! = 0.0 prior performing the division.
double TOLERANCE = 1.0E-10;
if (fabs(lv) < TOLERANCE){
NSLog(#"Division over ZERO");
exit(1);
}
[edit] Assuming that your logic is correct.

Related

Sorting NSDictionary which contains another dictionary

I face the problem, when i sort the dictionary, i can't get output from this.
here i show my NSMutableDictionary which contains.
ReasonMst is my NSMutableDictionary.
Printing description of ReasonMst:
{
1 = {
nReasonNo = 1;
vReasonCode = 1;
vReasonDesc = "Office Purpose";
vReasonType = O;
};
10 = {
nReasonNo = 10;
vReasonCode = 10;
vReasonDesc = Transit;
vReasonType = O;
};
2 = {
nReasonNo = 2;
vReasonCode = 2;
vReasonDesc = Personal;
vReasonType = O;
};
3 = {
nReasonNo = 3;
vReasonCode = 3;
vReasonDesc = Specific;
vReasonType = O;
};
4 = {
nReasonNo = 4;
vReasonCode = 4;
vReasonDesc = "Meeting";
vReasonType = I;
};
5 = {
nReasonNo = 5;
vReasonCode = 5;
vReasonDesc = "Meeting arrange";
vReasonType = I;
};
6 = {
nReasonNo = 6;
vReasonCode = 6;
vReasonDesc = "NATIONAL CONFERENCE";
vReasonType = I;
};
7 = {
nReasonNo = 7;
vReasonCode = 7;
vReasonDesc = Other;
vReasonType = O;
};
8 = {
nReasonNo = 8;
vReasonCode = 8;
vReasonDesc = "Briefing Meeting";
vReasonType = I;
};
9 = {
nReasonNo = 9;
vReasonCode = 9;
vReasonDesc = "Meeting At HO";
vReasonType = I;
};
KeyList = (
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
""
);
}
i want to sort this NSMutableDictionary to vReasonDesc wise. Can any one tell me how can i do this easiest way ?
Suppose ReasonMst is your NSMutableDictionary, do this
NSArray *key=[[NSArray alloc]initWithArray:[ReasonMst objectForKey:#"KeyList"]];
NSMutableArray *vReasonDesc=[[NSMutableArray alloc]init];
NSMutableArray *sortedKeys=[[NSMutableArray alloc]initWithArray:nil];
NSDictionary *tempDict=[[NSDictionary alloc]init];
for (int i=0; i<[key count]; i++) {
[vReasonDesc addObject:[[ReasonMst objectForKey:[key objectAtIndex:i]]objectForKey:#"vReasonDesc"]];
}
[vReasonDesc sortUsingSelector:#selector(caseInsensitiveCompare:)];
for (int i=0; i<[vReasonDesc count]; i++) {
for (int j=0; j<[key count]; j++) {
tempDict=[ReasonMst objectForKey:[key objectAtIndex:j]];
NSLog(#"%# ... %#",[vReasonDesc objectAtIndex:i], tempDict);
if ([[tempDict objectForKey:#"vReasonDesc"]isEqualToString:[vReasonDesc objectAtIndex:i]]) {
[sortedKeys addObject:[tempDict objectForKey:#"vReasonNo"]];
}
}
}
NSLog(#"sdafa %#",sortedKeys);
sortedKeys contain the keys sorted according to your vReasonDesc values... now you can access your ReasonMst according to the keys in sortedKeys which inorder.
for (int i=0; i<[sortedKeys count]; i++) {
NSLog (#"%#",[ReasonMst objectForKey:[sortedKeys objectAtIndex:i]]);
}

How to get data into NSArray from NSDictionary

i am getting following error while getting data from dictionary
"-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x4fbb80"
here is my code
NSDictionary *dic = [XMLReader dictionaryForXMLString:class.returnData error:nil];
MyGiftsarray = [[dic objectForKey:#"response"] objectForKey:#"gifts"];
for (NSDictionary *element in MyGiftsarray) {
[MyGiftsnamearray addObject:[element objectForKey:#"name"]];
[MyGiftsChkarray addObject:[element objectForKey:#"chk"]];
[MyGiftsIdarray addObject:[element objectForKey:#"id"]];
[MyGiftsApprovedarray addObject:[element objectForKey:#"approved"]];
[MyGiftsisCompletedarray addObject:[element objectForKey:#"completed"]];
}
this is NSDictionary from which i try to get data.
MyGiftsDict->(
{
Appliedpoint = 500;
Requiredpoint = 5000;
approved = N;
chk = 50;
completed = 0;
id = 66;
name = "1-800Flowers.com";
},
{
Appliedpoint = 85;
Requiredpoint = 2500;
approved = N;
chk = 25;
completed = 0;
id = 71;
name = "Bath Body Works";
},
{
Appliedpoint = 5;
Requiredpoint = 2500;
approved = N;
chk = 25;
completed = 0;
id = 75;
name = "Buca di Beppo";
},
{
Appliedpoint = 36;
Requiredpoint = 2500;
approved = N;
chk = 25;
completed = 0;
id = 66;
name = "1-800Flowers.com";
},
{
Appliedpoint = 25;
Requiredpoint = 5000;
approved = N;
chk = 50;
completed = 0;
id = 90;
name = "Jelly Belly";
},
{
Appliedpoint = 120;
Requiredpoint = 500;
approved = N;
chk = 5;
completed = 0;
id = 129;
name = "Amazon.com";
}
)
You are iterating in wrong manner-
Use -
MyGiftsDict = [[dic objectForKey:#"response"] objectForKey:#"gifts"];
And then iterate over dictionary step by step.
You need to use something like -
for(NSString *key in [MyGiftsDict allKeys])
{
[MyGiftsnamearray addObject:[MyGiftsDict objectForKey:key]];
}
Gifts is an NSDictionary in itself. It's not an NSArray! You don't need that for loop. Use simply
[MyGiftsNameArray addObject:[MyGiftsArray objectForKey:#"name"];
et cetera.
I don't think you will need the forcycle.

Instantiating C Array in Objective C - Crash Error - incorrect checksum for freed object

I am trying to setup a C style multidimensional array. It is a 301 by 16 array of float values. I am using the following code :
float ** animationArray;
animationArray = (float **)calloc(16, sizeof(float*));
for (int i=0; i<301; i++) {
animationArray[i] = (float*)calloc(301, sizeof(float));
}
int i;
for (i=0; i<301;i++) {
NSArray * animationEntry = [Animations objectAtIndex:i];
animationArray[i][0] = [[animationEntry objectAtIndex:0]doubleValue];
animationArray[i][4] = [[animationEntry objectAtIndex:1]doubleValue];
animationArray[i][8] = [[animationEntry objectAtIndex:2]doubleValue];
animationArray[i][12] = [[animationEntry objectAtIndex:3]doubleValue];
animationArray[i][1] = [[animationEntry objectAtIndex:4]doubleValue];
animationArray[i][5] = [[animationEntry objectAtIndex:5]doubleValue];
animationArray[i][9] = [[animationEntry objectAtIndex:6]doubleValue];
animationArray[i][13] = [[animationEntry objectAtIndex:7]doubleValue];
animationArray[i][2] = [[animationEntry objectAtIndex:8]doubleValue];
animationArray[i][6] = [[animationEntry objectAtIndex:9]doubleValue];
animationArray[i][10] = [[animationEntry objectAtIndex:10]doubleValue];
animationArray[i][14] = [[animationEntry objectAtIndex:11]doubleValue];
animationArray[i][3] = [[animationEntry objectAtIndex:12]doubleValue];
animationArray[i][7] = [[animationEntry objectAtIndex:13]doubleValue];
animationArray[i][11] = [[animationEntry objectAtIndex:14]doubleValue];
animationArray[i][15] = [[animationEntry objectAtIndex:15]doubleValue];
}
}
However this code causes a crash with the error "incorrect checksum for freed object - object was probably modified after being freed."
Could anyone possibly spot what is wrong ?
You switched 16 and 301 in your for loop in regards to your allocation call.
The problem seems to be here:
for (int i=0; i<16; i++) {
animationArray[i] = (float*)calloc(301, sizeof(float));
}
The var i should be 16 instead of 301, you just allocated 16 spaces.
You have inverted 16 and 301 in your declarations. So change it into:
float ** animationArray = (float **) calloc(301, sizeof(float*)); // Array of 301 float arrays
for (int i=0; i<301; i++) {
animationArray[i] = (float*)calloc(16, sizeof(float)); // Array of 16 floats
}
Also note that you can simplify the for loop as follows:
for (int i=0; i<301;i++) {
NSArray * animationEntry = [Animations objectAtIndex:i];
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 4; k++) {
animationArray[i][4*k+j] = [[animationEntry objectAtIndex:4*j+k]floatValue];
}
}
}

Noise in sound in ios 4.3.x and 5.0 after recording

I've got an app where I use Core Audio for sound recording. Sound is made from some parts and then must be saved to the device. It was working fine but in some new ios versions I have a noise, something like distortion, in output files. What is the possible reason? ExtAudioFileCreateWithURL is used to create output file and ExtAudioFileSetProperty to set its properties.
Any help will be appreciated.
This code was created by another programmer who is currently unavailable, so I don't have any idea why such hack was implemented.
The way sound buffer is created for different versions of ios:
static BOOL shouldFixData = NO;
static int checkOnce = 1;
if (checkOnce) {
checkOnce = 0;
if (inNumberFrames * 8 == ioData->mBuffers[0].mDataByteSize) {
shouldFixData = YES;
}
}
if (shouldFixData) {
AudioBufferList cutData = {0};
cutData.mNumberBuffers = 1;
cutData.mBuffers[0].mNumberChannels = ioData->mBuffers[0].mNumberChannels;
cutData.mBuffers[0].mDataByteSize = ioData->mBuffers[0].mDataByteSize / 2;
cutData.mBuffers[0].mData = malloc(cutData.mBuffers[0].mDataByteSize);
SInt32* oldData = (SInt32*)ioData->mBuffers[0].mData;
SInt32* newData = (SInt32*)cutData.mBuffers[0].mData;
int count = cutData.mBuffers[0].mDataByteSize/4;
for (int i = 0; i < count; ++i) {
newData[i] = oldData[i*2];
}
ExtAudioFileWriteAsync(userData->outputFile, inNumberFrames, &cutData);
free(cutData.mBuffers[0].mData);
} else {
ExtAudioFileWriteAsync(userData->outputFile, inNumberFrames, ioData);
}
}
Saving the record:
CAStreamBasicDescription dstFormat;
dstFormat.mSampleRate = mOutputFormat.mSampleRate;
dstFormat.mFormatID = kAudioFormatLinearPCM;
dstFormat.mChannelsPerFrame = 2;
dstFormat.mBitsPerChannel = 16;
dstFormat.mBytesPerPacket = 2 * dstFormat.mChannelsPerFrame;
dstFormat.mBytesPerFrame = 2 * dstFormat.mChannelsPerFrame;
dstFormat.mFramesPerPacket = 1;
dstFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsSignedInteger;
//recordInfo.output file is ExtAudioFileRef
err = ExtAudioFileCreateWithURL((CFURLRef)recordFileURL, kAudioFileWAVEType, &dstFormat, NULL, kAudioFileFlags_EraseFile, &recordInfo.outputFile);
if (err) { printf("ExtAudioFileCreateWithURL result %ld %08X %4.4s\n", err, (unsigned int)err, (char*)&err); return; }
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
NSComparisonResult versionCompareRes = [currSysVer compare:#"4.3" options:NSNumericSearch];
if (versionCompareRes == NSOrderedSame || versionCompareRes == NSOrderedDescending) {
//for new versions
err = ExtAudioFileSetProperty(recordInfo.outputFile, kExtAudioFileProperty_ClientDataFormat, sizeof(mOutputFormat), &mOutputFormat);
if (err) { printf("ExtAudioFileSetProperty result %ld %08X %4.4s\n", err, (unsigned int)err, (char*)&err); return; }
} else {
//for old versions
err = ExtAudioFileSetProperty(recordInfo.outputFile, kExtAudioFileProperty_ClientDataFormat, sizeof(dstFormat), &dstFormat);
if (err) { printf("ExtAudioFileSetProperty result %ld %08X %4.4s\n", err, (unsigned int)err, (char*)&err); return; }
}
sample output file:
output.mp3
You could use SPEEX to do denoising, include speex_preprocess.h first:
SpeexPreprocessState *_spt = speex_preprocess_state_init(NN, 16000);/NN is 320 for sampleRate 16000.
int i=1;
speex_preprocess_ctl(_spt, SPEEX_PREPROCESS_SET_DENOISE, &i);
-(BOOL)doConvert:(void *)data SampleLength:(SInt64)length
{
AudioBufferList *dataBuffer = (AudioBufferList*)data;
AudioSampleType *samples = (AudioSampleType*)dataBuffer->mBuffers[0].mData;
SInt64 count = length / NN;
//short sample_ground[count][NN];
short **sample_group;
sample_group = (short**)malloc(sizeof(short*)*count);
for (int i=0; i<count; i++)
sample_group[i] = (short*)malloc(sizeof(short)*NN);
for (int i = 0; i < count; i++) {
for (int j = 0 ; j < NN; j++) {
short value = samples[i*NN+j];
sample_group[i][j] = value;
}
}
for (int i = 0; i < count; i++) {
speex_preprocess_run(_spt, sample_group[i]);
}
for (int i = 0; i < count; i++) {
for (int j = 0 ; j < NN; j++) {
samples[i*NN+j] = sample_group[i][j];
}
}
for (int i=0; i<count; i++)
free(sample_group[i]);
free(sample_group);
return YES;
}
oops.. should have been feedback. Sorry..
The main difference in the code you posted is the format setup
sizeof(mOutputFormat), &mOutputFormat
where mOutputFormat not specified how its set.
compared to the dst format for older version which is set.
Setting "wrong" format usually gives bad sound :-)

To make blur effect on UIImage iphone Problem?

Hi here in this code i make the image to blur. but the problem is, it is very slow on iPhone.
here is my code.
- (UIImage*) gaussianBlur:(NSUInteger)radius
{
// Pre-calculated kernel
double dKernel[5][5]={
{1.0f/273.0f, 4.0f/273.0f, 7.0f/273.0f, 4.0f/273.0f, 1.0f/273.0f},
{4.0f/273.0f, 16.0f/273.0f, 26.0f/273.0f, 16.0f/273.0f, 4.0f/273.0f},
{7.0f/273.0f, 26.0f/273.0f, 41.0f/273.0f, 26.0f/273.0f, 7.0f/273.0f},
{4.0f/273.0f, 16.0f/273.0f, 26.0f/273.0f, 16.0f/273.0f, 4.0f/273.0f},
{1.0f/273.0f, 4.0f/273.0f, 7.0f/273.0f, 4.0f/273.0f, 1.0f/273.0f}};
NSMutableArray *kernel = [[[NSMutableArray alloc] initWithCapacity:5] autorelease];
for (int i = 0; i < 5; i++) {
NSMutableArray *row = [[[NSMutableArray alloc] initWithCapacity:5] autorelease];
for (int j = 0; j < 5; j++) {
[row addObject:[NSNumber numberWithDouble:dKernel[i][j]]];
}
[kernel addObject:row];
}
return [self applyConvolve:kernel];
}
- (UIImage*) applyConvolve:(NSArray*)kernel
{
CGImageRef inImage = self.CGImage;
CFDataRef m_DataRef = CGDataProviderCopyData(CGImageGetDataProvider(inImage));
CFDataRef m_OutDataRef = CGDataProviderCopyData(CGImageGetDataProvider(inImage));
UInt8 * m_PixelBuf = (UInt8 *) CFDataGetBytePtr(m_DataRef);
UInt8 * m_OutPixelBuf = (UInt8 *) CFDataGetBytePtr(m_OutDataRef);
int h = CGImageGetHeight(inImage);
int w = CGImageGetWidth(inImage);
int kh = [kernel count] / 2;
int kw = [[kernel objectAtIndex:0] count] / 2;
int i = 0, j = 0, n = 0, m = 0;
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
int outIndex = (i*w*4) + (j*4);
double r = 0, g = 0, b = 0;
for (n = -kh; n <= kh; n++) {
for (m = -kw; m <= kw; m++) {
if (i + n >= 0 && i + n < h) {
if (j + m >= 0 && j + m < w) {
double f = [[[kernel objectAtIndex:(n + kh)] objectAtIndex:(m + kw)] doubleValue];
if (f == 0) {continue;}
int inIndex = ((i+n)*w*4) + ((j+m)*4);
r += m_PixelBuf[inIndex] * f;
g += m_PixelBuf[inIndex + 1] * f;
b += m_PixelBuf[inIndex + 2] * f;
}
}
}
}
m_OutPixelBuf[outIndex] = SAFECOLOR((int)r);
m_OutPixelBuf[outIndex + 1] = SAFECOLOR((int)g);
m_OutPixelBuf[outIndex + 2] = SAFECOLOR((int)b);
m_OutPixelBuf[outIndex + 3] = 255;
}
}
CGContextRef ctx = CGBitmapContextCreate(m_OutPixelBuf,
CGImageGetWidth(inImage),
CGImageGetHeight(inImage),
CGImageGetBitsPerComponent(inImage),
CGImageGetBytesPerRow(inImage),
CGImageGetColorSpace(inImage),
CGImageGetBitmapInfo(inImage)
);
CGImageRef imageRef = CGBitmapContextCreateImage(ctx);
CGContextRelease(ctx);
UIImage *finalImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
CFRelease(m_DataRef);
CFRelease(m_OutDataRef);
return finalImage;
}
A 2-d Gaussian convolution is separable, which means it can be done as 2 1-d convolutions, one horizontal and one vertical. That should save you a bit of time.
http://en.wikipedia.org/wiki/Gaussian_blur#Implementation