Search Results

Search found 2343 results on 94 pages for 'masterchris 99'.

Page 69/94 | < Previous Page | 65 66 67 68 69 70 71 72 73 74 75 76  | Next Page >

  • Check if TIFF file is complete

    - by Davi
    I have a FileSystemWatcher monitoring a directory that receives TIF files from a scanning device. Its necessary to check if the scanning process is done and then read a multipage TIF file, otherwise, the FileSystemWatcher will raise the event before the file be fully scanned. I have something like: private void OnFileCreated(...) { while(IsFileLocked(path)) Thread.Sleep(time); // OK to read } This is what is happening: - Scanner creates the file - FileSystemWatcher detects the file, but its in use - Scanner reads the first page to the file - Scanner releases the file - My code leaves the while(FileInUse(path)) - My code reads the incomplete file (problem) - Scanner adds more pages to the file Let's say the scanner is scanning 100 pages, then, when "OK to read", the file will be incomplete (99 pages left). So, its necessary to know if the file is complete or not. Maybe waiting some time to see if the file is modified, but this time span can be up to hours, because the scanner can get idle scanning the same TIF. Other solution would be checking some flag in the TIF file that indicates that the file is not complete(I've looked for this but don't found anything).

    Read the article

  • [OT a bit] Flex+JEE what is it good for?

    - by Zenzen
    Ok so sorry for being, I guess, a bit off topic but still I think this is the best place to ask. My new semester just started (don't worry I won't ask you to do my homework) and this time we have a rather cool subject about www programming in general where we have to do a web service, web abb - whatever as long as it's "web". Here's the problem though, my team and I want to do it with Flex and JEE but we don't have much experience about what are they actually used for. I mean we know you can do virtually anything with it, but we don't really want to lose time on doing something useless. My first idea was to do a "brainstorming" 3D room/service - a place where people could log in have a video conference, a whiteboard, a place to upload pictures everyone could see, some toolbars for google, youtube etc. plus some other features which would make real-time brainstorming easy when you can't get everyone in one place. But is Flex+JEE really suitable? I mean I'm 99% sure it's doable but is it really worth doing it in Flex+JEE or was the whole purpose of JEE completely different? @EDIT: well this was only one of our ideas obviously. I do know the basics of JSP, Servlets, JPA etc. of course but yeah the main goal of this project is to get some actual experience. The problem is we don't really know is it worth doing something like let's say a social network (something like extended facebook) for gamers (doesn't really matter if it already exists) in JEE or would it only look ridiculous (because PHP or whatever would be a far better choice)? Bottom line is that we are wondering are only large scale applications (for banks etc.) written in JEE or is it good for anything (even the smaller projects)?

    Read the article

  • error 734 the ppp link control protocal was terminated

    - by satheesh
    Hi, i want to connect my mobile internet to pc using bluetooth device. I installed blue soleil software in my pc. Steps: 1.I can able to pair my cellphone with pc bluetooth device. 2.I selected my device and select bluetooth dialup networking service. 3.It asks an alert "DUN connection with device?" in my mobile. 4.After Clicked "YES", connect bluetooth DUN connection window opens. 5.In that window there was a fields "User Name", "PassWord" which i leave empty and then in "Dial = 99**1#" and click Dial button. 6.After that it say "Registering your computer on the netwok.." and become fails. 7. The Error is as "error 734 the ppp link control protocal was terminated" The same procedure should be followed for Nokia 3110c it works fine.But in my samsung mobile c3053 it not connected also i am tryig with samsung corby pro BT3510 mobile . Is there any settings changes needed for samsung mobiles ? Can anyone help me ? Thanks in advance...........

    Read the article

  • Cnoverting application to MVC architecture

    - by terence6
    I'm practicing writing MVC applications. I have a Mastermind game, that I would like to rewrite as MVC app. I have divided my code to parts, but instead of working game I'm getting empty Frame and an error in "public void paint( Graphics g )". Error comes from calling this method in my view with null argument. But how to overcome this ? MVC was quite simple with swing but awt and it's paint methods are much more complicated. Code of working app : http://paste.pocoo.org/show/224982/ App divided to MVC : Main : public class Main { public static void main(String[] args){ Model model = new Model(); View view = new View("Mastermind", 400, 590, model); Controller controller = new Controller(model, view); view.setVisible(true); } } Controller : import java.awt.*; import java.awt.event.*; public class Controller implements MouseListener, ActionListener { private Model model; private View view; public Controller(Model m, View v){ model = m; view = v; view.addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); view.addMouseListener(this); } public void actionPerformed( ActionEvent e ) { if(e.getSource() == view.checkAnswer){ if(model.isRowFull){ model.check(); } } } public void mousePressed(MouseEvent e) { Point mouse = new Point(); mouse = e.getPoint(); if (model.isPlaying){ if (mouse.x > 350) { int button = 1 + (int)((mouse.y - 32) / 50); if ((button >= 1) && (button <= 5)){ model.fillHole(button); } } } } public void mouseClicked(MouseEvent e) {} public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} } View : import java.awt.*; import javax.swing.*; import java.awt.event.*; public class View extends Frame implements ActionListener { Model model; JButton checkAnswer; private JPanel button; static final int HIT_X[] = {270,290,310,290,310}, HIT_Y[] = {506,496,496,516,516}; public View(String name, int w, int h, Model m){ model = m; setTitle( name ); setSize( w,h ); setResizable( false ); this.setLayout(new BorderLayout()); button = new JPanel(); button.setSize( new Dimension(400, 100)); button.setVisible(true); checkAnswer = new JButton("Check"); checkAnswer.addActionListener(this); checkAnswer.setSize( new Dimension(200, 30)); button.add( checkAnswer ); this.add( button, BorderLayout.SOUTH); button.setVisible(true); for ( int i=0; i < model.SCORE; i++ ){ for ( int j = 0; j < model.LINE; j++ ){ model.pins[i][j] = new Pin(20,0); model.pins[i][j].setPosition(j*50+30,510-i*50); model.pins[i+model.SCORE][j] = new Pin(8,0); model.pins[i+model.SCORE][j].setPosition(HIT_X[j],HIT_Y[j]-i*50); } } for ( int i=0; i < model.LINE; i++ ){ model.pins[model.OPTIONS][i] = new Pin( 20, i+2 ); model.pins[model.OPTIONS][i].setPosition( 370,i * 50 + 56); } model.combination(); model.paint(null); } public void actionPerformed( ActionEvent e ) { } } Model: import java.awt.*; public class Model extends Frame{ static final int LINE = 5, SCORE = 10, OPTIONS = 20; Pin pins[][] = new Pin[21][LINE]; int combination[] = new int[LINE]; int curPin = 0; int turn = 1; int repaintPin; boolean isUpdate = true, isPlaying = true, isRowFull = false; public Model(){ } void fillHole(int color) { pins[turn-1][curPin].setColor(color+1); repaintPins( turn ); curPin = (curPin+1) % LINE; if (curPin == 0){ isRowFull = true; } } public void paint( Graphics g ) { g.setColor( new Color(238, 238, 238)); g.fillRect( 0,0,400,590); for ( int i=0; i < pins.length; i++ ) { pins[i][0].paint(g); pins[i][1].paint(g); pins[i][2].paint(g); pins[i][3].paint(g); pins[i][4].paint(g); } } public void update( Graphics g ) { if ( isUpdate ) { paint(g); } else { isUpdate = true; pins[repaintPin-1][0].paint(g); pins[repaintPin-1][1].paint(g); pins[repaintPin-1][2].paint(g); pins[repaintPin-1][3].paint(g); pins[repaintPin-1][4].paint(g); } } void repaintPins( int pin ) { repaintPin = pin; isUpdate = false; repaint(); } void check() { int junkPegs[] = new int[LINE], junkCode[] = new int[LINE]; int pegCount = 0, pico = 0; for ( int i = 0; i < LINE; i++ ) { junkPegs[i] = pins[turn-1][i].getColor(); junkCode[i] = combination[i]; } for ( int i = 0; i < LINE; i++ ){ if (junkPegs[i]==junkCode[i]) { pins[turn+SCORE][pegCount].setColor(1); pegCount++; pico++; junkPegs[i] = 98; junkCode[i] = 99; } } for ( int i = 0; i < LINE; i++ ){ for ( int j = 0; j < LINE; j++ ) if (junkPegs[i]==junkCode[j]) { pins[turn+SCORE][pegCount].setColor(2); pegCount++; junkPegs[i] = 98; junkCode[j] = 99; j = LINE; } } repaintPins( turn+SCORE ); if ( pico == LINE ){ isPlaying = false; } else if ( turn >= 10 ){ isPlaying = false; } else{ curPin = 0; isRowFull = false; turn++; } } void combination() { for ( int i = 0; i < LINE; i++ ){ combination[i] = 1 + (int)(Math.random()*5); System.out.print(i+","); } } } class Pin{ private int color, X, Y, radius; private static final Color COLORS[] = { Color.black, Color.white, Color.red, Color.yellow, Color.green, Color.blue, new Color(7, 254, 250)}; public Pin(){ X = 0; Y = 0; radius = 0; color = 0; } public Pin( int r,int c ){ X = 0; Y = 0; radius = r; color = c; } public void paint( Graphics g ){ int x = X-radius; int y = Y-radius; if (color > 0){ g.setColor( COLORS[color]); g.fillOval( x,y,2*radius,2*radius ); } else{ g.setColor( new Color(238, 238, 238) ); g.drawOval( x,y,2*radius-1,2*radius-1 ); } g.setColor( Color.black ); g.drawOval( x,y,2*radius,2*radius ); } public void setPosition( int x,int y ){ this.X = x ; this.Y = y ; } public void setColor( int c ){ color = c; } public int getColor() { return color; } } Any clues on how to overcome this would be great. Have I divided my code improperly ?

    Read the article

  • Using lambda expressions and linq

    - by Andy
    So I've just started working with linq as well as using lambda expressions. I've run into a small hiccup while trying to get some data that I want. This method should return a list of all projects that are open or in progress from Jira Here's the code public static List<string> getOpenIssuesListByProject(string _projectName) { JiraSoapServiceService jiraSoapService = new JiraSoapServiceService(); string token = jiraSoapService.login(DEFAULT_UN, DEFAULT_PW); string[] keys = { getProjectKey(_projectName) }; RemoteStatus[] statuses = jiraSoapService.getStatuses(token); var desiredStatuses = statuses.Where(x => x.name == "Open" || x.name == "In Progress") .Select(x=>x.id); RemoteIssue[] AllIssues = jiraSoapService.getIssuesFromTextSearchWithProject(token, keys, "", 99); IEnumerable<RemoteIssue> openIssues = AllIssues.Where(x=> { foreach (var v in desiredStatuses) { if (x.status == v) return true; else return false; } return false; }); return openIssues.Select(x => x.key).ToList(); } Right now this only select issues that are "Open", and seems to skip those that are "In Progress". My question: First, why am I only getting the "Open" Issues, and second is there a better way to do this? The reason I get all the statuses first is that the issue only stores that statuses ID, so I get all the statuses, get the ID's that match "Open" and "In Progress", and then match those ID numbers to the issues status field.

    Read the article

  • Passing parameter to pthread

    - by Andrei Ciobanu
    Hello, i have the following code: #include <stdlib.h> #include <stdio.h> #include <pthread.h> #define NUM_THREADS 100 struct thread_param { char *f1; char *f2; int x; }; void *thread_function(void *arg){ printf("%d\n", ((struct thread_param*)arg)->x); } int main(int argc, char *argvs[]){ int i, thread_cr_res = 0; pthread_t *threads; threads = malloc(100 * sizeof(*threads)); if(threads == NULL){ fprintf(stderr,"MALLOC THREADS ERROR"); return (-1); } for(i = 0; i < NUM_THREADS; i++){ struct thread_param *tp; if((tp = malloc(sizeof(*tp))) == NULL){ fprintf(stderr,"MALLOC THREAD_PARAM ERROR"); return (-1); } tp->f1 = "f1"; tp->f2 = "f2"; tp->x = i; thread_cr_res = pthread_create(&threads[i], NULL, thread_function, (void*)tp); if(thread_cr_res != 0){ fprintf(stderr,"THREAD CREATE ERROR"); return (-1); } } return (0); } What i want to achieve, is to print all the numbers from 0 to 99, from threads. Also i am experimenting a way to pass a structure as a thread input parameter. What i am finding curios, is that not all the numbers are shown, eg: ./a.out | grep 9 9 19 29 39 49 And sometimes some numbers are shown twice: ... 75 74 89 77 78 79 91 91 Can you please explain me why is this happening ? No errors are shown.

    Read the article

  • access settings from whole jquery component

    - by Pacuraru Daniel
    I am trying to develop a jquery component for dialog modals and i dont know how to access the settings from all component functions. I need to access settings,zIndex from open function and it seems to not work. (function($) { var methods = { init: function(options) { var defaults = { bgClass: "fancy-dialog-bg", bgShow: null, zIndex: 100, show: null }; var settings = $.extend(defaults, options); return this.each(function() { var obj = $(this).hide().css("position", "fixed").css("z-index", settings.zIndex).css("left", "300px").css("top", "200px"); }); }, open: function() { // alert(settings.zIndex); not working var tes = $("<div></div>").css("backgroundColor", "#f00").css("position", "fixed").css("z-index", "99").css("width", "50%").css("height", "100%").css("left", "0").css("top", "0"); $('body').append(tes); var obj = $(this); obj.show(); }, close: function() { var obj = $(this); $("#fancy-dialog-bg-" + obj.attr('id')).remove(); obj.hide(); } }; $.fn.fancyDialog = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist.'); } }; })(jQuery);

    Read the article

  • Problems installing PIL after OSX 10.9

    - by user2632417
    I installed Mac OSX 10.9 the day it came out. Afterwards I decided I needed to install PIL. I'd installed it before, but it appeared the update had broken that. When I try to use pip to install PIL, it fails when building _imaging. It appears the root cause is this. /usr/include/sys/cdefs.h:655:2: error: Unsupported architecture Theres also a similar error here: /usr/include/machine/limits.h:8:2: error: architecture not supported and here: /usr/include/machine/_types.h:34:2: error: architecture not supported Then there's a whole list of missing types. /usr/include/sys/_types.h:94:9: error: unknown type name '__int64_t' typedef __int64_t __darwin_blkcnt_t; /* total blocks */ ^ /usr/include/sys/_types.h:95:9: error: unknown type name '__int32_t' typedef __int32_t __darwin_blksize_t; /* preferred block size */ ^ /usr/include/sys/_types.h:96:9: error: unknown type name '__int32_t' typedef __int32_t __darwin_dev_t; /* dev_t */ ^ /usr/include/sys/_types.h:99:9: error: unknown type name '__uint32_t' typedef __uint32_t __darwin_gid_t; /* [???] process and group IDs */ ^ /usr/include/sys/_types.h:100:9: error: unknown type name '__uint32_t' typedef __uint32_t __darwin_id_t; /* [XSI] pid_t, uid_t, or gid_t*/ ^ /usr/include/sys/_types.h:101:9: error: unknown type name '__uint64_t' typedef __uint64_t __darwin_ino64_t; /* [???] Used for 64 bit inodes */ Needless to say I don't know where to go from here. I've got a couple of guesses, but I don't even know how to check. Wrong include probably as a result of a badly configured environment variable Problem with Xcode's installation/ missing command line tools Messed up header files If anyone has any suggestions either to check one of those possibilities or for one of their own I'm all ears.

    Read the article

  • ExceptionInInitializerError and UnsatisfiedLinkError

    - by Nemesis
    I downloaded the Getac Z710 Android tablet RFID library/jar from there web site. But after I called the init function: 05-19 19:23:45.315: E/AndroidRuntime(2469): FATAL EXCEPTION: main 05-19 19:23:45.315: E/AndroidRuntime(2469): java.lang.ExceptionInInitializerError 05-19 19:23:45.315: E/AndroidRuntime(2469): at com.getac.lib.rfidreader.RfidTagReaderAPI.InitRFIDReader(RfidTagReaderAPI.java:118) 05-19 19:23:45.315: E/AndroidRuntime(2469): at shipadmin.musterstation.no.MainActivity.onCreate(MainActivity.java:104) 05-19 19:23:45.315: E/AndroidRuntime(2469): at android.app.Activity.performCreate(Activity.java:5008) 05-19 19:23:45.315: E/AndroidRuntime(2469): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 05-19 19:23:45.315: E/AndroidRuntime(2469): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) 05-19 19:23:45.315: E/AndroidRuntime(2469): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 05-19 19:23:45.315: E/AndroidRuntime(2469): at android.app.ActivityThread.access$600(ActivityThread.java:130) 05-19 19:23:45.315: E/AndroidRuntime(2469): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 05-19 19:23:45.315: E/AndroidRuntime(2469): at android.os.Handler.dispatchMessage(Handler.java:99) 05-19 19:23:45.315: E/AndroidRuntime(2469): at android.os.Looper.loop(Looper.java:137) 05-19 19:23:45.315: E/AndroidRuntime(2469): at android.app.ActivityThread.main(ActivityThread.java:4745) 05-19 19:23:45.315: E/AndroidRuntime(2469): at java.lang.reflect.Method.invokeNative(Native Method) 05-19 19:23:45.315: E/AndroidRuntime(2469): at java.lang.reflect.Method.invoke(Method.java:511) 05-19 19:23:45.315: E/AndroidRuntime(2469): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 05-19 19:23:45.315: E/AndroidRuntime(2469): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 05-19 19:23:45.315: E/AndroidRuntime(2469): at dalvik.system.NativeStart.main(Native Method) 05-19 19:23:45.315: E/AndroidRuntime(2469): Caused by: java.lang.UnsatisfiedLinkError: Couldn't load serial_port: findLibrary returned null 05-19 19:23:45.315: E/AndroidRuntime(2469): at java.lang.Runtime.loadLibrary(Runtime.java:365) 05-19 19:23:45.315: E/AndroidRuntime(2469): at java.lang.System.loadLibrary(System.java:538) 05-19 19:23:45.315: E/AndroidRuntime(2469): at android_serialport_api.SerialPort.<clinit>(SerialPort.java:69) 05-19 19:23:45.315: E/AndroidRuntime(2469): ... 16 more I tried other solutions for this, but still no luck. What would be the problem? They only have a limited documentation and support. TIA.

    Read the article

  • rotating a circle in UIView?

    - by senthilmuthu
    HI, i want to draw a circle in DrawRect through context like pie chart(took from tutorial) thorugh UITouch? i have given the code as follows,how can i rotate ? any help please? define PI 3.14159265358979323846 define snapshot_start 360 define snapshot_finish 360 static inline float radians(double degrees) { return degrees * PI / 180; } - (void)drawRect:(CGRect)rect { // Drawing code CGRect parentViewBounds = self.bounds; CGFloat x = CGRectGetWidth(parentViewBounds)/2; CGFloat y = CGRectGetHeight(parentViewBounds)*0.55; // Get the graphics context and clear it CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextClearRect(ctx, rect); // define stroke color CGContextSetRGBStrokeColor(ctx, 1, 1, 1, 1.0); // define line width CGContextSetLineWidth(ctx, 4.0); // need some values to draw pie charts double snapshotCapacity =20; double rawCapacity = 100; double systemCapacity = 1; int offset = 5; double pie1_start = 315.0; double pie1_finish = snapshotCapacity *360.0/rawCapacity; double system_finish = systemCapacity*360.0/rawCapacity; CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor greenColor] CGColor])); CGContextMoveToPoint(ctx, x+2*offset, y); CGContextAddArc(ctx, x+2*offset, y, 100, radians(snapshot_start), radians(snapshot_start+snapshot_finish), 0); CGContextClosePath(ctx); CGContextFillPath(ctx); // system capacity CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor colorWithRed:15 green:165/255 blue:0 alpha:1 ] CGColor])); CGContextMoveToPoint(ctx, x+offset,y); CGContextAddArc(ctx, x+offset, y, 100, radians(snapshot_start+snapshot_finish+offset), radians(snapshot_start+snapshot_finish+system_finish), 0); CGContextClosePath(ctx); CGContextFillPath(ctx); /* data capacity */ CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor colorWithRed:99/255 green:184/255 blue:255/255 alpha:1 ] CGColor])); CGContextMoveToPoint(ctx, x, y); CGContextAddArc(ctx, x, y, 100, radians(snapshot_start+snapshot_finish+system_finish+offset), radians(snapshot_start), 0); CGContextClosePath(ctx); CGContextFillPath(ctx); }

    Read the article

  • IE8 removes background-color of header row of Asp:Gridview

    - by Hitesh Riziya
    I am using Asp.net 4.0 GridView control to display data from database. I have applied the inbuilt theme to GridView. <asp:GridView ID="gv" runat="server" CellPadding="4" EmptyDataText="No records found." ForeColor="#333333" OnRowCommand="gv_RowCommand" Width="99%" OnPageIndexChanging="gv_PageIndexChanged" PageSize="50" AllowPaging="True" GridLines="None" AutoGenerateColumns="true"> <AlternatingRowStyle BackColor="White" /> <EditRowStyle BackColor="#7C6F57" /> <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" /> <HeaderStyle CssClass="GridHeader" BackColor="#1C5E55" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" /> <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#E3EAEB" /> <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" /> <SortedAscendingCellStyle BackColor="#F8FAFA" /> <SortedAscendingHeaderStyle BackColor="#246B61" /> <SortedDescendingCellStyle BackColor="#D4DFE1" /> <SortedDescendingHeaderStyle BackColor="#15524A" /></asp:GridView> I tried setting the CSS forcefully in my Master page .GridHeader { background-color:#1C5E55 !important;} But I am still missing the background-color. I can see the backgroundcolor applied to grid (for less-than 1 sec) while the page loading the js/css content NOTE: I already tried clearing cache of IE, ctrl + F5, shift + reload etc. Here is sample page of my issue. http://vd2.weenggs.com/Items.aspx email: [email protected] pass: test Thanks

    Read the article

  • Converting contents of a byte array to wchar_t*

    - by Christopher MacKinnon
    I seem to be having an issue converting a byte array (containing the text from a word document) to a LPTSTR (wchar_t *) object. Every time the code executes, I am getting a bunch of unwanted Unicode characters returned. I figure it is because I am not making the proper calls somewhere, or not using the variables properly, but not quite sure how to approach this. Hopefully someone here can guide me in the right direction. The first thing that happens in we call into C# code to open up Microsoft Word and convert the text in the document into a byte array. byte document __gc[]; document = word->ConvertToArray(filename); The contents of document are as follows: {84, 101, 115, 116, 32, 68, 111, 99, 117, 109, 101, 110, 116, 13, 10} Which ends up being the following string: "Test Document". Our next step is to allocate the memory to store the byte array into a LPTSTR variable, byte __pin * value; value = &document[0]; LPTSTR image; image = (LPTSTR)malloc( document->Length + 1 ); Once we execute the line where we start allocating the memory, our image variable gets filled with a bunch of unwanted Unicode characters: ????????????????? And then we do a memcpy to transfer over all of the data memcpy(image,value,document->Length); Which just causes more unwanted Unicode characters to appear: ????????????????? I figure the issue that we are having is either related to how we are storing the values in the byte array, or possibly when we are copying the data from the byte array to the LPTSTR variable. Any help with explaining what I'm doing wrong, or anything to point me in the right direction will be greatly appreciated.

    Read the article

  • Optimizing this "Boundarize" method for Numerics in Ruby

    - by mstksg
    I'm extending Numerics with a method I call "Boundarize" for lack of better name; I'm sure there are actually real names for this. But its basic purpose is to reset a given point to be within a boundary. That is, "wrapping" a point around the boundary; if the area is betweeon 0 and 100, if the point goes to -1, -1.boundarize(0,100) = 99 (going one too far to the negative "wraps" the point around to one from the max). 102.boundarize(0,100) = 2 It's a very simple function to implement; when the number is below the minimum, simply add (max-min) until it's in the boundary. If the number is above the maximum, simply subtract (max-min) until it's in the boundary. One thing I also need to account for is that, there are cases where I don't want to include the minimum in the range, and cases where I don't want to include the maximum in the range. This is specified as an argument. However, I fear that my current implementation is horribly, terribly, grossly inefficient. And because every time something moves on the screen, it has to re-run this, this is one of the bottlenecks of my application. Anyone have any ideas? module Boundarizer def boundarize min=0,max=1,allow_min=true,allow_max=false raise "Improper boundaries #{min}/#{max}" if min >= max new_num = self if allow_min while new_num < min new_num += (max-min) end else while new_num <= min new_num += (max-min) end end if allow_max while new_num > max new_num -= (max-min) end else while new_num >= max new_num -= (max-min) end end return new_num end end class Numeric include Boundarizer end

    Read the article

  • How to do an additional search on archive in rails if record not found, by extending model?

    - by Nick Gorbikoff
    Hello, I was wondering if somebody knows an elegant solution to the following: Suppose I have a table that holds orders, with a bunch of data. So I'm at 1M records, and searches begin to take time. So I want to speed it up by archiving some data that is more than 3 years old - saving it into a table called orders-archive, and then purging them from the orders table. So if we need to research something or customer wants to pull older information - they still can, but 99% of the lookups are done on the orders no older than a year and a half - so there is no reason to keep looking through older data all the time. These move & purge operations can be then croned to be done on a weekly basis. I already did some tests and I know that I will slash my search times by about 4 times. So far so good, right? However I was thinking about how to implement older archival lookups and the only reasonable thing I can think of is some sort of if-else If not found in orders, do a search in orders-archive. However - I have about 20 tables that I want to archive and god knows how many searches / finds are done through out the code, that I don't want to modify. So I was wondering if there is an elegant rails-way solution to this problem, by extending a model somehow? Has anyone dealt with similar case before? Thank you.

    Read the article

  • IndexOutOfRangeException when a stream is a multiple of the buffer size

    - by dnord
    I don't have a lot of experience with streams and buffers, but I'm having to do it for a project, and I'm stuck on an exception being thrown when the stream I'm reading is a multiple of the buffer size I've chosen. Let me show you: My code starts by reading bufferSize (100, let's say) bytes from the stream: numberOfBytesRead = DataReader.GetBytes(0, index, output, 0, bufferSize); Then, I loop through a while loop: while (numberOfBytesRead == bufferSize) { BufferWriter.Write(output); BufferWriter.Flush(); index += bufferSize; numberOfBytesRead = DataReader.GetBytes(0, index, output, 0, bufferSize); } ... and, once we get to a non-bufferSize read, we know we've hit the end of the stream and can move on. But if the bufferSize is 100, and the stream is 200, we'll read positions 0-99, 100-199, and then the attempt to read 200-299 errors out. I'd like it if it returned 0, but it throws an error. What I'm doing to handle that is, well, a try-catch: catch (System.IndexOutOfRangeException) numberOfBytesRead = 0; ...which ends the loop, and successfully finishes the thing, but we all know I don't want to control code flow with error handling. Is there a better (more standard?) way to handle stream reading when the stream length is unknown? This seems like a small wrinkle in a fairly reasonable strategy for reading streams, but I just don't know if I've got it wrong or what. The specifics of this (which I've cleaned up a little bit for posting) are a MySqlDataReader hitting a LARGEBLOB column. It's working whenever the buffer is larger than the number of returned bytes, or when the number of returned bytes is not a multiple of bufferSize. Because we don't, in that case, throw an IndexOutOfRangeException.

    Read the article

  • Entity Framework LINQ Query using Custom C# Class Method - Once yes, once no - because executing on the client or in SQL?

    - by BrooklynDev
    I have two Entity Framework 4 Linq queries I wrote that make use of a custom class method, one works and one does not: The custom method is: public static DateTime GetLastReadToDate(string fbaUsername, Discussion discussion) { return (discussion.DiscussionUserReads.Where(dur => dur.User.aspnet_User.UserName == fbaUsername).FirstOrDefault() ?? new DiscussionUserRead { ReadToDate = DateTime.Now.AddYears(-99) }).ReadToDate; } The linq query that works calls a from after a from, the equivalent of SelectMany(): from g in oc.Users.Where(u => u.aspnet_User.UserName == fbaUsername).First().Groups from d in g.Discussions select new { UnReadPostCount = d.Posts.Where(p => p.CreatedDate > DiscussionRepository.GetLastReadToDate(fbaUsername, p.Discussion)).Count() }; The query that does not work is more like a regular select: from d in oc.Discussions where d.Group.Name == "Student" select new { UnReadPostCount = d.Posts.Where(p => p.CreatedDate > DiscussionRepository.GetLastReadToDate(fbaUsername, p.Discussion)).Count(), }; The error I get is: LINQ to Entities does not recognize the method 'System.DateTime GetLastReadToDate(System.String, Discussion)' method, and this method cannot be translated into a store expression. My question is, why am I able to use my custom GetLastReadToDate() method in the first query and not the second? I suppose this has something to do with what gets executed on the db server and what gets executed on the client? These queries seem to use the GetLastReadToDate() method so similarly though, I'm wondering why would work for the first and not the second, and most importantly if there's a way to factor common query syntax like what's in the GetLastReadToDate() method into a separate location to be reused in several different places LINQ queries. Please note all these queries are sharing the same object context.

    Read the article

  • SQL Server job (stored proc) trace

    - by Jit
    Hi Friends, I need your suggestion on tracing the issue. We are running data load jobs at early morning and loading the data from Excel file into SQL Server 2005 db. When job runs on production server, many times it takes 2 to 3 hours to complete the tasks. We could drill down to one job step which is taking 99% of the total time to finish. While running the job step (stored procs) on staging environment (with the same production database restored) takes 9 to 10 minutes, the same takes hours on production server when it run at early morning as part of job. The production server always stuck up at the very job step. I would like to run trace on the very job step (around 10 stored procs run for each user in while loop within the job step) and collect the info to figure out the issue. What are the ways available in SQL Server 2005 to achieve the same? I want to run the trace only for these SPs and not for certain period time period on production server, as trace give lots of information and it becomes very difficult for me (as not being DBA) to analyze that much of trace information and figure out the issue. So I want to collect info about specific SPs only. Let me know what you suggest. Appreciate your time and help. Thanks.

    Read the article

  • Converting application to MVC architecture

    - by terence6
    I'm practicing writing MVC applications. I have a Mastermind game, that I would like to rewrite as MVC app. I have divided my code to parts, but instead of working game I'm getting empty Frame and an error in "public void paint( Graphics g )". Error comes from calling this method in my view with null argument. But how to overcome this ? MVC was quite simple with swing but awt and it's paint methods are much more complicated. Code of working app : http://paste.pocoo.org/show/224982/ App divided to MVC : Main : public class Main { public static void main(String[] args){ Model model = new Model(); View view = new View("Mastermind", 400, 590, model); Controller controller = new Controller(model, view); view.setVisible(true); } } Controller : import java.awt.*; import java.awt.event.*; public class Controller implements MouseListener, ActionListener { private Model model; private View view; public Controller(Model m, View v){ model = m; view = v; view.addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); view.addMouseListener(this); } public void actionPerformed( ActionEvent e ) { if(e.getSource() == view.checkAnswer){ if(model.isRowFull){ model.check(); } } } public void mousePressed(MouseEvent e) { Point mouse = new Point(); mouse = e.getPoint(); if (model.isPlaying){ if (mouse.x > 350) { int button = 1 + (int)((mouse.y - 32) / 50); if ((button >= 1) && (button <= 5)){ model.fillHole(button); } } } } public void mouseClicked(MouseEvent e) {} public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} } View : import java.awt.*; import javax.swing.*; import java.awt.event.*; public class View extends Frame implements ActionListener { Model model; JButton checkAnswer; private JPanel button; static final int HIT_X[] = {270,290,310,290,310}, HIT_Y[] = {506,496,496,516,516}; public View(String name, int w, int h, Model m){ model = m; setTitle( name ); setSize( w,h ); setResizable( false ); this.setLayout(new BorderLayout()); button = new JPanel(); button.setSize( new Dimension(400, 100)); button.setVisible(true); checkAnswer = new JButton("Check"); checkAnswer.addActionListener(this); checkAnswer.setSize( new Dimension(200, 30)); button.add( checkAnswer ); this.add( button, BorderLayout.SOUTH); button.setVisible(true); for ( int i=0; i < model.SCORE; i++ ){ for ( int j = 0; j < model.LINE; j++ ){ model.pins[i][j] = new Pin(20,0); model.pins[i][j].setPosition(j*50+30,510-i*50); model.pins[i+model.SCORE][j] = new Pin(8,0); model.pins[i+model.SCORE][j].setPosition(HIT_X[j],HIT_Y[j]-i*50); } } for ( int i=0; i < model.LINE; i++ ){ model.pins[model.OPTIONS][i] = new Pin( 20, i+2 ); model.pins[model.OPTIONS][i].setPosition( 370,i * 50 + 56); } model.combination(); model.paint(null); } public void actionPerformed( ActionEvent e ) { } } Model: import java.awt.*; public class Model extends Frame{ static final int LINE = 5, SCORE = 10, OPTIONS = 20; Pin pins[][] = new Pin[21][LINE]; int combination[] = new int[LINE]; int curPin = 0; int turn = 1; int repaintPin; boolean isUpdate = true, isPlaying = true, isRowFull = false; public Model(){ } void fillHole(int color) { pins[turn-1][curPin].setColor(color+1); repaintPins( turn ); curPin = (curPin+1) % LINE; if (curPin == 0){ isRowFull = true; } } public void paint( Graphics g ) { g.setColor( new Color(238, 238, 238)); g.fillRect( 0,0,400,590); for ( int i=0; i < pins.length; i++ ) { pins[i][0].paint(g); pins[i][1].paint(g); pins[i][2].paint(g); pins[i][3].paint(g); pins[i][4].paint(g); } } public void update( Graphics g ) { if ( isUpdate ) { paint(g); } else { isUpdate = true; pins[repaintPin-1][0].paint(g); pins[repaintPin-1][1].paint(g); pins[repaintPin-1][2].paint(g); pins[repaintPin-1][3].paint(g); pins[repaintPin-1][4].paint(g); } } void repaintPins( int pin ) { repaintPin = pin; isUpdate = false; repaint(); } void check() { int junkPegs[] = new int[LINE], junkCode[] = new int[LINE]; int pegCount = 0, pico = 0; for ( int i = 0; i < LINE; i++ ) { junkPegs[i] = pins[turn-1][i].getColor(); junkCode[i] = combination[i]; } for ( int i = 0; i < LINE; i++ ){ if (junkPegs[i]==junkCode[i]) { pins[turn+SCORE][pegCount].setColor(1); pegCount++; pico++; junkPegs[i] = 98; junkCode[i] = 99; } } for ( int i = 0; i < LINE; i++ ){ for ( int j = 0; j < LINE; j++ ) if (junkPegs[i]==junkCode[j]) { pins[turn+SCORE][pegCount].setColor(2); pegCount++; junkPegs[i] = 98; junkCode[j] = 99; j = LINE; } } repaintPins( turn+SCORE ); if ( pico == LINE ){ isPlaying = false; } else if ( turn >= 10 ){ isPlaying = false; } else{ curPin = 0; isRowFull = false; turn++; } } void combination() { for ( int i = 0; i < LINE; i++ ){ combination[i] = 1 + (int)(Math.random()*5); System.out.print(i+","); } } } class Pin{ private int color, X, Y, radius; private static final Color COLORS[] = { Color.black, Color.white, Color.red, Color.yellow, Color.green, Color.blue, new Color(7, 254, 250)}; public Pin(){ X = 0; Y = 0; radius = 0; color = 0; } public Pin( int r,int c ){ X = 0; Y = 0; radius = r; color = c; } public void paint( Graphics g ){ int x = X-radius; int y = Y-radius; if (color > 0){ g.setColor( COLORS[color]); g.fillOval( x,y,2*radius,2*radius ); } else{ g.setColor( new Color(238, 238, 238) ); g.drawOval( x,y,2*radius-1,2*radius-1 ); } g.setColor( Color.black ); g.drawOval( x,y,2*radius,2*radius ); } public void setPosition( int x,int y ){ this.X = x ; this.Y = y ; } public void setColor( int c ){ color = c; } public int getColor() { return color; } } Any clues on how to overcome this would be great. Have I divided my code improperly ?

    Read the article

  • g-wan - reproducing the performance claims

    - by user2603628
    Using gwan_linux64-bit.tar.bz2 under Ubuntu 12.04 LTS unpacking and running gwan then pointing wrk at it (using a null file null.html) wrk --timeout 10 -t 2 -c 100 -d20s http://127.0.0.1:8080/null.html Running 20s test @ http://127.0.0.1:8080/null.html 2 threads and 100 connections Thread Stats Avg Stdev Max +/- Stdev Latency 11.65s 5.10s 13.89s 83.91% Req/Sec 3.33k 3.65k 12.33k 75.19% 125067 requests in 20.01s, 32.08MB read Socket errors: connect 0, read 37, write 0, timeout 49 Requests/sec: 6251.46 Transfer/sec: 1.60MB .. very poor performance, in fact there seems to be some kind of huge latency issue. During the test gwan is 200% busy and wrk is 67% busy. Pointing at nginx, wrk is 200% busy and nginx is 45% busy: wrk --timeout 10 -t 2 -c 100 -d20s http://127.0.0.1/null.html Thread Stats Avg Stdev Max +/- Stdev Latency 371.81us 134.05us 24.04ms 91.26% Req/Sec 72.75k 7.38k 109.22k 68.21% 2740883 requests in 20.00s, 540.95MB read Requests/sec: 137046.70 Transfer/sec: 27.05MB Pointing weighttpd at nginx gives even faster results: /usr/local/bin/weighttp -k -n 2000000 -c 500 -t 3 http://127.0.0.1/null.html weighttp - a lightweight and simple webserver benchmarking tool starting benchmark... spawning thread #1: 167 concurrent requests, 666667 total requests spawning thread #2: 167 concurrent requests, 666667 total requests spawning thread #3: 166 concurrent requests, 666666 total requests progress: 9% done progress: 19% done progress: 29% done progress: 39% done progress: 49% done progress: 59% done progress: 69% done progress: 79% done progress: 89% done progress: 99% done finished in 7 sec, 13 millisec and 293 microsec, 285172 req/s, 57633 kbyte/s requests: 2000000 total, 2000000 started, 2000000 done, 2000000 succeeded, 0 failed, 0 errored status codes: 2000000 2xx, 0 3xx, 0 4xx, 0 5xx traffic: 413901205 bytes total, 413901205 bytes http, 0 bytes data The server is a virtual 8 core dedicated server (bare metal), under KVM Where do I start looking to identify the problem gwan is having on this platform ? I have tested lighttpd, nginx and node.js on this same OS, and the results are all as one would expect. The server has been tuned in the usual way with expanded ephemeral ports, increased ulimits, adjusted time wait recycling etc.

    Read the article

  • Android App crashing on Back Button (performResumeActivity)

    - by Rutger
    My App consists of 2 Activities at the moment. . the MAIN activity with a Gallery View . a FriendsListActivity with a ListView When the user moves away from the FriendsListActivity with the back button, and returns to the MAIN activity the following error keeps popping up in debug mode. DalvikVM[localhost:8676] Thread [<1 main] (Suspended (exception RuntimeException)) ActivityThread.performResumeActivity(IBinder, boolean) line: 2095 ActivityThread.handleResumeActivity(IBinder, boolean, boolean) line: 2110 BinderProxy(ActivityThread$H).handleMessage(Message) line: 954 ActivityThread$H(Handler).dispatchMessage(Message) line: 99 Looper.loop() line: 123 ActivityThread.main(String[]) line: 3647 Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method] Method.invoke(Object, Object...) line: 507 ZygoteInit$MethodAndArgsCaller.run() line: 839 ZygoteInit.main(String[]) line: 597 NativeStart.main(String[]) line: not available [native method] Thread [<8 Binder Thread #2] (Running) Thread [<7 Binder Thread #1] (Running) With the LogCat 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): FATAL EXCEPTION: main 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): java.lang.RuntimeException: Unable to resume activity {com.package.MAIN/com.package.MAIN.MAIN}: java.lang.NullPointerException 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2095) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2110) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:954) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.os.Handler.dispatchMessage(Handler.java:99) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.os.Looper.loop(Looper.java:123) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread.main(ActivityThread.java:3647) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at java.lang.reflect.Method.invokeNative(Native Method) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at java.lang.reflect.Method.invoke(Method.java:507) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at dalvik.system.NativeStart.main(Native Method) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): Caused by: java.lang.NullPointerException 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at com.package.MAIN.MAIN.onResume(MAIN.java:91) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1149) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.Activity.performResume(Activity.java:3833) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2085) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): ... 10 more Further info in the Variables panel states: this: ActivityThread e: NullPointerException cause: NullPointerException detailMessage: null stackTrace: null r: ActivityThread$ActivityClientRecord activity: MAIN detailMessage after one Eclipse Resume: Unable to resume activity (MAIN) The code from the FriendsListActivity looks like this public class FriendsListActivity extends ListActivity { // =========================================================== // Fields // =========================================================== private ArrayList<Friend> friends = new ArrayList<Friend>(); private FriendsArrayAdapter friendsArrayAdapter; private ListView listView; // =========================================================== // onCreate // =========================================================== @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.friends_list); registerForContextMenu(getListView()); setButtonNewFriendClickListener(); } public void generateFriendsList() { FriendsService fs = new FriendsService(this); friends = fs.getFriendsList(); listView = (ListView) findViewById(android.R.id.list); friendsArrayAdapter = new FriendsArrayAdapter( this, R.layout.friend_list_item, friends); listView.setAdapter(friendsArrayAdapter); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.friends_context_menu, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); FriendsService fs = new FriendsService(this); Friend f = new Friend(); f = friends.get(info.position); switch (item.getItemId()) { case R.id.edit: Intent i = new Intent(this, FriendEditActivity.class); i.putExtra("userid", f.userId); startActivity(i); return true; case R.id.delete: fs.deleteFriend(f.userId); generateFriendsList(); return true; default: return super.onContextItemSelected(item); } } // =========================================================== // onPause // =========================================================== protected void onPause() { super.onPause(); finish(); } // =========================================================== // onResume // =========================================================== protected void onResume() { super.onResume(); generateFriendsList(); } // =========================================================== // onStop // =========================================================== protected void onStop() { super.onStop(); } // =========================================================== // onDestroy // =========================================================== @Override protected void onDestroy() { super.onDestroy(); } // =========================================================== // Activity methods // =========================================================== private void setButtonNewFriendClickListener() { Button clickButton = (Button)findViewById(R.id.button_add_friend); clickButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(v.getContext(), FriendNewActivity.class); startActivity(i); } }); } The AndroidManifest looks like this <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.package.mypackage"> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name="com.package.mypackage.mypackage" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".FriendsListActivity"></activity> <activity android:name=".FriendEditActivity"></activity> <activity android:name=".FriendNewActivity"></activity> <activity android:name=".TakePictureActivity"></activity> <activity android:name=".FriendsService"></activity> <activity android:name=".MyService"></activity> </application> <uses-sdk android:minSdkVersion="9" /> The MAIN activity looks like this: package com.package.mypackage; import java.util.ArrayList; import com.package.domain.Domain; import com.package.service.MyService; import com.package.viewadapter.myImageAdapter; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.Gallery; import android.widget.Toast; public class myActivity extends Activity { // =========================================================== // Fields // =========================================================== private MyImageAdapter myImageAdapter; private ArrayList<Domain> domain = new ArrayList<Domain>(); // =========================================================== // onCreate // =========================================================== @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); /* Set Buttons to listen for any click event. */ setButtonFriendsClickListener(); setButtonCameraClickListener(); setButtonPreferencesClickListener(); } // =========================================================== // onStart // =========================================================== @Override public void onStart() { super.onStart(); /* Find the gallery defined in the main.xml */ Gallery g = (Gallery) findViewById(R.id.gallery); /* Show a Toast message when image is clicked */ g.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { MyImageAdapter image_ID = new MyImageAdapter(myActivity.this, position, null); if (image_ID.getItemId(position) == 0) { Toast test_toast = Toast.makeText(myActivity.this, "This is the New Image click", Toast.LENGTH_SHORT); test_toast.show(); } else { Toast test_toast = Toast.makeText(myActivity.this, "The clicked image has image number " + image_ID.getItemId(position) + " in the imageadapter.", Toast.LENGTH_SHORT); test_toast.show(); } } }); g.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) { MyImageAdapter image_ID = new MyImageAdapter(myActivity.this, position, null); Toast test_toast = Toast.makeText(myActivity.this, "The long clicked image has image number " + image_ID.getItemId(position) + " in the imageadapter.", Toast.LENGTH_SHORT); test_toast.show(); return true; } }); } // =========================================================== // onPause // =========================================================== protected void onPause() { super.onPause(); } // =========================================================== // onResume // =========================================================== protected void onResume() { super.onResume(); generateMyGallery(); } // =========================================================== // onStop // =========================================================== protected void onStop() { super.onStop(); } // =========================================================== // onDestroy // Is also called when user changes from horizontal // to vertical orientation and back // =========================================================== @Override protected void onDestroy() { super.onDestroy(); } // =========================================================== // Save and Restore UI states // =========================================================== @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); } protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } // =========================================================== // Main Activity methods // =========================================================== public void generateMyGallery() { MyService cs = new MyService(this); domain = cs.getDomainList(); // Add the new_image drawable to the ArrayList Domain d = new Domain(); d.photoLocation = "drawable"; d.photoName = "new_image"; d.extra1 = "no_text"; d.extra2 = "no_text"; domain.add(0, d); myImageAdapter = new MyImageAdapter(this, R.layout.text_overlay_image_view, domain); /* Find the gallery defined in the main.xml */ Gallery g = (Gallery) findViewById(R.id.gallery); g.setSpacing(10); /* Apply a new (custom) ImageAdapter to it. */ g.setAdapter(myImageAdapter); g.setSelection(1); } private void setButtonFriendsClickListener() { Button clickButton = (Button)findViewById(R.id.button_friends_list); clickButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { setContentView(R.layout.friends_list); Intent myIntent = new Intent(v.getContext(), FriendsListActivity.class); startActivity(myIntent); } }); } private void setButtonCameraClickListener() { Button clickButton = (Button)findViewById(R.id.button_take_picture); clickButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { setContentView(R.layout.take_picture); Intent myIntent = new Intent(v.getContext(), TakePictureActivity.class); startActivity(myIntent); } }); } private void setButtonPreferencesClickListener() { Button clickButton = (Button)findViewById(R.id.button_preferences); clickButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent myIntent = new Intent(v.getContext(), MyPreferencesActivity.class); startActivity(myIntent); } }); } }; Anyone has an idea why the App crashes. Any help is much appreciated. I did find out that, when I finish() the MAIN activity when I start the FriendListActivity and restart the MAIN activity when closing the FriendListActivity, that the crash does not occur. However, this basically restarts the App and that is not the intention. Thanks all, I got the problem solved. This is what I did. . When moving all gallery related actions to the onCreate, the creash didn't happen anymore. But then after returning to the MAIN activity, the activity wasn't shown. . I then moved all the onCreate (except the super), the generateGallery, and the onStart() to the onResume. Now it works fine!

    Read the article

  • Generating different randoms valid for a day on different independent devices?

    - by Pentium10
    Let me describe the system. There are several mobile devices, each independent from each other, and they are generating content for the same record id. I want to avoid generating the same content for the same record on different devices, for this I though I would use a random and make it so too cluster the content pool based on these randoms. Suppose you have choices from 1 to 100. Day 1 Device#1 will choose for the record#33 between 1-10 Device#2 will choose for the record#33 between 40-50 Device#3 will choose for the record#33 between 50-60 Device#1 will choose for the record#55 between 40-50 Device#2 will choose for the record#55 between 1-10 Device#3 will choose for the record#55 between 10-20 Device#1 will choose for the record#11 between 1-10 Device#2 will choose for the record#22 between 1-10 Device#3 will choose for the record#99 between 1-10 Day 2 Device#1 will choose for the record#33 between 90-100 Device#2 will choose for the record#33 between 1-10 Device#3 will choose for the record#33 between 50-60 They don't have access to a central server. Data available for each of them: IMEI (unique per mobile) Date of today (same on all devices) Record id (same on all devices) What do you think, how is it possible? ps. tags can be edited

    Read the article

  • Linear Search with Jagged Array?

    - by Nerathas
    Hello, I have the following program that creates 100 random elements trough a array. Those 100 random value's are unique, and every value only gets displayed once. Although with the linear search it keeps looking up the entire array. How would i be able to get a Jagged Array into this, so it only "scans" the remaining places left? (assuming i keep the table at 100 max elements, so if one random value is generated the array holds 99 elements with linear search scans and on...) I assume i would have to implent the jagged array somewhere in the FoundLinearInArray? Hopefully this made any sence. Regards. private int ValidNumber(int[] T, int X, int Range) { Random RndInt = new Random(); do { X = RndInt.Next(1, Range + 1); } while (FoundLinearInArray(T, X)); return X; }/*ValidNumber*/ private bool FoundLinearInArray(int[] A, int X) { byte I = 0; while ((I < A.Length) && (A[I] != X)) { I++; } return (I < A.Length); }/*FoundInArray*/ public void FillArray(int[] T, int Range) { for (byte I = 0; I < T.Length; I++) { T[I] = ValidNumber(T, I, Range); } }/*FillArray*/

    Read the article

  • What's the best Linux backup solution?

    - by Jon Bright
    We have a four Linux boxes (all running Debian or Ubuntu) on our office network. None of these boxes are especially critical and they're all using RAID. To date, I've therefore been doing backups of the boxes by having a cron job upload tarballs containing the contents of /etc, MySQL dumps and other such changing, non-packaged data to a box at our geographically separate hosting centre. I've realised, however that the tarballs are sufficient to rebuild from, but it's certainly not a painless process to do so (I recently tried this out as part of a hardware upgrade of one of the boxes) long-term, the process isn't sustainable. Each of the boxes is currently producing a tarball of a couple of hundred MB each day, 99% of which is the same as the previous day partly due to the size issue, the backup process requires more manual intervention than I want (to find whatever 5GB file is inflating the size of the tarball and kill it) again due to the size issue, I'm leaving stuff out which it would be nice to include - the contents of users' home directories, for example. There's almost nothing of value there that isn't in source control (and these aren't our main dev boxes), but it would be nice to keep them anyway. there must be a better way So, my question is, how should I be doing this properly? The requirements are: needs to be an offsite backup (one of the main things I'm doing here is protecting against fire/whatever) should require as little manual intervention as possible (I'm lazy, and box-herding isn't my main job) should continue to scale with a couple more boxes, slightly more data, etc. preferably free/open source (cost isn't the issue, but especially for backups, openness seems like a good thing) an option to produce some kind of DVD/Blu-Ray/whatever backup from time to time wouldn't be bad My first thought was that this kind of incremental backup was what tar was created for - create a tar file once each month, add incrementally to it. rsync results to remote box. But others probably have better suggestions.

    Read the article

  • Learning PHP - start out using a framework or no?

    - by Kevin Torrent
    I've noticed a lot of jobs in my area for PHP. I've never used PHP before, and figure if I can get more opportunities if I pick it up then it might be a good idea. The problem is that PHP without any framework is ugly and 99% of the time really bad code. All the tutorials and books I've seen are really lousy - it never shows any kind of good programming practice but always the quick and dirty kind of way of doing things. I'm afraid that trying to learn PHP this way will just imprint these bad practices in my head and make me waste time later trying to unlearn them. I've used C# in the past so I'm familiar with OOP and software design patterns and similar. Should I be trying to learn PHP by using one of the better known frameworks for it? I've looked at CakePHP, Symfony and the Zend Framework so far; Zend seems to be the most flexible without being too constraining like Cake and Symfony (although Symfony seemed less constraining than CakePHP which is trying too hard to be Ruby on Rails), but many tutorials for Zend I've seen assume you already know PHP and want to learn to use the framework. What would be my best opportunity for learning PHP, but learning GOOD PHP that uses real software engineering techniques instead of spaghetti code? It seems all the PHP books and resources either assume you are just using raw PHP and therefore showcase bade practices, or that you already know PHP and therefore don't even touch on parts of the language.

    Read the article

  • WP7 - group of textboxes into some sort of template?

    - by Jeff V
    I'm still pretty new at Silverlight so there might be a way to do this, but I'm just unfamiliar with the terminology... I basically have this grouping of textboxes and textblocks and I would like to repeat this same grouping whenever the addNew button is clicked. Is there a way to do this by creating some sort of template? Or do I have to add each item individually. <Grid> <toolkit:ListPicker Height="70" HorizontalAlignment="Right" Name="listPicker1" VerticalAlignment="Top" Width="56" ItemTemplate="{StaticResource PickerItemTemplate}" FullModeItemTemplate="{StaticResource PickerFullModeItemTemplate}" Margin="0,97,167,0"></toolkit:ListPicker> <TextBlock Height="33" HorizontalAlignment="Left" Margin="10,7,0,0" Name="tbDate" Text="Date:" VerticalAlignment="Top" Width="266" /> <TextBlock Height="42" HorizontalAlignment="Left" Margin="9,55,0,0" Name="tbItem" Text="Item:" VerticalAlignment="Top" Width="90" /> <TextBox Height="75" HorizontalAlignment="Left" Margin="92,33,0,0" Name="tbItemName" Text="" VerticalAlignment="Top" Width="341" /> <TextBlock Height="42" HorizontalAlignment="Left" Margin="5,118,0,0" Name="tbServing" Text="Serving:" VerticalAlignment="Top" Width="99" /> <TextBox Height="70" HorizontalAlignment="Left" Margin="90,96,0,0" Name="tbServingValue" Text="" VerticalAlignment="Top" Width="75" /> <TextBlock Height="42" HorizontalAlignment="Left" Margin="156,120,0,0" Name="tbUOM" Text="UOM:" VerticalAlignment="Top" Width="60" /> <Button Content="" HorizontalAlignment="Right" Height="63" Margin="0,100,13,0" VerticalAlignment="Top" Width="132" RenderTransformOrigin="0.455,0.286" Style="{StaticResource wp7_buttonAddNew}" x:Name="btnAddNewItem" Click="btnAddNewItem_Click"/> </Grid> Thanks!

    Read the article

< Previous Page | 65 66 67 68 69 70 71 72 73 74 75 76  | Next Page >