Search Results

Search found 165 results on 7 pages for 'cmp'.

Page 2/7 | < Previous Page | 1 2 3 4 5 6 7  | Next Page >

  • Linux. Compare binary files

    - by frustratedCmpNoLongerUser
    I need to compare two binary files and get output in form for every different byte. So if file1.bin is 00 90 00 11 in binary form and file2.bin is 00 91 00 10 I want to get something like 00000001 90 91 00000003 11 10 what is the easiest way to accomplish the goal? Standard tool? Some 3rd party tool? inb4: cmp -l should be killed with fire,it uses decimal system for offsets and octal for bytes. "Consistency for losers" must be cmp's motto.

    Read the article

  • Assembly load and execute issue

    - by Jean Carlos Suárez Marranzini
    I'm trying to develop Assembly code allowing me to load and execute(by input of the user) 2 other Assembly .EXE programs. I'm having two problems: -I don't seem to be able to assign the pathname to a valid register(Or maybe incorrect syntax) -I need to be able to execute the other program after the first one (could be either) started its execution. This is what I have so far: mov ax,cs ; moving code segment to data segment mov ds,ax mov ah,1h ; here I read from keyboard int 21h mov dl,al cmp al,'1' ; if 1 jump to LOADRUN1 JE LOADRUN1 popf cmp al,'2' ; if 1 jump to LOADRUN2 JE LOADRUN2 popf LOADRUN1: MOV AH,4BH MOV AL,00 LEA DX,[PROGNAME1] ; Not sure if it works INT 21H LOADRUN2: MOV AH,4BH MOV AL,00 LEA DX,[PROGNAME2] ; Not sure if it works INT 21H ; Here I define the bytes containing the pathnames PROGNAME1 db 'C:\Users\Usuario\NASM\Adding.exe',0 PROGNAME2 db 'C:\Users\Usuario\NASM\Substracting.exe',0 I just don't know how start another program by input in the 'parent' program, after one is already executing. Thanks in advance for your help! Any additional information I'll be more than happy to provide. -I'm using NASM 16 bits, Windows 7 32 bits.

    Read the article

  • Android Permission Issue android.permission.READ_CONTACTS

    - by jkmcgee
    Hello, All I am trying to do is read a contact off of my emulator and display it to the screen. I can't seem to resolve this error. Both of my packages (com.msi.ibm.tutorial and .MobileServiceCallContacts) have the permission READ_CONTACTS set in their manifest xml files. So any ideas as to what I've got wrong ? Here is the error message from eclipse console if it helps, it's not helping me, but I'm a little rusty at this and completely new to Android development. MobileServiceCallContacts]Starting activity com.msi.ibm.tutorial.MobileServiceCallContacts on device MobileServiceCallContacts]ActivityManager: Starting: Intent { cmp=com.msi.ibm.tutorial/.MobileServiceCallContacts } MobileServiceCallContacts]ActivityManager: java.lang.SecurityException: Permission Denial: starting Intent { flg=0x10000000 cmp=com.msi.ibm.tutorial/.MobileServiceCallContacts } from null (pid=-1, uid=-1) requires android.permission.READ_CONTACTS

    Read the article

  • android service onBind SecurityException

    - by Metalex
    I don't know why but in some devices my service isn't allowed to bind. java.lang.RuntimeException: Unable to create application mypackage.MyApplication: java.lang.SecurityException: Unable to find app for caller android.app.ApplicationThreadProxy@41680e78 (pid=16805) when binding service Intent { cmp=mypackage/.MyService } at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4394) at android.app.ActivityThread.access$1300(ActivityThread.java:141) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1294) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5039) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.SecurityException: Unable to find app for caller android.app.ApplicationThreadProxy@41680e78 (pid=16805) when binding service Intent { cmp=mypackage/.MyService } at android.os.Parcel.readException(Parcel.java:1425) at android.os.Parcel.readException(Parcel.java:1379) at android.app.ActivityManagerProxy.bindService(ActivityManagerNative.java:2720) at android.app.ContextImpl.bindService(ContextImpl.java:1431) at android.app.ContextImpl.bindService(ContextImpl.java:1407) at android.content.ContextWrapper.bindService(ContextWrapper.java:473) at mypackage.MyApplication.openService(MyApplication.java:151) at mypackage.MyApplication.onCreate(MyApplication.java:110) at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1000) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4391) ... 10 more java.lang.SecurityException: Unable to find app for caller android.app.ApplicationThreadProxy@41680e78 (pid=16805) when binding service Intent { cmp=mypackage/.MyService } at android.os.Parcel.readException(Parcel.java:1425) at android.os.Parcel.readException(Parcel.java:1379) at android.app.ActivityManagerProxy.bindService(ActivityManagerNative.java:2720) at android.app.ContextImpl.bindService(ContextImpl.java:1431) at android.app.ContextImpl.bindService(ContextImpl.java:1407) at android.content.ContextWrapper.bindService(ContextWrapper.java:473) at mypackage.MyApplication.openService(MyApplication.java:151) at mypackage.MyApplication.onCreate(MyApplication.java:110) at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1000) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4391) at android.app.ActivityThread.access$1300(ActivityThread.java:141) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1294) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5039) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) at dalvik.system.NativeStart.main(Native Method) Code from MyApplication: @Override public void onCreate() { super.onCreate(); openService(); } public void openService() { Intent service = new Intent(this, MyService.class); mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = IMyService.Stub.asInterface(service); if (mListener != null) { mListener.onServiceStarted(mService); } } @Override public void onServiceDisconnected(ComponentName cn) { mService = null; } }; bindService(service, mConnection, Context.BIND_AUTO_CREATE); // 151 line } Please help me! Thank you!

    Read the article

  • adding nodes to a binary search tree randomly deletes nodes

    - by SDLFunTimes
    Hi, stack. I've got a binary tree of type TYPE (TYPE is a typedef of data*) that can add and remove elements. However for some reason certain values added will overwrite previous elements. Here's my code with examples of it inserting without overwriting elements and it not overwriting elements. the data I'm storing: struct data { int number; char *name; }; typedef struct data data; # ifndef TYPE # define TYPE data* # define TYPE_SIZE sizeof(data*) # endif The tree struct: struct Node { TYPE val; struct Node *left; struct Node *rght; }; struct BSTree { struct Node *root; int cnt; }; The comparator for the data. int compare(TYPE left, TYPE right) { int left_len; int right_len; int shortest_string; /* find longest string */ left_len = strlen(left->name); right_len = strlen(right->name); if(right_len < left_len) { shortest_string = right_len; } else { shortest_string = left_len; } /* compare strings */ if(strncmp(left->name, right->name, shortest_string) > 1) { return 1; } else if(strncmp(left->name, right->name, shortest_string) < 1) { return -1; } else { /* strings are equal */ if(left->number > right->number) { return 1; } else if(left->number < right->number) { return -1; } else { return 0; } } } And the add method struct Node* _addNode(struct Node* cur, TYPE val) { if(cur == NULL) { /* no root has been made */ cur = _createNode(val); return cur; } else { int cmp; cmp = compare(cur->val, val); if(cmp == -1) { /* go left */ if(cur->left == NULL) { printf("adding on left node val %d\n", cur->val->number); cur->left = _createNode(val); } else { return _addNode(cur->left, val); } } else if(cmp >= 0) { /* go right */ if(cur->rght == NULL) { printf("adding on right node val %d\n", cur->val->number); cur->rght = _createNode(val); } else { return _addNode(cur->rght, val); } } return cur; } } void addBSTree(struct BSTree *tree, TYPE val) { tree->root = _addNode(tree->root, val); tree->cnt++; } The function to print the tree: void printTree(struct Node *cur) { if (cur == 0) { printf("\n"); } else { printf("("); printTree(cur->left); printf(" %s, %d ", cur->val->name, cur->val->number); printTree(cur->rght); printf(")\n"); } } Here's an example of some data that will overwrite previous elements: struct BSTree myTree; struct data myData1, myData2, myData3; myData1.number = 5; myData1.name = "rooty"; myData2.number = 1; myData2.name = "lefty"; myData3.number = 10; myData3.name = "righty"; initBSTree(&myTree); addBSTree(&myTree, &myData1); addBSTree(&myTree, &myData2); addBSTree(&myTree, &myData3); printTree(myTree.root); Which will print: (( righty, 10 ) lefty, 1 ) Finally here's some test data that will go in the exact same spot as the previous data, but this time no data is overwritten: struct BSTree myTree; struct data myData1, myData2, myData3; myData1.number = 5; myData1.name = "i"; myData2.number = 5; myData2.name = "h"; myData3.number = 5; myData3.name = "j"; initBSTree(&myTree); addBSTree(&myTree, &myData1); addBSTree(&myTree, &myData2); addBSTree(&myTree, &myData3); printTree(myTree.root); Which prints: (( j, 5 ) i, 5 ( h, 5 ) ) Does anyone know what might be going wrong? Sorry if this post was kind of long.

    Read the article

  • Assembly Jump conditionals -- jae vs. jbe

    - by Raven Dreamer
    Hi, all! I'm working on an assembly program (intel 8086). I'm trying to determine whether an input character (stored in dl) is within a certain range of hex values. cmp dl, 2Eh ;checks for periods je print ;jumps to print a "." input cmp dl, 7Ah ;checks for outside of wanted range jae input ; returns to top Please confirm that this is a correct interpretation of my code: step 1: if dl = 2E, goto print Step 2: if dl = 7A is false, goto input [if dl < 7A, goto input]

    Read the article

  • extjs4 display tooltip on button click instead of mouse hover

    - by user856753
    I am trying to add a on click listener to the below tooltip. I do not want the tooltip to display on mouse hover. Instead it need it show on button click. Do I have to add a handler function inside a listener? { xtype: 'button', cls:'my-btn', iconCls:'question', src:'../www/css/slate/btn/question.png', padding: '5 0 0 0', listeners: { render: function(cmp) { Ext.create('Ext.tip.ToolTip', { closable:true, hideDelay : 3000, padding: '0 0 0 0', maxWidth:400, width:800, target: cmp.el, html: "<b>read-only</b>:Users will have read only access to all pages", getTargetXY: function() { return [810, 340]; } }); } } },

    Read the article

  • sorting a list of objects by value php

    - by Mike
    I have a list of objects: class Beer { var $name; var $id; var $style; var $brewery; var $rate; function getName() { return $this->name; } function getID() { return $this->id; } function getStyle() { return $this->style; } function getBrewery() { return $this->brewery; } function getRate() { return $this->rate; } } After doing some research online on how to accomplish this, this is my code: usort($localBeersList, "cmp"); function cmp($a, $b) { if ($a->getRate() == $b->getRate()) { return 0; } return ($a->getRate() < $b->getRate()) ? -1 : 1; } If I try and output my list after this I do not get anything.

    Read the article

  • PHP sorting an array by mysql date.

    - by daviemanchester
    Hi I have an array that I would like to sort using a date field from a mysql database. Here is a sample of the array which is named 'news' in my class: [48] => Array ( [id] => 14 [type] => 3 [updated] => 2010-04-17 13:54:42 ) [49] => Array ( [id] => 15 [type] => 3 [updated] => 2010-04-17 13:57:21 ) I want to sort de by the 'updated' field. I have some code I have started but am unsure how to complete it and get it working. function sortNews($x) { usort($this->news, array("ProcessClass", "cmp")); //correct sort type? } function cmp($a, $b) { ...................................... missing code } Can anyone help??

    Read the article

  • Efficient inline templates and C++

    - by Darryl Gove
    I've talked before about calling inline templates from C++, I've also talked about calling inline templates efficiently. This time I want to talk about efficiently calling inline templates from C++. The obvious starting point is that I need to declare the inline templates as being extern "C": extern "C" { int mytemplate(int); } This enables us to call it, but the call may not be very efficient because the compiler will treat it as a function call, and may produce suboptimal code based on that premise. So we need to add the no_side_effect pragma: extern "C" { int mytemplate(int); #pragma no_side_effect(mytemplate) } However, this may still not produce optimal code. We've discussed how the no_side_effect pragma cannot be combined with exceptions, well we know that the code cannot produce exceptions, but the compiler doesn't know that. If we tell the compiler that information it may be able to produce even better code. We can do this by adding the "throw()" keyword to the template declaration: extern "C" { int mytemplate(int) throw(); #pragma no_side_effect(mytemplate) } The following is an example of how these changes might improve performance. We can take our previous example code and migrate it to C++, adding the use of a try...catch construct: #include <iostream extern "C" { int lzd(int); #pragma no_side_effect(lzd) } int a; int c=0; class myclass { int routine(); }; int myclass::routine() { try { for(a=0; a<1000; a++) { c=lzd(c); } } catch(...) { std::cout << "Something happened" << std::endl; } return 0; } Compiling this produces a slightly suboptimal code sequence in the hot loop: $ CC -O -xtarget=T4 -S t.cpp t.il ... /* 0x0014 23 */ lzd %o0,%o0 /* 0x0018 21 */ add %l6,1,%l6 /* 0x001c */ cmp %l6,1000 /* 0x0020 */ bl,pt %icc,.L77000033 /* 0x0024 23 */ st %o0,[%l7] There's a store in the delay slot of the branch, so we're repeatedly storing data back to memory. If we change the function declaration to include "throw()", we get better code: $ CC -O -xtarget=T4 -S t.cpp t.il ... /* 0x0014 21 */ add %i1,1,%i1 /* 0x0018 23 */ lzd %o0,%o0 /* 0x001c 21 */ cmp %i1,999 /* 0x0020 */ ble,pt %icc,.L77000019 /* 0x0024 */ nop The store has gone, but the code is still suboptimal - there's a nop in the delay slot rather than useful work. However, it's good enough for this example. The point I'm making is that the compiler produces the better code with both the "throw()" and the no side effect pragma.

    Read the article

  • Inline template efficiency

    - by Darryl Gove
    I like inline templates, and use them quite extensively. Whenever I write code with them I'm always careful to check the disassembly to see that the resulting output is efficient. Here's a potential cause of inefficiency. Suppose we want to use the mis-named Leading Zero Detect (LZD) instruction on T4 (this instruction does a count of the number of leading zero bits in an integer register - so it should really be called leading zero count). So we put together an inline template called lzd.il looking like: .inline lzd lzd %o0,%o0 .end And we throw together some code that uses it: int lzd(int); int a; int c=0; int main() { for(a=0; a<1000; a++) { c=lzd(c); } return 0; } We compile the code with some amount of optimisation, and look at the resulting code: $ cc -O -xtarget=T4 -S lzd.c lzd.il $ more lzd.s .L77000018: /* 0x001c 11 */ lzd %o0,%o0 /* 0x0020 9 */ ld [%i1],%i3 /* 0x0024 11 */ st %o0,[%i2] /* 0x0028 9 */ add %i3,1,%i0 /* 0x002c */ cmp %i0,999 /* 0x0030 */ ble,pt %icc,.L77000018 /* 0x0034 */ st %i0,[%i1] What is surprising is that we're seeing a number of loads and stores in the code. Everything could be held in registers, so why is this happening? The problem is that the code is only inlined at the code generation stage - when the actual instructions are generated. Earlier compiler phases see a function call. The called functions can do all kinds of nastiness to global variables (like 'a' in this code) so we need to load them from memory after the function call, and store them to memory before the function call. Fortunately we can use a #pragma directive to tell the compiler that the routine lzd() has no side effects - meaning that it does not read or write to memory. The directive to do that is #pragma no_side_effect(<routine name), and it needs to be placed after the declaration of the function. The new code looks like: int lzd(int); #pragma no_side_effect(lzd) int a; int c=0; int main() { for(a=0; a<1000; a++) { c=lzd(c); } return 0; } Now the loop looks much neater: /* 0x0014 10 */ add %i1,1,%i1 ! 11 ! { ! 12 ! c=lzd(c); /* 0x0018 12 */ lzd %o0,%o0 /* 0x001c 10 */ cmp %i1,999 /* 0x0020 */ ble,pt %icc,.L77000018 /* 0x0024 */ nop

    Read the article

  • Advanced Linux file permission question (ownership change during write operation)

    - by Kent
    By default the umask is 0022: usera@cmp$ touch somefile; ls -l total 0 -rw-r--r-- 1 usera usera 0 2009-09-22 22:30 somefile The directory /home/shared/ is meant for shared files and should be owned by root and the shared group. Files created here by usern (any user) are automatically owned by the shared group. There is a cron-job taking care of changing owning user and owning group (of any moved files) once per day: usera@cmp$ cat /etc/cron.daily/sharedscript #!/bin/bash chown -R root:shared /home/shared/ chmod -R 770 /home/shared/ I was writing a really large file to the shared directory. It had me (usera) as owning user and the shared group as group owner. During the write operation the cron job was run, and I still had no problem completing the write process. You see. I thought this would happen: I am writing the file. The file permissions and ownership data for the file looks like this: -rw-r--r-- usera shared The cron job kicks in! The chown line is processed and now the file is owned by the root user and the shared group. As the owning group only has read access to the file I get a file write error! Boom! End of story. Why did the operation succeed? A link to some kind of reference documentation to back up the reason would be very welcome (as I could use it to study more details).

    Read the article

  • Twitter 2 for Android crash every time I try uploading multi photos [closed]

    - by Hazz
    Hello, I'm using the new Twitter 2 on Android 2.1. Whenever I hit the button which enables me to upload multiple photos in a single tweet, I always get the error "The application Camera (process com.sonyericsson.camera) has stopped unexpectidly. Please try again". However, uploading a single photo using the camera button in Twitter have no problem, it works. My phone is Sony Ericsson x10 mini pro. I tried signing out and back in, same result. Anything I can do to fix this? This is the log info I got using Log Collector: 02-23 15:05:57.328 I/ActivityManager( 1240): Starting activity: Intent { act=com.twitter.android.post.status cmp=com.twitter.android/.PostActivity } 02-23 15:05:57.338 D/PhoneWindow(15095): couldn't save which view has focus because the focused view com.android.internal.policy.impl.PhoneWindow$DecorView@45726938 has no id. 02-23 15:05:57.688 I/ActivityManager( 1240): Displayed activity com.twitter.android/.PostActivity: 340 ms (total 340 ms) 02-23 15:05:59.018 I/ActivityManager( 1240): Starting activity: Intent { act=android.intent.action.PICK typ=vnd.android.cursor.dir/image cmp=com.sonyericsson.camera/com.sonyericsson.album.grid.GridActivity } 02-23 15:05:59.038 I/ActivityManager( 1240): Start proc com.sonyericsson.camera for activity com.sonyericsson.camera/com.sonyericsson.album.grid.GridActivity: pid=15113 uid=10057 gids={1006, 1015, 3003} 02-23 15:05:59.128 I/dalvikvm(15113): Debugger thread not active, ignoring DDM send (t=0x41504e4d l=38) 02-23 15:05:59.158 I/dalvikvm(15113): Debugger thread not active, ignoring DDM send (t=0x41504e4d l=50) 02-23 15:05:59.448 I/ActivityManager( 1240): Displayed activity com.sonyericsson.camera/com.sonyericsson.album.grid.GridActivity: 423 ms (total 423 ms) 02-23 15:05:59.458 W/dalvikvm(15113): threadid=15: thread exiting with uncaught exception (group=0x4001e160) 02-23 15:05:59.458 E/AndroidRuntime(15113): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception 02-23 15:05:59.468 E/AndroidRuntime(15113): java.lang.RuntimeException: An error occured while executing doInBackground() 02-23 15:05:59.468 E/AndroidRuntime(15113): at android.os.AsyncTask$3.done(AsyncTask.java:200) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.lang.Thread.run(Thread.java:1096) 02-23 15:05:59.468 E/AndroidRuntime(15113): Caused by: java.lang.IllegalArgumentException: Unsupported MIME type. 02-23 15:05:59.468 E/AndroidRuntime(15113): at com.sonyericsson.album.grid.GridActivity$AlbumTask.doInBackground(GridActivity.java:202) 02-23 15:05:59.468 E/AndroidRuntime(15113): at com.sonyericsson.album.grid.GridActivity$AlbumTask.doInBackground(GridActivity.java:124) 02-23 15:05:59.468 E/AndroidRuntime(15113): at android.os.AsyncTask$2.call(AsyncTask.java:185) 02-23 15:05:59.468 E/AndroidRuntime(15113): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 02-23 15:05:59.468 E/AndroidRuntime(15113): ... 4 more 02-23 15:05:59.628 E/SemcCheckin(15113): Get crash dump level : java.io.FileNotFoundException: /data/semc-checkin/crashdump 02-23 15:05:59.628 W/ActivityManager( 1240): Unable to start service Intent { act=com.sonyericsson.android.jcrashcatcher.action.BUGREPORT_AUTO cmp=com.sonyericsson.android.jcrashcatcher/.JCrashCatcherService (has extras) }: not found 02-23 15:05:59.648 I/Process ( 1240): Sending signal. PID: 15113 SIG: 3 02-23 15:05:59.648 I/dalvikvm(15113): threadid=7: reacting to signal 3 02-23 15:05:59.778 I/dalvikvm(15113): Wrote stack trace to '/data/anr/traces.txt' 02-23 15:06:00.388 E/SemcCheckin( 1673): Get Crash Level : java.io.FileNotFoundException: /data/semc-checkin/crashdump 02-23 15:06:01.708 I/DumpStateReceiver( 1240): Added state dump to 1 crashes 02-23 15:06:02.008 D/iddd-events( 1117): Registering event com.sonyericsson.idd.probe.android.devicemonitor::ApplicationCrash with 4314 bytes payload. 02-23 15:06:06.968 D/dalvikvm( 1673): GC freed 661 objects / 126704 bytes in 124ms 02-23 15:06:11.928 D/dalvikvm( 1379): GC freed 19753 objects / 858832 bytes in 84ms 02-23 15:06:13.038 I/Process (15113): Sending signal. PID: 15113 SIG: 9 02-23 15:06:13.048 I/WindowManager( 1240): WIN DEATH: Window{4596ecc0 com.sonyericsson.camera/com.sonyericsson.album.grid.GridActivity paused=false} 02-23 15:06:13.048 I/ActivityManager( 1240): Process com.sonyericsson.camera (pid 15113) has died. 02-23 15:06:13.048 I/WindowManager( 1240): WIN DEATH: Window{459db5e8 com.sonyericsson.camera/com.sonyericsson.album.grid.GridActivity paused=false} 02-23 15:06:13.078 I/UsageStats( 1240): Unexpected resume of com.twitter.android while already resumed in com.sonyericsson.camera 02-23 15:06:13.098 W/InputManagerService( 1240): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@456e7168 02-23 15:06:21.278 D/dalvikvm( 1745): GC freed 2032 objects / 410848 bytes in 60ms

    Read the article

  • Phone-book Database Help - Python

    - by IDOntWantThat
    I'm new to programming and have an assignment I've been working at for awhile. I understand defining functions and a lot of the basics but I'm kind of running into a brick wall at this point. I'm trying to figure this one out and don't really understand how the 'class' feature works yet. I'd appreciate any help with this one; also any help with some python resources that have can dummy down how/why classes are used. You've been going to work on a database project at work for sometime now. Your boss encourages you to program the database in Python. You disagree, arguing that Python is not a database language but your boss persists by providing the source code below for a sample telephone database. He asks you to do two things: Evaluate the existing source code and extend it to make it useful for managers in the firm. (You do not need a GUI interface, just work on the database aspects: data entry and retrieval - of course you must get the program to run or properly work He wants you to critically evaluate Python as a database tool. Import the sample code below into the Python IDLE and enhance it, run it and debug it. Add features to make this a more realistic database tool by providing for easy data entry and retrieval. import shelve import string UNKNOWN = 0 HOME = 1 WORK = 2 FAX = 3 CELL = 4 class phoneentry: def __init__(self, name = 'Unknown', number = 'Unknown', type = UNKNOWN): self.name = name self.number = number self.type = type # create string representation def __repr__(self): return('%s:%d' % ( self.name, self.type )) # fuzzy compare or two items def __cmp__(self, that): this = string.lower(str(self)) that = string.lower(that) if string.find(this, that) >= 0: return(0) return(cmp(this, that)) def showtype(self): if self.type == UNKNOWN: return('Unknown') if self.type == HOME: return('Home') if self.type == WORK: return('Work') if self.type == FAX: return('Fax') if self.type == CELL: return('Cellular') class phonedb: def __init__(self, dbname = 'phonedata'): self.dbname = dbname; self.shelve = shelve.open(self.dbname); def __del__(self): self.shelve.close() self.shelve = None def add(self, name, number, type = HOME): e = phoneentry(name, number, type) self.shelve[str(e)] = e def lookup(self, string): list = [] for key in self.shelve.keys(): e = self.shelve[key] if cmp(e, string) == 0: list.append(e) return(list) # if not being loaded as a module, run a small test if __name__ == '__main__': foo = phonedb() foo.add('Sean Reifschneider', '970-555-1111', HOME) foo.add('Sean Reifschneider', '970-555-2222', CELL) foo.add('Evelyn Mitchell', '970-555-1111', HOME) print 'First lookup:' for entry in foo.lookup('reifsch'): print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) print print 'Second lookup:' for entry in foo.lookup('e'): print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) I'm not sure if I'm on the right track but here is what I have so far: def openPB(): foo = phonedb() print 'Please select an option:' print '1 - Lookup' print '2 - Add' print '3 - Delete' print '4 - Quit' entry=int(raw_input('>> ')) if entry==1: namelookup=raw_input('Please enter a name: ') for entry in foo.lookup(namelookup): print '%-40s %s (%s)' % (entry.name, entry.number, entry.showtype() ) elif entry==2: name=raw_input('Name: ') number=raw_input('Number: ') showtype=input('Type (UNKNOWN, HOME, WORK, FAX, CELL): \n>> ') for entry in foo.add(name, number, showtype): #Trying to figure out this part print '%-40s %s (%s)'% (entry.name, entry.number, entry.showtype() ) elif entry==3: delname=raw_input('Please enter a name to delete: ') # #Trying to figure out this part print "Contact '%s' has been deleted" (delname) elif entry==4: print "Phone book is now closed" quit else: print "Your entry was not recognized." openPB() openPB()

    Read the article

  • Calling unmanaged code from within C#

    - by Charles Gargent
    I am trying to use a dll in my c# program but I just cant seem to get it to work. I have made a test app shown below. The return value is 0, however it does not actually do what it is supposed to do. Whereas the following command does work: rundll32 cmproxy.dll,SetProxy /source_filename proxy-1.txt /backup_filename roxy.bak /DialRasEntry NULL /TunnelRasEntry DSLVPN /Profile "C:\Documents and ettings\Administrator\Application Data\Microsoft\Network\Connections\Cm\dslvpn.cmp" Code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Net; using WUApiLib; namespace nac { class Program { [DllImport("cmproxy.dll", CharSet = CharSet.Unicode)] static extern int SetProxy(string cmdLine); static void Main(string[] args) { string cmdLine = @"/source_filename proxy-1.txt /backup_filename proxy.bak /DialRasEntry NULL /TunnelRasEntry DSLVPN /Profile ""C:\Documents and Settings\Administrator\Application Data\Microsoft\Network\Connections\Cm\dslvpn.cmp"""; Console.WriteLine(SetProxy(cmdLine)); } } } Here is the contents of the dumpbin /exports command File Type: DLL Section contains the following exports for cmproxy.dll 00000000 characteristics 3E7FEF8C time date stamp Tue Mar 25 05:56:28 2003 0.00 version 1 ordinal base 1 number of functions 1 number of names ordinal hint RVA name 1 0 00001B68 SetProxy Summary 1000 .data 1000 .reloc 1000 .rsrc 2000 .text When this works it sets the proxy server for a VPN connection.

    Read the article

  • Intel Assembly Programming

    - by Kay
    class MyString{ char buf[100]; int len; boolean append(MyString str){ int k; if(this.len + str.len>100){ for(k=0; k<str.len; k++){ this.buf[this.len] = str.buf[k]; this.len ++; } return false; } return true; } } Does the above translate to: start: push ebp ; save calling ebp mov ebp, esp ; setup new ebp push esi ; push ebx ; mov esi, [ebp + 8] ; esi = 'this' mov ebx, [ebp + 14] ; ebx = str mov ecx, 0 ; k=0 mov edx, [esi + 200] ; edx = this.len append: cmp edx + [ebx + 200], 100 jle ret_true ; if (this.len + str.len)<= 100 then ret_true cmp ecx, edx jge ret_false ; if k >= str.len then ret_false mov [esi + edx], [ebx + 2*ecx] ; this.buf[this.len] = str.buf[k] inc edx ; this.len++ aux: inc ecx ; k++ jmp append ret_true: pop ebx ; restore ebx pop esi ; restore esi pop ebp ; restore ebp ret true ret_false: pop ebx ; restore ebx pop esi ; restore esi pop ebp ; restore ebp ret false My greatest difficulty here is figuring out what to push onto the stack and the math for pointers. NOTE: I'm not allowed to use global variables and i must assume 32-bit ints, 16-bit chars and 8-bit booleans.

    Read the article

  • Intel IA-32 Assembly

    - by Kay
    I'm having a bit of difficulty converting the following java code into Intel IA-32 Assembly: class Person() { char name [8]; int age; void printName() {...} static void printAdults(Person [] list) { for(int k = 0; k < 100; k++){ if (list[k].age >= 18) { list[k].printName(); } } } } My attempt is: Person: push ebp; save callers ebp mov ebp, esp; setup new ebp push esi; esi will hold name push ebx; ebx will hold list push ecx; ecx will hold k init: mov esi, [ebp + 8]; mov ebx, [ebp + 12]; mov ecx, 0; k=0 forloop: cmp ecx, 100; jge end; if k>= 100 then break forloop cmp [ebx + 4 * ecx], 18 ; jl auxloop; if list[k].age < 18 then go to auxloop jmp printName; printName: auxloop: inc ecx; jmp forloop; end: pop ecx; pop ebx; pop esi; pop ebp; Is my code correct? NOTE: I'm not allowed to use global variables.

    Read the article

  • TreeMap sort by value

    - by vito huang
    I'm new to java, i want to write an comparator to that will let me sort TreeMap by value instead of the default natural sorting. i tried something like this, but can't find out what went wrong: import java.util.*; class treeMap { public static void main(String[] args) { System.out.println("the main"); byValue cmp = new byValue(); Map<String, Integer> map = new TreeMap<String, Integer>(cmp); map.put("de",10); map.put("ab", 20); map.put("a",5); for (Map.Entry<String,Integer> pair: map.entrySet()) { System.out.println(pair.getKey()+":"+pair.getValue()); } } } class byValue implements Comparator<Map.Entry<String,Integer>> { public int compare(Map.Entry<String,Integer> e1, Map.Entry<String,Integer> e2) { if (e1.getValue() < e2.getValue()){ return 1; } else if (e1.getValue() == e2.getValue()) { return 0; } else { return -1; } } } I guess what am i asking is what controls what get pass to comparator function, can i get an Map.Entry pass to comparator?

    Read the article

  • How does loop address alignment affect the speed on Intel x86_64?

    - by Alexander Gololobov
    I'm seeing 15% performance degradation of the same C++ code compiled to exactly same machine instructions but located on differently aligned addresses. When my tiny main loop starts at 0x415220 it's faster then when it is at 0x415250. I'm running this on Intel Core2 Duo. I use gcc 4.4.5 on x86_64 Ubuntu. Can anybody explain the cause of slowdown and how I can force gcc to optimally align the loop? Here is the disassembly for both cases with profiler annotation: 415220 576 12.56% |XXXXXXXXXXXXXX 48 c1 eb 08 shr $0x8,%rbx 415224 110 2.40% |XX 0f b6 c3 movzbl %bl,%eax 415227 0.00% | 41 0f b6 04 00 movzbl (%r8,%rax,1),%eax 41522c 40 0.87% | 48 8b 04 c1 mov (%rcx,%rax,8),%rax 415230 806 17.58% |XXXXXXXXXXXXXXXXXXX 4c 63 f8 movslq %eax,%r15 415233 186 4.06% |XXXX 48 c1 e8 20 shr $0x20,%rax 415237 102 2.22% |XX 4c 01 f9 add %r15,%rcx 41523a 414 9.03% |XXXXXXXXXX a8 0f test $0xf,%al 41523c 680 14.83% |XXXXXXXXXXXXXXXX 74 45 je 415283 ::Run(char const*, char const*)+0x4b3 41523e 0.00% | 41 89 c7 mov %eax,%r15d 415241 0.00% | 41 83 e7 01 and $0x1,%r15d 415245 0.00% | 41 83 ff 01 cmp $0x1,%r15d 415249 0.00% | 41 89 c7 mov %eax,%r15d 415250 679 13.05% |XXXXXXXXXXXXXXXX 48 c1 eb 08 shr $0x8,%rbx 415254 124 2.38% |XX 0f b6 c3 movzbl %bl,%eax 415257 0.00% | 41 0f b6 04 00 movzbl (%r8,%rax,1),%eax 41525c 43 0.83% |X 48 8b 04 c1 mov (%rcx,%rax,8),%rax 415260 828 15.91% |XXXXXXXXXXXXXXXXXXX 4c 63 f8 movslq %eax,%r15 415263 388 7.46% |XXXXXXXXX 48 c1 e8 20 shr $0x20,%rax 415267 141 2.71% |XXX 4c 01 f9 add %r15,%rcx 41526a 634 12.18% |XXXXXXXXXXXXXXX a8 0f test $0xf,%al 41526c 749 14.39% |XXXXXXXXXXXXXXXXXX 74 45 je 4152b3 ::Run(char const*, char const*)+0x4c3 41526e 0.00% | 41 89 c7 mov %eax,%r15d 415271 0.00% | 41 83 e7 01 and $0x1,%r15d 415275 0.00% | 41 83 ff 01 cmp $0x1,%r15d 415279 0.00% | 41 89 c7 mov %eax,%r15d

    Read the article

  • How to use void*

    - by Rondogiannis Aristophanes
    I am imlementing a simple merge function and I have got stuck, as the compiler gives me errors that I cannot explain. Here is my merge function: void merge(void *a, int beg, int middle, int end, int (*cmp)(const void*, const void* { std::stack<void*> first; std::stack<void*> second; for(int i = beg; i < middle; i++) { first.push(a+i); } for(int i = middle; i < end; i++) { second.push(a+i); } for(int i = beg; i < end; i++) { if(first.empty()) { void *tmp = second.top(); second.pop(); a+i = tmp; } else if(second.empty()) { void *tmp = first.top(); first.pop(); a+i = tmp; } else if(cmp(first.top(), second.top())) { void *tmp = first.top(); first.pop(); a+i = tmp; } else { void *tmp = second.top(); second.pop(); a+i = tmp; } } } And here is the error: sort.h: In function `void merge(void*, int, int, int, int (*)(const void*, const void*))': sort.h:9: error: pointer of type `void *' used in arithmetic sort.h:12: error: pointer of type `void *' used in arithmetic sort.h:19: error: pointer of type `void *' used in arithmetic sort.h:19: error: non-lvalue in assignment sort.h:23: error: pointer of type `void *' used in arithmetic sort.h:23: error: non-lvalue in assignment sort.h:27: error: pointer of type `void *' used in arithmetic sort.h:27: error: non-lvalue in assignment sort.h:31: error: pointer of type `void *' used in arithmetic sort.h:31: error: non-lvalue in assignment Can anyone help me? TIA.

    Read the article

  • Python Tkinter comparing PhotoImage objects

    - by Kyle Schmidt
    In a simple LightsOut game, when I click on a light I need to toggle the image on a button. I'm doing this with Tkinter, so I thought I'd just check and see what image is currently on the button (either 'on.gif' or 'off.gif') and set it to the other one, like this: def click(self,x,y): if self.buttons[x][y].image == self.on: self.buttons[x][y].config(image=self.off) self.buttons[x][y].image == self.off else: self.buttons[x][y].config(image=self.on) self.buttons[x][y].image == self.on This ends up always being True - I can turn a lgiht off, but never turn it back on. Did some research, realized that I should probably be using cmp: def click(self,x,y): if cmp(self.buttons[x][y].image,self.on) == 0: self.buttons[x][y].config(image=self.off) self.buttons[x][y].image == self.off else: self.buttons[x][y].config(image=self.on) self.buttons[x][y].image == self.on But that gave me the exact same result. Both self.on and self.off are PhotoImage objects. Aside from keeping a separate set of lists which tracks what type of light is in each position and redrawing them every click, is there a way to directly compare two PhotoImage objects like this?

    Read the article

  • Launch market place with id of an application that doesn't exist in the android market place

    - by Gaurav
    Hi, I am creating an application that checks the installation of a package and then launches the market-place with its id. When I try to launch market place with id of an application say com.mybrowser.android by throwing an intent android.intent.action.VIEW with url: market://details?id=com.mybrowser.android, the market place application does launches but crashes after launch. Note: the application com.mybrowser.android doesn't exists in the market-place. MyApplication is my application. $ adb logcat I/ActivityManager( 1030): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=myapp.testapp/.MyApplication } I/ActivityManager( 1030): Start proc myapp.testapp for activity myapp.testapp/.MyApplication: pid=3858 uid=10047 gids={1015, 3003} I/MyApplication( 3858): [ Activity CREATED ] I/MyApplication( 3858): [ Activity STARTED ] I/MyApplication( 3858): onResume D/dalvikvm( 1109): GC freed 6571 objects / 423480 bytes in 73ms I/MyApplication( 3858): Pressed OK button I/MyApplication( 3858): Broadcasting Intent: android.intent.action.VIEW, data: market://details?id=com.mybrowser.android I/ActivityManager( 1030): Starting activity: Intent { act=android.intent.action.VIEW dat=market://details?id=com.mybrowser.android flg=0x10000000 cmp=com.android.ven ding/.AssetInfoActivity } I/MyApplication( 3858): onPause I/ActivityManager( 1030): Start proc com.android.vending for activity com.android.vending/.AssetInfoActivity: pid=3865 uid=10023 gids={3003} I/ActivityThread( 3865): Publishing provider com.android.vending.SuggestionsProvider: com.android.vending.SuggestionsProvider D/dalvikvm( 1030): GREF has increased to 701 I/vending ( 3865): com.android.vending.api.RadioHttpClient$1.handleMessage(): Handle DATA_STATE_CHANGED event: NetworkInfo: type: WIFI[], state: CONNECTED/CO NNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: true I/ActivityManager( 1030): Displayed activity com.android.vending/.AssetInfoActivity: 609 ms (total 7678 ms) D/dalvikvm( 1030): GC freed 10458 objects / 676440 bytes in 128ms I/MyApplication( 3858): [ Activity STOPPED ] D/dalvikvm( 3865): GC freed 3538 objects / 254008 bytes in 84ms W/dalvikvm( 3865): threadid=19: thread exiting with uncaught exception (group=0x4001b180) E/AndroidRuntime( 3865): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception E/AndroidRuntime( 3865): java.lang.RuntimeException: An error occured while executing doInBackground() E/AndroidRuntime( 3865): at android.os.AsyncTask$3.done(AsyncTask.java:200) E/AndroidRuntime( 3865): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) E/AndroidRuntime( 3865): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) E/AndroidRuntime( 3865): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) E/AndroidRuntime( 3865): at java.util.concurrent.FutureTask.run(FutureTask.java:137) E/AndroidRuntime( 3865): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) E/AndroidRuntime( 3865): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) E/AndroidRuntime( 3865): at java.lang.Thread.run(Thread.java:1096) E/AndroidRuntime( 3865): Caused by: java.lang.NullPointerException E/AndroidRuntime( 3865): at com.android.vending.AssetItemAdapter$ReloadLocalAssetInformationTask.doInBackground(AssetItemAdapter.java:845) E/AndroidRuntime( 3865): at com.android.vending.AssetItemAdapter$ReloadLocalAssetInformationTask.doInBackground(AssetItemAdapter.java:831) E/AndroidRuntime( 3865): at android.os.AsyncTask$2.call(AsyncTask.java:185) E/AndroidRuntime( 3865): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) E/AndroidRuntime( 3865): ... 4 more I/Process ( 1030): Sending signal. PID: 3865 SIG: 3 I/dalvikvm( 3865): threadid=7: reacting to signal 3 I/dalvikvm( 3865): Wrote stack trace to '/data/anr/traces.txt' I/DumpStateReceiver( 1030): Added state dump to 1 crashes D/AndroidRuntime( 3865): Shutting down VM W/dalvikvm( 3865): threadid=3: thread exiting with uncaught exception (group=0x4001b180) E/AndroidRuntime( 3865): Uncaught handler: thread main exiting due to uncaught exception E/AndroidRuntime( 3865): java.lang.NullPointerException E/AndroidRuntime( 3865): at com.android.vending.controller.AssetInfoActivityController.getIdDeferToLocal(AssetInfoActivityController.java:637) E/AndroidRuntime( 3865): at com.android.vending.AssetInfoActivity.displayAssetInfo(AssetInfoActivity.java:556) E/AndroidRuntime( 3865): at com.android.vending.AssetInfoActivity.access$800(AssetInfoActivity.java:74) E/AndroidRuntime( 3865): at com.android.vending.AssetInfoActivity$LoadAssetInfoAction$1.run(AssetInfoActivity.java:917) E/AndroidRuntime( 3865): at android.os.Handler.handleCallback(Handler.java:587) E/AndroidRuntime( 3865): at android.os.Handler.dispatchMessage(Handler.java:92) E/AndroidRuntime( 3865): at android.os.Looper.loop(Looper.java:123) E/AndroidRuntime( 3865): at android.app.ActivityThread.main(ActivityThread.java:4363) E/AndroidRuntime( 3865): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime( 3865): at java.lang.reflect.Method.invoke(Method.java:521) E/AndroidRuntime( 3865): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) E/AndroidRuntime( 3865): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) E/AndroidRuntime( 3865): at dalvik.system.NativeStart.main(Native Method) I/Process ( 1030): Sending signal. PID: 3865 SIG: 3 W/ActivityManager( 1030): Process com.android.vending has crashed too many times: killing! D/ActivityManager( 1030): Force finishing activity com.android.vending/.AssetInfoActivity I/dalvikvm( 3865): threadid=7: reacting to signal 3 D/ActivityManager( 1030): Force removing process ProcessRecord{44e48548 3865:com.android.vending/10023} (com.android.vending/10023) However, when I try to launch the market place for a package that exists in the market place say com.opera.mini.android, everything works. Log for this case: D/dalvikvm( 966): GC freed 2781 objects / 195056 bytes in 99ms I/MyApplication( 1165): Pressed OK button I/MyApplication( 1165): Broadcasting Intent: android.intent.action.VIEW, data: market://details?id=com.opera.mini.android I/ActivityManager( 78): Starting activity: Intent { act=android.intent.action.VIEW dat=market://details?id=com.opera.mini.android flg=0x10000000 cmp=com.android.vending/.AssetInfoActivity } I/AndroidRuntime( 1165): AndroidRuntime onExit calling exit(0) I/WindowManager( 78): WIN DEATH: Window{44c72308 myapp.testapp/myapp.testapp.MyApplication paused=true} I/ActivityManager( 78): Process myapp.testapp (pid 1165) has died. I/WindowManager( 78): WIN DEATH: Window{44c72958 myapp.testapp/myapp.testapp.MyApplication paused=false} D/dalvikvm( 78): GC freed 31778 objects / 1796368 bytes in 142ms I/ActivityManager( 78): Displayed activity com.android.vending/.AssetInfoActivity: 214 ms (total 22866 ms) W/KeyCharacterMap( 978): No keyboard for id 65540 W/KeyCharacterMap( 978): Using default keymap: /system/usr/keychars/qwerty.kcm.bin V/RenderScript_jni( 966): surfaceCreated V/RenderScript_jni( 966): surfaceChanged V/RenderScript( 966): setSurface 480 762 0x573430 D/ViewFlipper( 966): updateRunning() mVisible=true, mStarted=true, mUserPresent=true, mRunning=true D/dalvikvm( 978): GC freed 10065 objects / 624440 bytes in 95ms Any ideas? Thanks in advance!

    Read the article

  • Runtime error of TASM language help!

    - by dominoos
    .model small .stack 400h .data message db "hello. ", 0ah, 0dh, "$" firstdigit db ? seconddigit db ? thirddigit db ? number dw ? newnumber db ? anumber dw 0d bnumber dw 0d Firstn db 0ah, 0dh, "Enter first 3 digit number: ","$" secondn db 0ah, 0dh, "Enter second 3 digit number: ","$" messageB db 0ah, 0dh, "HCF of two number is: ","$" linebreaker db 0ah, 0dh, ' ', 0ah, 0dh, '$' .code Start: mov ax, @data ; establish access to the data segment mov ds, ax ; mov number, 0d mov dx, offset message ; print the string "yob choi 0648293" mov ah, 9h int 21h num: mov dx, offset Firstn ; print the string "put 1st 3 digit" mov ah, 9h int 21h ;run JMP FirstFirst ; jump to FirstFirst FirstFirst: ;first digit mov ah, 1d ;bios code for read a keystroke int 21h ;call bios, it is understood that the ascii code will be returned in al mov firstdigit, al ;may as well save a copy sub al, 30h ;Convert code to an actual integer cbw ;CONVERT BYTE TO WORD. This takes whatever number is in al and ;extends it to ax, doubling its size from 8 bits to 16 bits ;The first digit now occupies all of ax as an integer mov cx, 100d ;This is so we can calculate 100*1st digit +10*2nd digit + 3rd digit mul cx ;start to accumulate the 3 digit number in the variable imul cx ;it is understood that the other operand is ax ; the result will use both dx::ax ;dx will contain only leading zeros add anumber, ax ;save ;Second Digit mov ah, 1d ;bios code for read a keystroke int 21h ;call bios, it is understood that the ascii code will be returned in al mov seconddigit, al ;may as well save a copy sub al, 30h ;Convert code to an actual integer cbw ;CONVERT BYTE TO WORD. This takes whatever number is in al and ;extends it to ax, boubling its size from 8 bits to 16 bits ;The first digit now occupies all of ax as an integer mov cx, 10d ;continue to accumulate the 3 digit number in the variable mul cx ;it is understood that the other operand is ax, containing first digit ;the result will use both dx::ax ;dx will contain only leading zeros. add anumber, ax ;save ;third Digit mov ah, 1d ;samething as above int 21h ; mov thirddigit, al ; sub al, 30h ; cbw ; add anumber, ax ; jmp num2 ;go to checks Num2: mov dx, offset secondn ; print the string "put 2nd 3 digits" mov ah, 9h int 21h ;run JMP SecondSecond SecondSecond: ;first digit mov ah, 1d ;bios code for read a keystroke int 21h ;call bios, it is understood that the ascii code will be returned in al mov firstdigit, al ;may as well save a copy sub al, 30h ;Convert code to an actual integer cbw ;CONVERT BYTE TO WORD. This takes whatever number is in al and ;extends it to ax, doubling its size from 8 bits to 16 bits ;The first digit now occupies all of ax as an integer mov cx, 100d ;This is so we can calculate 100*1st digit +10*2nd digit + 3rd digit mul cx ;start to accumulate the 3 digit number in the variable imul cx ;it is understood that the other operand is ax ; the result will use both dx::ax ;dx will contain only leading zeros add bnumber, ax ;save ;Second Digit mov ah, 1d ;bios code for read a keystroke int 21h ;call bios, it is understood that the ascii code will be returned in al mov seconddigit, al ;may as well save a copy sub al, 30h ;Convert code to an actual integer cbw ;CONVERT BYTE TO WORD. This takes whatever number is in al and ;extends it to ax, boubling its size from 8 bits to 16 bits ;The first digit now occupies all of ax as an integer mov cx, 10d ;continue to accumulate the 3 digit number in the variable mul cx ;it is understood that the other operand is ax, containing first digit ;the result will use both dx::ax ;dx will contain only leading zeros. add bnumber, ax ;save ;third Digit mov ah, 1d ;samething as above int 21h ; mov thirddigit, al ; sub al, 30h ; cbw ; add bnumber, ax ; jmp compare ;go to compare compare: CMP ax, anumber ;comparing numbB and Number JA comp1 ;go to comp1 if anumber is bigger CMP ax, anumber ; JB comp2 ;go to comp2 if anumber is smaller CMP ax, anumber ; JE equal ;go to equal if two numbers are the same JMP compare ;go to compare (avioding error) comp1: SUB ax, anumber; subtract smaller number from bigger number JMP compare ; comp2: SUB anumber, ax; subtract smaller number from bigger number JMP compare ; equal: mov ah, 9d ;make linkbreak after the 2nd 3 digit number mov dx, offset linebreaker int 21h mov ah, 9d ;print "HCF of two number is:" mov dx, offset messageB int 21h mov ax,anumber ;copying 2nd number into ax add al,30h ; converting to ascii mov newnumber,al ; copying from low part of register into newnumb mov ah, 2d ;bios code for print a character mov dl, newnumber ;we had saved the ascii code here int 21h ;call to bios JMP exit; exit: mov ah, 4ch int 21h ;exit the program End hi, this is a program that finds highest common factor of 2 different 3digit number. if i put 200, 235,312 (low numbers) it works fine. but if i put 500, 550, 654(bigger number) the program crashes after the 2nd 3digit number is entered. can you help me to find out what problem is?

    Read the article

  • Convert Java program to C

    - by imicrothinking
    I need a bit of guidance with writing a C program...a bit of quick background as to my level, I've programmed in Java previously, but this is my first time programming in C, and we've been tasked to translate a word count program from Java to C that consists of the following: Read a file from memory Count the words in the file For each occurrence of a unique word, keep a word counter variable Print out the top ten most frequent words and their corresponding occurrences Here's the source program in Java: package lab0; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; public class WordCount { private ArrayList<WordCountNode> outputlist = null; public WordCount(){ this.outputlist = new ArrayList<WordCountNode>(); } /** * Read the file into memory. * * @param filename name of the file. * @return content of the file. * @throws Exception if the file is too large or other file related exception. */ public char[] readFile(String filename) throws Exception{ char [] result = null; File file = new File(filename); long size = file.length(); if (size > Integer.MAX_VALUE){ throw new Exception("File is too large"); } result = new char[(int)size]; FileReader reader = new FileReader(file); int len, offset = 0, size2read = (int)size; while(size2read > 0){ len = reader.read(result, offset, size2read); if(len == -1) break; size2read -= len; offset += len; } return result; } /** * Make article word by word. * * @param article the content of file to be counted. * @return string contains only letters and "'". */ private enum SPLIT_STATE {IN_WORD, NOT_IN_WORD}; /** * Go through article, find all the words and add to output list * with their count. * * @param article the content of the file to be counted. * @return words in the file and their counts. */ public ArrayList<WordCountNode> countWords(char[] article){ SPLIT_STATE state = SPLIT_STATE.NOT_IN_WORD; if(null == article) return null; char curr_ltr; int curr_start = 0; for(int i = 0; i < article.length; i++){ curr_ltr = Character.toUpperCase( article[i]); if(state == SPLIT_STATE.IN_WORD){ article[i] = curr_ltr; if ((curr_ltr < 'A' || curr_ltr > 'Z') && curr_ltr != '\'') { article[i] = ' '; //printf("\nthe word is %s\n\n",curr_start); if(i - curr_start < 0){ System.out.println("i = " + i + " curr_start = " + curr_start); } addWord(new String(article, curr_start, i-curr_start)); state = SPLIT_STATE.NOT_IN_WORD; } }else{ if (curr_ltr >= 'A' && curr_ltr <= 'Z') { curr_start = i; article[i] = curr_ltr; state = SPLIT_STATE.IN_WORD; } } } return outputlist; } /** * Add the word to output list. */ public void addWord(String word){ int pos = dobsearch(word); if(pos >= outputlist.size()){ outputlist.add(new WordCountNode(1L, word)); }else{ WordCountNode tmp = outputlist.get(pos); if(tmp.getWord().compareTo(word) == 0){ tmp.setCount(tmp.getCount() + 1); }else{ outputlist.add(pos, new WordCountNode(1L, word)); } } } /** * Search the output list and return the position to put word. * @param word is the word to be put into output list. * @return position in the output list to insert the word. */ public int dobsearch(String word){ int cmp, high = outputlist.size(), low = -1, next; // Binary search the array to find the key while (high - low > 1) { next = (high + low) / 2; // all in upper case cmp = word.compareTo((outputlist.get(next)).getWord()); if (cmp == 0) return next; else if (cmp < 0) high = next; else low = next; } return high; } public static void main(String args[]){ // handle input if (args.length == 0){ System.out.println("USAGE: WordCount <filename> [Top # of results to display]\n"); System.exit(1); } String filename = args[0]; int dispnum; try{ dispnum = Integer.parseInt(args[1]); }catch(Exception e){ dispnum = 10; } long start_time = Calendar.getInstance().getTimeInMillis(); WordCount wordcount = new WordCount(); System.out.println("Wordcount: Running..."); // read file char[] input = null; try { input = wordcount.readFile(filename); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } // count all word ArrayList<WordCountNode> result = wordcount.countWords(input); long end_time = Calendar.getInstance().getTimeInMillis(); System.out.println("wordcount: completed " + (end_time - start_time)/1000000 + "." + (end_time - start_time)%1000000 + "(s)"); System.out.println("wordsort: running ..."); start_time = Calendar.getInstance().getTimeInMillis(); Collections.sort(result); end_time = Calendar.getInstance().getTimeInMillis(); System.out.println("wordsort: completed " + (end_time - start_time)/1000000 + "." + (end_time - start_time)%1000000 + "(s)"); Collections.reverse(result); System.out.println("\nresults (TOP "+ dispnum +" from "+ result.size() +"):\n" ); // print out result String str ; for (int i = 0; i < result.size() && i < dispnum; i++){ if(result.get(i).getWord().length() > 15) str = result.get(i).getWord().substring(0, 14); else str = result.get(i).getWord(); System.out.println(str + " - " + result.get(i).getCount()); } } public class WordCountNode implements Comparable{ private String word; private long count; public WordCountNode(long count, String word){ this.count = count; this.word = word; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } public long getCount() { return count; } public void setCount(long count) { this.count = count; } public int compareTo(Object arg0) { // TODO Auto-generated method stub WordCountNode obj = (WordCountNode)arg0; if( count - obj.getCount() < 0) return -1; else if( count - obj.getCount() == 0) return 0; else return 1; } } } Here's my attempt (so far) in C: #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> // Read in a file FILE *readFile (char filename[]) { FILE *inputFile; inputFile = fopen (filename, "r"); if (inputFile == NULL) { printf ("File could not be opened.\n"); exit (EXIT_FAILURE); } return inputFile; } // Return number of words in an array int wordCount (FILE *filePointer, char filename[]) {//, char *words[]) { // count words int count = 0; char temp; while ((temp = getc(filePointer)) != EOF) { //printf ("%c", temp); if ((temp == ' ' || temp == '\n') && (temp != '\'')) count++; } count += 1; // counting method uses space AFTER last character in word - the last space // of the last character isn't counted - off by one error // close file fclose (filePointer); return count; } // Print out the frequencies of the 10 most frequent words in the console int main (int argc, char *argv[]) { /* Step 1: Read in file and check for errors */ FILE *filePointer; filePointer = readFile (argv[1]); /* Step 2: Do a word count to prep for array size */ int count = wordCount (filePointer, argv[1]); printf ("Number of words is: %i\n", count); /* Step 3: Create a 2D array to store words in the file */ // open file to reset marker to beginning of file filePointer = fopen (argv[1], "r"); // store words in character array (each element in array = consecutive word) char allWords[count][100]; // 100 is an arbitrary size - max length of word int i,j; char temp; for (i = 0; i < count; i++) { for (j = 0; j < 100; j++) { // labels are used with goto statements, not loops in C temp = getc(filePointer); if ((temp == ' ' || temp == '\n' || temp == EOF) && (temp != '\'') ) { allWords[i][j] = '\0'; break; } else { allWords[i][j] = temp; } printf ("%c", allWords[i][j]); } printf ("\n"); } // close file fclose (filePointer); /* Step 4: Use a simple selection sort algorithm to sort 2D char array */ // PStep 1: Compare two char arrays, and if // (a) c1 > c2, return 2 // (b) c1 == c2, return 1 // (c) c1 < c2, return 0 qsort(allWords, count, sizeof(char[][]), pstrcmp); /* int k = 0, l = 0, m = 0; char currentMax, comparedElement; int max; // the largest element in the current 2D array int elementToSort = 0; // elementToSort determines the element to swap with starting from the left // Outer a iterates through number of swaps needed for (k = 0; k < count - 1; k++) { // times of swaps max = k; // max element set to k // Inner b iterates through successive elements to fish out the largest element for (m = k + 1; m < count - k; m++) { currentMax = allWords[k][l]; comparedElement = allWords[m][l]; // Inner c iterates through successive chars to set the max vars to the largest for (l = 0; (currentMax != '\0' || comparedElement != '\0'); l++) { if (currentMax > comparedElement) break; else if (currentMax < comparedElement) { max = m; currentMax = allWords[m][l]; break; } else if (currentMax == comparedElement) continue; } } // After max (count and string) is determined, perform swap with temp variable char swapTemp[1][20]; int y = 0; do { swapTemp[0][y] = allWords[elementToSort][y]; allWords[elementToSort][y] = allWords[max][y]; allWords[max][y] = swapTemp[0][y]; } while (swapTemp[0][y++] != '\0'); elementToSort++; } */ int a, b; for (a = 0; a < count; a++) { for (b = 0; (temp = allWords[a][b]) != '\0'; b++) { printf ("%c", temp); } printf ("\n"); } // Copy rows to different array and print results /* char arrayCopy [count][20]; int ac, ad; char tempa; for (ac = 0; ac < count; ac++) { for (ad = 0; (tempa = allWords[ac][ad]) != '\0'; ad++) { arrayCopy[ac][ad] = tempa; printf("%c", arrayCopy[ac][ad]); } printf("\n"); } */ /* Step 5: Create two additional arrays: (a) One in which each element contains unique words from char array (b) One which holds the count for the corresponding word in the other array */ /* Step 6: Sort the count array in decreasing order, and print the corresponding array element as well as word count in the console */ return 0; } // Perform housekeeping tasks like freeing up memory and closing file I'm really stuck on the selection sort algorithm. I'm currently using 2D arrays to represent strings, and that worked out fine, but when it came to sorting, using three level nested loops didn't seem to work, I tried to use qsort instead, but I don't fully understand that function as well. Constructive feedback and criticism greatly welcome (...and needed)!

    Read the article

  • O&rsquo;Reilly Deals to 9/June/2014 05:00 PT&ndash;50% off E-Books on Regular Expressions

    - by TATWORTH
    Originally posted on: http://geekswithblogs.net/TATWORTH/archive/2014/06/06/orsquoreilly-deals-to-9june2014-0500-ptndash50-off-e-books-on-regular.aspxUntil 9/June/2014 05:00 PT, O’Reilly are offering 50% off E-Books on Regular Expressions at http://shop.oreilly.com/category/deals/regular-expressions-owo.do?code=DEAL&imm_mid=0bd938&cmp=em-prog-books-videos-lp-dod_regex. “Regular expressions—powerful tools for manipulating text and data—are now standard features in most languages and tools. Yet despite their widespread availability and unparalleled power, regular expressions are frequently underused. With ebooks and videos from shop.oreilly.com, learn tips for matching, extracting, and transforming text and data. Today only, save 50% and discover the epic functionality of Reg Ex.”

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >